Sunday 17 March 2013

Exception.when, for more readable and maintainable code

I recently started using a small change in my Java coding that seems to improve readability, testability, and makes maintenance a lot easier.

Instead of using IF statements everywhere to check and then throw business exceptions, I now modify  my Exceptions and call "Exception.when(...)".

So this...

User user = userService.getUser(userId);
if(!user.isLoggedIn()){
 throw new MyBusinessException("User is not logged in");
}

becomes...
 
User user = userService.getUser(userId);
MyBusinessException.when(!user.isLoggedIn(),"User is not logged in");

It really is a lot easier to read the code when written like this.

The changes to your Exception class are easy too. All we are doing is hiding the conditional inside a static function. Just add a method like this...

static void when(boolean condition,String msg){
 if(condition){
  throw new BusinessException(msg);
 }
}

I am mostly using this with a RESTful system based on JAX-RS, and I have to do a lot of condition checking,which was becoming a nightmare to read with all those IF statements. Now, it reads like a dream, well, rather like proper English, so a perfect DSL.

FYI: I did look into everything I could think of to make it easier to implement, ie: generics, inheritance, etc. But you cannot use static methods in either interfaces or abstracts, and exceptions are blocked from generics. So we are stuck implementing this method in every Exception Class, but I think it is worth it.



No comments:

Post a Comment