Wednesday, February 24, 2010

Python 3 I/O

I came across this useful page that helps you understand whats new in Python 3 I/O and what are all the significant performance enhancements you can achieve/expect.

Returning an empty collection instead of null

For one of my recent projects, I had to work with legacy code. There were methods that are returning collections, like lists or sets. These collections were created by reading data from the database. Whenever there is no data to form the collection, these methods return null. Now that is bad!

One of the issues of returning null is that the caller always have to check for null. Most of the time the caller either searches for a particular value in the returned collection or iterate through the elements in the returned collection. The code will look like this:

List rows = myDao.getRowsFor("key");
if(rows != null) {
  for(Row row:rows) {
    // Do something with the row

As you can see, it is easy to avoid the null pointer check if the getRowsFor() returned an empty list instead of a null pointer when there is no data in the database.

The clutter caused out of the null pointer checks all over the code. You can read more about this simple principle in Effective Java and an excerpt of that can be found here.