Friday, April 6, 2012

Better Coding: Dealing with Exceptions

During code reviews or debugging sessions, i always find new programmers having a hard time trying to deal with exceptions especially when the compiler forces you to do something with them. And the thing with exceptions is that if you don't handle them properly, you might have a hard time trying to debug your programs.

What are exceptions anyway?
Exceptions are conditions that change the normal flow of the program, they are usually in reponse to some part of the code having an unexpected error that the programmer needs to handle. Things like when you are reading a file you might get an IOException when something went wrong with IO operations, or when you are converting from a String to a number, you will get a NumberFormatException when the string is not a number.

So what are some wrong ways to handle them,

Don't just print the stacktrace.
IDE's tries to be helpful and will help you to automatically write the "try catch" block statements, and they will usually put in a e.printStackTrace() for you.

public void readAFile(){
    try{
        //Some code that tries to open and read a file
    }catch(IOException e){
        e.printStackTrace();
    }
}
What most people do after that is to forget about it. Printing out stacktraces usually is not advised, hackers can find out what your application does in the back end, and sometimes if you are not careful, SQL errors are printed out and the hackers can devise an attack based on SQL Injection.

Do Nothing!

public void readAFile(){
    try{
        //Some code that tries to open and read a file
    }catch(IOException e){
       //Do nothing;
    }
}


And then we are left scratching our heads what went wrong with the program because nothing was print out when there was an error! These are they type of errors that can make you stay up late in the office, because you simply can't see what went wrong from the UI, console or the logs.

So what should you do?

Rethrow the exception if the class can't handle it.

It is likely that your method might not be the best place to handle the exception, so you rethrow to the calling method to handle it.

Example: The FileLoader class tries to readAFile but things do go wrong when reading a file, but the FileLoader is probably not the best place to handle the error. The calling class and method would like to know when there is an error so that they can either do some remedy action, inform the user or log it. In this case SomeUIClass is trying to read the file and when FileLoader throws the exception, a messagebox comes out and logs the error to the log file.


  public class FileLoader{  
      public void readAFile(File f) throws IOException{  
           //file reading code  
      }  
 }  
 public class SomeUIClass{  
      public void readFile(File f){  
           try{  
                FileLoader.readAFile(f);  
           }catch(IOExecption e){  
                //Print some message to the UI to inform the UI that it failed to read a file  
                //Maybe log something to the log file  
           }  
      }  
 }  
>

Rethrow a more generic exception.


We all like to "program to an interface", but sometimes programming to an interface can be made challenging if we rethrow a checked exception. An example.

Let say we have an interface called BooksDao. It is an Data Access Object used to retrieve books. So we have an implementation called JDBCBookDao that retrive books that is stored in a relational database using SQL. So there is a chance that it will throw a SQLException when trying to retrive some data.


public interface BooksDao{  
      public List getBooks(String query);
 }  
 public class JDBCBooksDao implements BooksDao{  
      public List getBooks(String query){  
           try{  
                //Some JDBC code
           }catch(SQLException e){  

           }  
      }  
 }  



But you see what happens if there is an error, it would be quite hard to tell the call method that an error has occured. But if we rethrow the SQLException like the previous rule then we are saying that all implementations of BooksDao.getBooks needs to throw an SQLException.


public interface BooksDao{  
      public List getBooks(String query) throws SQLException;
 }  


What if we change the implementation of BooksDao to a MongoDBBooksDao ? and the MongoDB api dosen't throw an SQLException but throw a MongoDBException, we will be force to convert whatever exception that MongoDB has to an SQLException.


public class MongoDBBooksDao implments BooksDao{
 public List getBooks(String query)throws SQLException{
  try{
   //Some MongoDB api
  }catch(MondoDBException e){
   throw new SQLException(..);
  }
 }
}


The trick here is to create your own exceptions for your classes, this makes it easy to handle the different exceptions that the various underlying implementations can throw. All you need to do if just to re-throw the specific exception like SQLException to your custom exception.

