mercoledì 23 gennaio 2013

Autoboxing pitfalls

  1. Use carefully Boolean in setter method for boolean attribute:
EXAMPLE :
DON'T DO THIS (throws null pointer exception):

public
class BooleanMethod {
boolean attribute = false;
/**
*
@return the attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
*
@param attribute the attribute to set
*/
public void setAttribute(boolean attribute) {
this.attribute = attribute;
}
public static void main (String [] args) {
BooleanMethod obj =
new BooleanMethod();
Boolean condition =
null;
obj.setAttribute(condition);
System.
out.println(obj.isAttribute());
}
}


Exception in thread "main"
java.lang.NullPointerExceptionat BooleanMethod.main(BooleanMethod.java:23)

BETTER

public
class BooleanMethod {
boolean attribute = false;
/**
*
@return the attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
*
@param attribute the attribute to set
*/
public void setAttribute(boolean attribute) {
this.attribute = attribute;
}
public static void main (String [] args) {
BooleanMethod obj =
new BooleanMethod();
Boolean condition =
null;
if (condition != null){
obj.setAttribute(condition);
}
System.
out.println(obj.isAttribute());
condition = Boolean.
TRUE;
if (condition != null){
obj.setAttribute(condition);
}
System.
out.println(obj.isAttribute());
}
}