Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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.



Wednesday, 28 January 2009

Banned Characters in Cookies in Tomcat

I was recently asked to look into why we had a problem with "[]" (square brackets) that were being passed to us as part of an affiliate id, eg: "SF_1234_[345]".


It seems we were saving the value to a cookie. This works fine if you check the cookie values in the browser. However, when we tried to pull the value in Tomcat, it got truncated to "SF_1234_"


After some painfull research... I finally found a page on the Tomcat buglist that clarifies the issue, and breaks down the RFCs to manageable information.


The upshot it quite simple.


The following characters should never be used in an unquoted cookie value.


()<>@,;:\\\"/[]?={} \t


While they will work on some systems, anything that implements the RFC properly will break. As happened to us with Tomcat.