Tuesday, October 2, 2012

Programmer Tip: #1 Constants First

Based on my experience, programmers always commit this mistake in using constants in the code. I always see this problem even in large projects made by experienced programmers. So I decided to choose this topic for my first blog. Check this code.

public static final String CONSTANT_VALUE = "Value";
    
public static boolean functn(String compare) {
    if(compare.equals(CONSTANT_VALUE)) {
        return true;
    }
    return false;
}

Did you notice something wrong with this code? Well, Yes you're right. What if a null value is passed to the functn method? This code will produce a NullPointerException. So to avoid getting a NullPointerException some programmers will check if the passed value is null or add some try-catch to handle the exception like this

public static final String CONSTANT_VALUE = "Value";
    
public static boolean functn(String compare) {
    if(compare != null 
       && compare.equals(CONSTANT_VALUE)) {
        return true;
    }
    return false;
}

public static boolean functnWithTryCatch(String compare) {
    try {
        if(compare.equals(CONSTANT_VALUE)) {
            return true;
        }
        return false;
    } catch (NullPointerException e) {
        return false;
    }
}

Note: declare your constant variables as "static"

The right way of doing it is just to put the constant variable first and make the "compare" the parameter in your operation. This is because the constant variable always has a value and will never turn to null. Even if the passed parameter is null, this will not produce any NullPointerException and behave properly. See example below

public static final String CONSTANT_VALUE = "Value";
    
public static boolean functn(String compare) {
    if(CONSTANT_VALUE.equals(compare)) {
        return true;
    }
    return false;
}

Notice that the code is now: if(CONSTANT_VALUE.equals(compare))

Hope you learned something. Sorry if the design and the words used is not that good. Busy eh :p I'll improve this page pag di na ako busy. Thanks ;)

No comments:

Post a Comment