Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Is it a good practice to call the variable a method returns with a variable name result?

For instance:

public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}

Or should I name it by its type?

public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.

share|improve this question

closed as not constructive by Jim G., Jarrod Roberson, Matthieu, Caleb, Walter Feb 11 '12 at 2:09

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

67  
I have also seen ofTheJedi used for that purpose. Not a recommendation, just saying I've seen it. Zorglub ofTheJedi = //...; return ofTheJedi; –  user4051 Feb 10 '12 at 9:55
6  
I usually call it "retval" (value to return) but that's more or less the same thing as "result", which I would put my vote on. –  Zeta Two Feb 10 '12 at 9:58
5  
Everybody has a different answer, they're all similar, but different, and valid, the question isn't willingly subjective, but the answers are. It's more of a poll. –  ZJR Feb 10 '12 at 10:48
15  
I'd say that "result" as a variable is fine, but "calculate" as a function is absolutely not. –  Kaz Dragon Feb 10 '12 at 11:01
2  
Do you work with a lot of former Delphi programmers? –  Peter Turner Feb 10 '12 at 14:28

17 Answers 17

If this is a method variable, it really depends on readability.

Seeing as you already have the type name in both the variable declaration and the method return type, you might as well use result - it is descriptive of the role of the variable.

share|improve this answer

Cross-reading is made easier if the variable is named result. This makes your intention clear.

share|improve this answer

If I need a return variable (which is actually happens rarely), I always call it ret and always define it right below the function head. The function already has a name, which says all about what it returns.

If I have myFunction I could name it's return variable myFunctionReturnValue to say exactly the same thing, only I'd have to say it explicitly every single time. Since functions should generally be short, there is no need for such explicitness. And even if I lose track, I can jump to the declaration and will land right below the function definition.

But any other name, that doesn't implicitly (like ret or result) or explicitly (like myFunctionReturnValue or myFunctionResult) state, that this is the current functions return variable is too generic.

In your second example zorglub is a terrible choice. All the declaration really tells me is that you created a variable, the name of which is equal to the type annotation found right next to the name. It's about as helpful as int someInt or Zorglub z.

In your first example, when I look at the code, I first see the function name, that tells me, that this function calculates a Zorglub. As I read the second line I see "ok, here's the zorglub, that is going to be returned, but it evidently can't be returned right away and is therefore stored in the result variable" (as a side note: If you're not going to reassign the value, then you best declare the variable final to communicate that), and then I think "so now let's see what happens to it before it gets returned". Unlike in the first example I don't need to actually read any further than that to know that this is the variable, that's going to be returned and that I want to follow in the function body if I want to understand it.

You might want to read up on Spartan Programming, which is rather related to your question.

share|improve this answer
5  
+1 for "zorglub is a terrible choice". There is no earthly reason for having a variable name, in any context whatsoever, that's identical to the type name (minus the initial capital). The declaration tells you the type of the variable - naming your variable after your type is no better than calling your variables x1, x2, x3 and so on. The name of any variable should express what the variable is for or what it does. My preferred name for a variable in this particular case is toReturn - because the variable references the object to return. In fact, lots of my variable names start with "to". –  David Wallace Feb 10 '12 at 10:47
16  
@DavidWallace - that's too strong of an absolute. I have a class called Container. If I have a method that modifies the quantity, I might say var container = getContainer(id); container.Quantity += 1; That's certainly readable if the context of the method only operates on a single container, and that's all it does. Calling it theContainerWeAreGoingToAdjustTheQuantityOf is just ridiculous. –  Scott Whitlock Feb 10 '12 at 12:47
3  
@David, I disagree. Let's take a situation where you have several local variables, each of a different type (let's say User, Manager and Department). And suppose the task is to link the user to the department and the manager's team. IMHO it is perfectly OK to call this User instance simply user (as opposed to userToJoinThisDepartmentAndManager? Or what would be your choice?) –  Péter Török Feb 10 '12 at 12:49
8  
Minor nitpick: I hate seeing "ret" or "rv" or other abbreviated variants of result/returnValue. "result" is not very long, and nobody needs to conserve characters. –  Kristopher Johnson Feb 10 '12 at 15:23
1  
@KristopherJohnson: "result" is not very long, but it also doesn't mean "return value". Return-values aren't always results of computations, and conversely, results of computations aren't always return-values. I suppose you could name your return-value returnValue, but ret is traditional, just like int and char. –  ruakh Feb 10 '12 at 15:45

In your second example, you're conflating the type of the result with what it is.

Zorglub zorglub;

just tells me it's a Zorglub, twice. Three times if I bother to read the method return type. However,

double variance;

for example, gives me a clue about what the return value means, in terms of program semantics. It may or may not be any clearer than just calling it result, depending on the size of the method - that's a judgement call for each method IMO.

share|improve this answer

If you play with many Zorglub objects in your methods, you "could" make a mistake and return the wrong one, or/and you could be tempted to name the others zorglub1, zorglub2, etc.

If you name it result, there is no chance for you to make a mistake like that. Plus, I find that is a good name; I've also seen returnedValue or returnedObject several times, it's also clear although a bit lengthy.

share|improve this answer

I personally am not completely comfortable using result as a variable name. Fair enough, it tells me that the associated value is the result of some computation - however, I guess that is true to about (or over) 90% of the variables / fields used in a program.

