Archive for July, 2008

Autoboxing/Unboxing – be careful!

July 28, 2008

I found interesting thing using Autoboxing/Unboxing in Java 5.

I’ve got a function
String toYesNo(boolean parameter) {
if (parameter)
return “Yes”;
else
return “No”;
}
When I pass Boolean instead of boolean to it and occasionally this Boolean is null:
Boolean b = null;
toYesNo(b);
The function produces a NullPointerException 😦
It’s logical, but it’s bloody unfair!!!!!!

Using enum in switch statement

July 15, 2008

In CRUD web application I often use search forms and search criteria. I found that using enum to keep the list of search fields helps scalability and future support of the software.

public static enum FieldList {
FIRST_NAME, LAST_NAME, ORGANIZATION, EMAIL
};

then I put search fields list into request in Struts action:

List<FieldList> list = new ArrayList<FieldList>();
for (FieldList field : FieldList.values()) {
list.add(field);
}
request.setAttribute(“contactSearchFieldList”, list);

then I parse user’s input in Struts form:

public ContactCriteria parseCriteria() throws IllegalArgumentException {
ContactCriteria criteria = new ContactCriteria();
parsedCriteria = “”;
if (!(empty(searchField.name())) && !(empty(searchTerm))) {
switch(searchField) {
case FIRST_NAME:
criteria.setFirstName(searchTerm);
case LAST_NAME:
criteria.setLastName(searchTerm);
case ORGANIZATION:
criteria.setOrg(searchTerm);
case EMAIL:
criteria.setEmail(searchTerm);
}
parsedCriteria += searchField + ” = ” + “‘” + searchTerm + “‘”;
} else
throw new IllegalArgumentException(“Please set Contact search parameters properly”);

Note that if I qualify class name for the enum like FieldList.FIRST_NAME, I’ll get “The enum constant FieldList.FIRST_NAME reference cannot be qualified in a case label.” compilation error