Let's say we have a class called 'Automobile' and we have an instance of that class called 'myCar'. I would like to ask why do we need to put the values that our methods return in a variable? Why don't we just call the method?
For example, why should one write:
string message = myCar.SpeedMessage();
Console.WriteLine(message);
instead of:
Console.WriteLine(myCar.SpeedMessage());
4 Answers 4
Short answer: We don't. Both examples are absolutely fine.
There are three reasons why people use temporary variables anyway (like in your first example):
- It gives an explicit name to the intermediate value (we now know that it's a
message
, not just any old string). - It helps prevent statements getting too long and too complex.
- It makes step-debugging easier, because you can step over each part individually (although there are step debuggers that work at sub-line precision).
-
10@Timwi Disagree. I'd move #2 up to #1. Writing code in simple, easy to read steps is an excellent habit, and using local variables as needed facilitates that.Caleb– Caleb10/07/2012 18:02:16Commented Oct 7, 2012 at 18:02
-
2+1 excellent points. I always argue for point #1 - naming it explicitly allows you to describe the variable's intent, which is basically the only information missing (your IDE can do the rest: inform you of the type, navigate to source, etc).Daniel B– Daniel B10/08/2012 07:05:13Commented Oct 8, 2012 at 7:05
-
24. There used to be an extra step in between creating the variable and the (now) only use of it, that was removed for some reason.jwenting– jwenting10/08/2012 07:33:13Commented Oct 8, 2012 at 7:33
-
2Just wanted to point out that many optimizers will elide the variable, so if you go looking for it in the debugger, it may not exist. Not a problem if you compile with the debug flag set, but at higher optimization levels that's a pretty common optimization.TMN– TMN10/08/2012 14:10:52Commented Oct 8, 2012 at 14:10
-
1Re: "Explicit name to intermediate value" - in the example above,
speedMessage()
is more descriptive than justmessage
. I would think that when possible, it would be better to improve the name of a method being called than to introduce a temporary variable. When that's not possible, a temporary variable or a comment can aid readability. But I'm with you on #2 and #3.GlenPeterson– GlenPeterson10/09/2012 04:09:14Commented Oct 9, 2012 at 4:09
in most languages you don't need to which is handy if you want to use a getter and pass it into a method:
bar.doBaz(faa.getFoo())
but it can improve readability by separating the calls especially when it's a non trivial function
also it reduces the horizontal footprint of the call at the cost of an extra line (provided that the new variable's name is short)
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.
In this case it doesn't really matter but when you're working with bigger systems it can be an issue as:
- It makes debugging a lot easier
- If you have a habit of compacting your code as far as me it makes it actually readable ie:
square(getNum1(var1,var2[(param1+(param2%2))]),obj1.getNum2(((ptr1+dynamicOffset1)+5)(getMult(NULL))))
-
1You might want to expand on the "makes debugging easier" statement, by explaining how some (all?) debuggers make it hard to set a breakpoint in the middle of a statement. Using two lines means it's possible to set a break after the variable has been assigned but before the value is used in the following statement.Bryan Oakley– Bryan Oakley10/08/2012 17:22:12Commented Oct 8, 2012 at 17:22
Explore related questions
See similar questions with these tags.
SpeedMessage
was an expensive operation and its value was going to be used multiple times.