53

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.

badp
  • 1,890

17 Answers17

48

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.

Oded
  • 53,734
40

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

mouviciel
  • 15,491
17

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.

back2dos
  • 30,140
14

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.

Useless
  • 12,823
8

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.

Jalayn
  • 9,827
5

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.

1

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.

1

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..

1

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.

DeadMG
  • 36,914
1

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.

S.Robins
  • 11,505
0

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)

KeesDijk
  • 8,968
0

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.

0

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.

0

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.

0

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.

0

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.

rbp
  • 156
-1

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

java_mouse
  • 2,657
  • 17
  • 23