There are some times when an extra variable can help general readability, especially when evaluating some long expression inside an if
or a function call that makes the code go way off the right-hand side of the screen.
In Java 5 or later (and many similar languages), an extra variable can be useful to find the cause of null-pointer exceptions. Consider the following Java code which relies on Java's "autoboxing" to convert Integer
objects to an int
primitive:
public int add(Integer firstIntObj, Integer secondIntObj) {
return firstIntObj + secondIntObj;
}
It will throw a NullPointerException when it converts an uninitialized (null
) Integer
object into a primitive int
, but this exception doesn't indicate which object caused the exception because the two possible culprits are on the same line. The following would blow up on a different line for each null
input, thus the line number in the exception will indicate which one was null
:
public int add(Integer firstIntObj, Integer secondIntObj) {
int first = firstIntObj;
int second = secondIntObj;
return first + second;
}
A better way to handle this is to throw your own descriptive exception so that someone calling this method can diagnose their own problem without needing your source code:
public int add(Integer firstIntObj, Integer secondIntObj) {
if (firstIntObj == null) {
throw new IllegalArgumentException("First argument was null!");
}
if (secondIntObj == null) {
throw new IllegalArgumentException("Second argument was null!");
}
return firstIntObj + secondIntObj;
}
This technique can be used to split up any line that could throw more than one exception. Using separate variables is less typing than throwing a descriptive exception - it's quick and dirty.
SpeedMessage
was an expensive operation and its value was going to be used multiple times.