Rule java:S2129 says don’t use constructors when you can use valueOf() instead. Okay, we get that for those boxed types, constructors are quite out-of-date and should never be mentioned in modern circles. But there’s a subtle issue with BigDecimal, which includes a “scale” component.
The most efficient way (I’ve done tests) to make a BD with exact control of scale is with the 2-arg form of BigDecimal.valueOf(). The problem is, it’s hard to read! Which of these identical constants is easier to read?
BigDecimal.valueOf(100,4)
BigDecimal.valueOf(.01).setScale(4)
new BigDecimal(“0.0100”)
Unfortunately, Java doesn’t have a String form of valueOf(). So for literal constants, our policy currently is:
Use form (1) if you’re defining a constant or something which you can follow with something like // = 0.0100
Use form (3) if it’s part of a larger expression, where adding such a comment would just get in the way.
Thanks a lot for your feedback! I would say that your problem looks like a clear case for creating custom rule. You can read how to do it here.
Hope this suggestion fits you. Contact us in case of any questions.
Well this isn’t really a case for a custom rule, because I’m not asking for issues to be flagged. I’m asking for issues NOT to be flagged, basically another exception to the rule. There are already at least two explicit exceptions: 1) BigDecimal(double), and 2) BigInteger(String) where the integer in the String is too long. I’m assuming from (2) that it works for BigDecimal as well (and is just not listed) but I’m pointing out there’s a valid reason to use the BigDecimal(String) constructor even for short strings.
Ok, thanks. I’ve looked at the rule implementation and can say that we indeed already have this exception. So new BigDecimal(“0.0100”) doesn’t raise issues. I can add this case to exceptions list in the rule’s specification.