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());
}
}

1 commento:

  1. The casino was raided by an agent on July 18
    A man with a 넷마블 바카라 gambling license in Oklahoma has been melbet arrested on charges that 토토 사이트 직원 모집 the gambler stole $3 million 토토 꽁머니 of cash and other merchandise. 알바로 모라타

    RispondiElimina