8

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());
1
  • 6
    The only time I would do that would be if SpeedMessage was an expensive operation and its value was going to be used multiple times.
    – axblount
    Oct 6, 2012 at 17:54

4 Answers 4

52

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):

  1. It gives an explicit name to the intermediate value (we now know that it's a message, not just any old string).
  2. It helps prevent statements getting too long and too complex.
  3. It makes step-debugging easier, because you can step over each part individually (although there are step debuggers that work at sub-line precision).
5
  • 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
    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
    Oct 8, 2012 at 7:05
  • 2
    4. 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
    Oct 8, 2012 at 7:33
  • 2
    Just 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
    Oct 8, 2012 at 14:10
  • 1
    Re: "Explicit name to intermediate value" - in the example above, speedMessage() is more descriptive than just message. 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. Oct 9, 2012 at 4:09
4

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)

4

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.

2

In this case it doesn't really matter but when you're working with bigger systems it can be an issue as:

  1. It makes debugging a lot easier
  2. 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))))

1
  • 1
    You 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. Oct 8, 2012 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.