вторник, 9 ноября 2010 г.

Simplify if

From time to time we write unoptimized code. For program to be cute it is fun to be optimized.
For example this is a possible way to write if sequence:

if (p.equals("Completed")){
return true;
} else {
return false;
}

But to be optimized the method body should look like this:

return "Completed".equals(p);


What's really interesting is that it's not only looking good. Indeed it helps you to evade null pointer exception in case when p equals null. We are not able to call method from null - it'll throw exception, but when using equals() method this would be processed correctly.

To study this in depth we can explore StringUtils.java (the one that is in org.apache.commons.lang package).


public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}


Lets look at the method in JAVA source code and the values it may return:

StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false


It returns true in case of equality. So, we can use this or the same logic to write our optimized pieces of code.

Have fun, optimize :)

Комментариев нет:

Most popular

Authors