Saturday, November 9, 2013

Coding patterns - coding a method that always throws an exception


 
Sometimes we have a method that does some business logic and it 
always throws a known exception. One example can be if a user tried
to login unsuccessfully, we want to log that information and 
always throw a custom exception which the clients catch and handle
accordingly. In such case there is a simple coding pattern that 
makes the code look cleaner. 
This is an example without the coding pattern applied. See below with 
the pattern.

public void  handleLoginFailure(String CustomExceptionMessage) 
                                         throws CustomException{
 //do some logic before throwing the CustomException
 throw new CustomException(CustomExceptionMessage);
}

public void testMethod() throws CustomException{
 handleLoginFailure("username and password invalid"); 
}

This is an example with the coding pattern applied. Now someone 
reading testMethod() knows that handleLoginFailure() always throws 
an exception thus simplyfing the code readability.
public CustomException handleLoginFailure
                         (String CustomExceptionMessage) {
 //do some logic before throwing the CustomException
 return new CustomException(CustomExceptionMessage);
}

public void testMethod() throws CustomException{
 throw handleLoginFailure("username and password invalid"); 
}

No comments:

Post a Comment