The try catch vs checks conundrum

4/22/2015 03:29:00 PM

HTML Script Banner


This is a discussion that will, at some point, come up between colleagues. Should I use checks null checks on everything in a function or just solve the entire thing by putting a try { } catch {} block around the entire function and get it over with.

A simple example would by:

  public String doThisFunction(Object parameter) {  
     if(parameter != null) {        
       return parameter.getName();  
     }  
     return null;  
  }  

VS

  public String doThisFunction(Object parameter) {      
     try{  
       return parameter.getName();  
     }  
     catch(NullPointerException e) {  
       return null;  
     }  
  }  


Basically you create a function and you expect the one to use it later on (if you are in a team) to responsibly use your function and prevent sending null objects. On the other hand you want/need to provide robustness in your code so the application doesn't just crash.

Both will work and in the end the functions will always return the same thing in either case, whether someone sends a null object or a correct value. So which one is the correct way to go?

I believe that in this case we need to look at readability of the code for others rather than functionality . When a new developer joins the team, which one will be more easy to understand? In this example both are equally readable, it is quite clear why the exception is thrown and how it is caught.
But when we look at big chunks of code it is a lot harder to discern where the exception is caught and why, for example:

  public Boolean doThisFunction(Object parameter, Object parameter2) {      
     try{  
       parameter.setName(parameter2.getName());  
       return true;    }  
     catch(NullPointerException e) {  
       return false;  
     }  
  }  

In this example it is not clear which object throws the exception and for a new developer the reason why this is thrown is not clear either. We can make this more readable by writing the code like this:

  public Boolean doThisFunction(Object parameter, Object parameter2) {      
     if(parameter != null && parameter2 != null && parameter2.hasName()) {  
       parameter.setName(parameter2.getName());  
       return true;   
     }     
     return false;  
  }  

In this example we can discern that both objects should not be null and parameter 2 needs to have a name for this function to do something useful.

In the end this does not change the outcome or how the function works, just the convention and readability. The choice of how to proceed needs to be discussed within the team and decisions need to be made...

You Might Also Like

0 reacties