6

I'm still learning Java, and I've been reading articles on several sites. I found an article at Java Code Geeks that I have a question about. The article is explaining open/closed principle. The article uses a scenario of applying a discount to a company's product for it's example. The first part of the code is as follows:

import java.math.BigDecimal; import java.math.RoundingMode; public class Discount { public BigDecimal apply(BigDecimal price) { BigDecimal percent = new BigDecimal("0.10"); BigDecimal discount = price.multiply(percent); return price.subtract(discount.setScale(2, RoundingMode.HALF_UP)); } } 

The second part of the code is as follows:

import java.math.BigDecimal; public class DiscountService { public BigDecimal applyDiscounts(BigDecimal price,Discount discount) { BigDecimal discountPrice = price.add(BigDecimal.ZERO); discountPrice = discount.apply(discountPrice); return discountPrice; } } 

On Oracle's site, it says that the ZERO in BigDecimal has a a value of 0 and a scale of zero. Does this mean that in price.add(BigDecimal.ZERO) we are simply adding 0 to the price that's brought in? If so, why? Or is it there simply to drop the decimal places from the price? Or is there some other purpose for it?

Thanks!

0

1 Answer 1

4

price.add(BigDecimal.ZERO) is being used to create a new BigDecimal since BigDecimal doesn't have a copy constructor.

As to why, this is presumably a defensive copy in case the BigDecimal being passed in is actually a "sabotaged" version (because BigDecimal isn't final) whose value can be changed after the fact. This is talked about in depth in Effective Java as the item "Make defensive copies when needed;" Item 39 in 2nd edition or Item 50 in 3rd Edition.

Sign up to request clarification or add additional context in comments.

8 Comments

@David: Makes sense what Pwerlord is saying, but if are still curious then best is to put a comment on the article and if you can get lucky and author replies.
@Powerlord Hmm, that seems to be what they are doing, but it's still pretty strange because even if it were sabotaged, SabotagedBigDecimal.add(BigDecimal bd) could've been overridden to return this.
@xtratic That's actually a good point. They should have done BigDecimal.ZERO.add(price) which would return a standard BigDecimal.
@Powerlord I think the consensus here is that bigDecimal.add(BigDecimal.ZERO) is pointless and confusing, not expressing the true intent.
@Taslim Exactly bigDecimal.add(BigDecimal.ZERO) doesn't express that the intent is just to make a defensive copy. (hence why it confused OP)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.