So, after considering code blocks yesterday, what about another bane of Java life, nulls. How could they be simplified in a Java-friendly style?
Here's the use case I'm trying to solve:
public isFromBritain(Profile profile) {
if (profile != null) {
Person person = profile.getPerson();
if (person != null) {
Address address = person.getAddress();
if (address != null) {
return "GB".equals(getCountry());
}
}
}
return false;
}
And here is my proposed solution for JDK1.6:
public isFromBritain(Profile profile) {
return profile#getPerson()#getAddress()#getCountry()#equals("GB");
}
A bit surprising at first glance, yet much much simpler to read and understand. I'm using # to indicate "ignore null for now and continue processing". I used # as javadoc already uses it instead of a dot. Implementation-wise, the compiler would expand it to the former use-case, so no big issues there.
By the way, this series of entries is inspired by Graham Hamilton's blog about boilerplate Java code. I'm just trying to show what gets in my way, and provide a Java-style (not Ruby/c#/python/... style) solution. As always, opinions welcome :-)