0
\$\begingroup\$

I have the following code for currency formatting

boolean isNegative = probe.nl_price!=null && probe.nl_price.signum() == -1;
String str = "Price: " + (isNegative ? "-" :"") + "$" + FormatUtils.getFormatInstance().format(probe.nlr_price.abs())

Is there more elgant way to rewrite it?

\$\endgroup\$
2
  • \$\begingroup\$ Can you provide also the probe class together with the nl_price and nlr_price with some explication? It's also strange that you don't use the getters for last 2 classes but acces the variable directly. I have a feeling that we can refactor there so this can be better. \$\endgroup\$
    – chillworld
    Commented Jan 22, 2016 at 12:26
  • 1
    \$\begingroup\$ If probe.nl_price is null, a NullPointerException will be thrown at probe.nlr_price.abs(). So checking for it before for the sign is useless. \$\endgroup\$
    – Tunaki
    Commented Jan 22, 2016 at 14:55

1 Answer 1

1
\$\begingroup\$

You could use an optional if you are using java 8. It would be nice to have all the code though.

 String sign = Optional.ofNullable(probe.nl_price)
                             .filter(p -> p.signsum() == -1)
                             .map(p -> "-")
                             .orElse("");
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.