public interface BooksDao{  
      public List getBooks(String query) throws DataException;
}  

 public class JDBCBooksDao implements BooksDao{  
      public List getBooks(String query) throws DataException{  
           try{  
                //Some JDBC code
           }catch(SQLException e){  
    throw new DataException(..);
           }  
      }  
 } 

public class MongoDBBooksDao implments BooksDao{
 public List getBooks(String query)throws DataException{
  try{
   //Some MongoDB api
  }catch(MondoDBException e){
   throw new DataException(..);
  }
 }
}

See it now looked much neater, what you should also consider is whether to re-throw all checked exceptions into unchecked exceptions. One limitation of Java is that if you throw a checked exception you need to declare it in the method, for unchecked you need not and it makes your interface cleaner because it does not need to depend on the exception. However you will need to make a conscious effort to try and catch the exception in your code. There are lots of debate on whether checked exceptions are better or not, i leave that up to you. My preference is that if you can throw an unchecked exception.


Thursday, January 5, 2012

Hadoop World videos

Hadoop World videos can be found here  http://www.cloudera.com/resources/Hadoop+World/. Seems like I will be spending some time watching these for the next few weeks.

Thursday, December 29, 2011

Bing 2.0 API is useless

Bing's 2.0 Search API is basically useless. The results dosen't match up with the Bing.com website and so testing is almost impossible.

And worse the results returned by the API are mostly irrelevant. I think Microsoft needs to seriously look at what are they targeting the Bing API for. Because as a developer i won't want to use it.

But there is a lack of freely available search apis out there.
Google Custom search requires you to search only specific websites that you specify and not google itself.
Yahoo BOSS requires payment so its out for me.

Anyone knows of what other options are out there?

Links to the issue:
Stack Overflow
Bing Community 

Wednesday, December 14, 2011

Sheevaplug Debian Install

Upgraded from the default Ubuntu install to Debian today, mainly followed the instruction by Martin Michlmayr. Mostly worked but the instructions for after installation of Debian to the MMC card was slightly different for mine.

These are the ones that worked for me.

setenv bootargs_console console=ttyS0,115200
setenv bootcmd_mmc 'mmcinit; ext2load mmc 0:1 0x00800000 /uImage; ext2load mmc 0:1 0x01100000 /uInitrd'
setenv bootcmd 'setenv bootargs $(bootargs_console); run bootcmd_mmc; bootm 0x00800000 0x01100000'
saveenv

The main difference is the mmcinit command, on my uboot it was "mmcinit" together, for the instructions that Martin gave was "mmc init" with a space.

Monday, July 25, 2011

Product Owner's Guide - Breaking down estimates



Overhead this while at work.


"The Product Owner wants us to break down our inital estimate on the development effort into parts like analysis, design and coding ...".


That sounds to me like the Product Owner(PO) thinks that whatever estimate that the team came up with is too long and wants to cut the estimate. If the team gives such such a breakdown, then be prepared for the negotiation about the time needed for the project to be discussed.


But how is the team going to come up with such a figure anyway? I always found the statement like "Most of the time is spent in design but little in coding", or using the 80-20 rule that 80% is spent in design and 20% in coding. Is that statement still relavant today? In the past (I mean way way past), people do spent a lot of time in design because computers process ur programs in batches and you better get it right the first time if not you wait a day for the next run.


Fast forward to today, where we have powerful ides, programs run almost instantly, where you can code a little, test a little, you are more likely to try a program a vertical slice and then build up your system from there, with refactoring tools so powerful, changing methods, implementing interfaces no longer is such a chore.


 Now back to the story, not matter what the project team tries to justify their number the PO will just try to cut it. The problem with most people is that they have some prenotion of when the project will end, but they do not realised that an estimate is just that, an estimate, it's a educated guess base on whatever information you have. An estimate is not an accurate prediction of the future and couple with the fact that software estimates are usually wrong. Steve McConnell says it well in his book Software Estimatation.

"Estimation should be treated as an unbiased, analytical process;
planning should be treated as a biased, goal-seeking process"

So if you ask someone for an estimate, you are asking for his opinion on how long it will take, and you shouldn't try to cut his estimate down.