Moreover, as several other answers noted, it may be used to mark the value to be returned from a method / function. However, if I keep my methods short, focused on doing one thing only and staying consistently on a single level of abstraction, I won't have many local variables and it will be trivial to see what a method is going to return.

So I prefer to keep my methods short and clean, and name my variables to express the meaning of the value they hold, rather than its local role inside the enclosing method. However, (e.g. in legacy code) Zorglub result may certainly be easier to understand than Zorglub zorglub.

share|improve this answer
11  
It is not called result because it is the result of some computation; it is called result because it is the result of this computation. That also works as its meaning IMO, even if it's not the most specific meaning possible. Expressing meaning is golden, but intention and idioms can be valuable too. In this case it's a bit of a trade-off. –  Supr Feb 10 '12 at 12:04

I personally use the name result for the value to be returned from function/method. It makes it explicit that it is the value to be returned. Naming it by type does not seem useful, because there may be more than one variable of that same type.

share|improve this answer

Whats the difference? its just 2 different words there that will do the same thing so the real problem is which one sounds more clear to you?

The "result" or "zorglub".

I would prefer using ZorglubResult for a starter to see that result returns from Zorglub easier to compare with other results you may have and its a result as you can see..

share|improve this answer

should I name it by its type?

No. Never. This is called Systems Hungarian and is trivially outdated by the idea of using a program which can display the type of any variable any time you need it.

share|improve this answer

Whenever you need to name anything in code, you should provide names that are descriptive, meaningful, and readable. The case of a return variable is a particularly good example of where people tend to become complacent about naming.

If you have a function that is clearly named, and you only need a single line of code, then you can skip the naming entirely. Making your methods short and single purpose is always the ideal that you should be aiming for. However, it is the case that sometimes you do need to complete a function with several lines of code. I those cases it is always advisable to name your variable to match the purpose of your function.

If the purpose of the function is to return the result of a calculation or a decision algorithm, then result is a perfectly adequate name for your variable to use, but what if your function is returning an item from a list? What if your function is serving some other purpose that has nothing to do with math or lists? In those cases, it is better to provide the variable with a meaningful name that relates to why the function was created. Sure, you could simply use result if you wanted to because it's a name that isn't likely to clash with anything else, however from a readability perspective it makes more sense to name your variable more meaningfully and in context.

share|improve this answer

I like combining them, shows what it is and that it is intended to be returned.

so in your example it would be resultZorglub

if what it is doesn't really matter than it would just be result (not resultString)

share|improve this answer

I don't see much of a difference between setting a return value at some point and then using conditionals to skip over all code that might modify it, and returning right away, so I go for the direct return, hence there is no result variable.

If you have an intermediate value that may or may not be changed by conditional code, then it is not a result (yet), so it certainly should not be named so.

share|improve this answer

When I was working in C++ and I guess this may apply in Java I did.

e.g.

int Width() const
{
    Requires(....);
    Requires(....);

    //calculation

    Ensures(...);
    Ensures(...);
    return Result;
}

This is design by contract, as the ensure block should be at the end of the method. But the return must be last. We had the rule that return Result was the only thing that could follow the ensure block.

share|improve this answer

In a recursive function, it is often effective to carry the result from step to step, to make for a tail call optimization. To signalize to the user, that he needn't provide a parameter, it can be reasonable to name a parameter "result":

def removeOccurence [A] (slice: Seq[A], original: Seq[A]) = {
  @scala.annotation.tailrec
  def remove (leftOriginal: Seq[A], result: Seq[A]) : Seq[A] =
    trimStart (slice, leftOriginal) match {
      case (h :: tail) => remove (tail, h +: result)
      case (Nil)       => result.reverse
    }
    remove (original, Nil)
}

But more often I use 'carry' and 'sofar', which I have seen in the wild, and which carry the idea even a bit better, in most cases.

A second reason is of course, if your topic suggest the word ''result'', for example if you do arithmetic evaluation. You might parse the formula, replace variables with values, and calculate a result in the end.

A third reason has already been stated, but I have a small deviation: You write a method which performs some job, let's say it evaluates a form of ''max''.

def max = {
  val result = somethingElseToDo
  if (foo) result else default 
}

Instead of calling the result ''result'', we could call it ''max'', but in some languages you can omit parenthesis when calling a method, so max would be a recursive call to the method itself.

In general, I would prefer a name which tells, what the result is. But if that name is already taken, maybe by more than one variable, attribut or method, because there is a GUI-field, a string representation, a numerical and one for the database, using another one increases the probability of confusion. In short methods of 3 to 7 lines, ''result'' shouldn't be a problem for a name.

share|improve this answer

In Object Pascal this is not a choice. You have to assign value to the Result variable somewhere in the code of the function.

Example:

function AddIntegers( A,B: Integer): Integer;
begin
  Result := A + B; 
end; 

So for me is pretty natural have an "Result" (or "Retorno", as I spell it in Portuguese to avoid name conflict with language's reserved words) variable to receive an return value.

Of couse, if it's a very simple expression in a C-derived language, I won't bother to declare an result variable - returning the expression directly.

share|improve this answer

result is fine. I am able to understand the code in the first glance so the variable name served the purpose.

share|improve this answer

its not just what you name the result (I am particular to 'r'), but also how its used. for instance, if you're going to have a return variable, then every return statement should return it. don't have 'return r;' at the end, but sprinkle things like 'return m * x + b;" throughout the method/function. use "r = m * x + b; return r;" instead.

share|improve this answer

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