Guava: Defensive coding with Preconditions class



Basic idea behind Defensive coding is not making any assumptions while writing the code and escalating the problem in it's early stage (known as fail fast technique).

This is very simple and effective technique for securing your code from unseen defects.

Guava provide very useful utility class Preconditions for these type of check.


   public static void salaryHike(User user, float salaryHike){
        Preconditions.checkNotNull(user);
        //assuming user will never demoted :)) 
        Preconditions.checkArgument(salaryHike > 0, "salary hike must be positive"); 
        Preconditions.checkState(Validator.validateUser(user), "User is not valid");
        user.salary = user.salary + salaryHike;
    }


Comments

Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

CSS Specificity

Application Design Notes