More likely is the product owner is trying to get a plan from the team not an estimate, and the team's estimate isn't matching his plan. His plan can be anything, could be trying to meet some timeline for marketing, or some trade show demo.


  Product Owners please just tell the team what is your plan, it may be because of marketing, budget and other reasons that you need to slim it down. But please tell the real reason and not by trying to get the estimate within your plan.


  For the development team, try to find out the underlying reason for doing such an exercise, buy a copy of Steve McConnell Estimation book and give it to him. Negatiate on the scope, not all features need to be a mercedes, sometimes a vespa is good enough.


  The only thing that can be reliably cut down to meet the target is actually the scope of the project. Does the Product Owner need 100% of all the features of the software to be done to be really useful? More likely than not something like 50-70% will probably be good enough.


Main takeaway - Estimation and Planning are 2 different things, try to make sure what is it you are talking about.


   

Thursday, April 28, 2011

Expanding your toolbox - Picking a new language to learn.

Image: graur razvan ionut / FreeDigitalPhotos.net
One day a developer on my team came up to me and asked, what should he programming language should he learn next to be marketable (and by the way he also thinks that Java is slowly dying).

Well as to whether Java is dying a not, I don't think so, a quick check with TIOBE shows that Java is still ranked among the top few languages and lots of places still runs Java. So i do have a job for the next few years.

But the thought came to me, it is worth learning things that are marketable or should you learn things that broaden your knowledge? What's your take on it? Should you expand your toolbox or have more of the same tools?

Steamhead takes the languages from Seven Languages in Seven weeks and puts it into a nice flow chart. I think all should go check that out and pick something out from that list. After doing quite a lot in Java I begin to appreciate the simplicity of using interpreted languages like  python and php, and the fact that their frameworks are usually simple as compared to Java ones where sometimes we descend into XML configuration hell.

Steve Yegge has a interesting way of categorizing the various languages, he breaks them down into Nouns (Java, C# or OO languages), Verbs (LISP, Clojure or Functional Programming) and Verbs and Nouns (Scala, Ruby, Python, C++ or a Mixture of both).

Well for me I am more for the expand your toolbox model, go learn something that makes you have a new way of looking at things. A lot of people learn languages but they don't really learn design, think stuff like design patterns (Gang of Four, Java EE Design ...), SOLID principles, OO Metrics. Even if you know the syntax, you simply can't write maintainable programs and all you write lacks a certain craftsmanship to it.

By learning a different language and looking at the api, you can have a different idea about how to design your programs. An example will be like in Java. You have Math.abs a static function to get the absolute value of a number, have you ever wonder why its so "un OO" like? Compare with Ruby its just number.abs(), simple and elegant and fits into the OO paradigm.

In short

If you know Java, C# go learn Lisp Dialects (Common Lisp, Clojure), Haskell, Ruby, Python...

If you know Python, Ruby, you are pretty much there, since you straddle the limits between the 2 kingdoms.

If you know Common Lisp, Clojure, dont bother learning any other thing since you will think why in the world Java, C# programmers are typing so much code and configuring so much XML.

If in doubt just learn PHP to be marketable :)





Wednesday, February 2, 2011

One hour early a day...

My latest read is Robin Sharma's book (The Leader who had no title), interesting read. But one statement struck me (I more or less paraphrase it)

"If you wake up one hour early each day for a month, in 30 days you will have almost one weeks worth of working time, think of the things you could do"

When i told this to some of my colleagues/friends they say wha sleep less one hour how ? Not enough time to sleep already.

"You have enough time to sleep when you are dead" 

I guess this is the difference between people who do impressive/great things (physically fit, be it in doing voluntary work, open source projects, making lots of money, hobbies, making a difference, side business, execise often) and the rest of us. They spent the time not just dreaming and talking about it but actually doing it. I am not actually saying that you forgo sleep altogether but think of the possibilities that could happen if you think about how to spend your time wisely.

At the end of our life, lets not spend time regretting what it might have been, or what we might have done better.

Remember the saying that you need 10,000 hours to become good at what u do, maybe i should start doing things instead of writing things on my blog :)