jsf - Java null checks on Javabean nested attributes -
i'm working bigdecimal calculations , read it's better check null surround try catch. example:
private bigdecimal computespringrateboltwasher() { if (boltwasher.getmaterial().getelastic_modulus() != null) { bigdecimal term1 = boltwasher.getmaterial().getelastic_modulus().multiply(bigdecimal.ten); // other equations return results; } return null; }
but here nullpointerexception because bolt washer's material null. how cleanly check null on material on elastic modulus?
does boil down this? i'll have few other attributes in method i'll need check , messy.
private bigdecimal computespringrateboltwasher() { if (boltwasher.getmaterial() != null) { if (boltwasher.getmaterial().getelastic_modulus() != null) {
edit
the reason return null in facelets page, if not input values have been entered results page shows ? (with omnifaces coalese)
bolt washer spring rate = <h:outputtext value="#{of:coalesce(controller.boltanalysis.jointstiffness.boltwasherspringrate, '?')}"> <f:convertnumber minfractiondigits="7" /> </h:outputtext>
simplify code, (extract boltwasher.getmaterial() new variable, code more readable). if writing api or application provide validations, apache commons comes in handy. this, see comments in code:
import org.apache.commons.lang3.validate; import java.math.bigdecimal; /** * */ public class { private bigdecimal anything; public void setanything(bigdecimal anything){ this.anything = anything; } /** * computespringrateboltwasher. explain method intended do. * * @return result of calculation * @throws nullpointerexception when null, explain other fields cause exception */ public bigdecimal computespringrateboltwasher() { validate.notnull(this.anything, "anything must not null"); //validate.notnull(somethingelse, "something else must not null"); bigdecimal term1 = this.anything.multiply(bigdecimal.ten); //do more things term1 , return result return term1; } public static void main(string[] args){ any = new any(); any.setanything(new bigdecimal(10)); bigdecimal result = any.computespringrateboltwasher(); system.out.println(result); any.setanything(null); result = any.computespringrateboltwasher(); system.out.println(result); } }
this produce following ouput (you decide catch runtime exception)
exception in thread "main" java.lang.nullpointerexception: must not null @ org.apache.commons.lang3.validate.notnull(validate.java:222) @ any.computespringrateboltwasher(any.java:20) @ any.main(any.java:36)
Comments
Post a Comment