About Me

My Photo
I am a Software Architect and Developer based in Bangalore, India. I have experience in building (scalable) applications using Java, JSP, JSF, JBoss Drools, Spring Framework, Hibernate, Ajax, JavaScript, MySQL, NoSQL (HBase, Project Voldemort). I am also a fan of Ruby on Rails, and have done some experimental work with it.

Sunday, August 31, 2008

Respect the contract

If an API ( a method in Java class) declares that its going to return a value of certain type, it must always return a value of that type and should never return any other value such as "null". Many times when we are using API written by somebody else, we inadverently end up writing code like following:

List aList = someClass.getTheList();
if (aList != null) {
// do something with aList
}

This happens because the API can null to mean that it did not find any data to return. Instead it should return an empty list.


List getTheList() {
List returnValue = null;
//Do something to fill the list, get it from DB or external source
if (returnValue == null) {
returnValue = new ArrayList();
}
return returnValue;
}


If every API developer respects the interface contract, then, the API user's code will become lot more easier to understand and can avoid unnecessary checks to avoid Null pointer excpetions (NPE)

No comments: