50

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,870
  • 1
  • 16
  • 21
Nicolas Raoul
  • 1,062
  • 1
  • 11
  • 20
  • 75
    I have also seen `ofTheJedi` used for that purpose. Not a recommendation, just saying I've seen it. `Zorglub ofTheJedi = //...; return ofTheJedi;` –  Feb 10 '12 at 09:55
  • 8
    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 09: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
  • 17
    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
  • 1
    I name return variables as `result` or `ret` all the time. – dan04 Feb 10 '12 at 14:16
  • 2
    Do you work with a lot of former Delphi programmers? – Peter Turner Feb 10 '12 at 14:28
  • I tend to use "rv", since that's what Mozilla used a few years back (not sure if they still do). "result" is probably more readable. – Plutor Feb 10 '12 at 14:30
  • 1
    `return @return;` – Chris S Feb 10 '12 at 14:33
  • 1
    Bob Martin's advice/observation that we spend 90% of our time reading code is a good mantra to live by for naming. Which would make it more 'human' to you if you were reading it - `return rtval` or `return result`? – Chris S Feb 10 '12 at 15:32
  • In my opinion that is ok naming it something like result, because the method(!) returns a result. Which type it is, is already declared, so it is not really confusing. – Markus Zeller May 20 '17 at 11:33

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,326
  • 19
  • 166
  • 181
40

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

mouviciel
  • 15,473
  • 1
  • 37
  • 64
  • 2
    +1 This is the main point. I know what result means in any context just by glancing at the code. – Xeoncross Feb 10 '12 at 15:51
  • 1
    I agree, using the variable type does not help you understand that your going to return it. In these simple examples, it is easier to see the return w/o scrolling or looking, but its faster to know up front what the returned value of the function is. It is also important to initalize it, as done in the example. – nycynik Feb 10 '12 at 21:36
16

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
  • 29,980
  • 3
  • 73
  • 114
  • 8
    +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". – Dawood ibn Kareem Feb 10 '12 at 10:47
  • 21
    @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
  • 4
    @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
  • 11
    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
  • 2
    @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
  • @KristopherJohnson: As @ruakh pointed out, result is not really on spot. It's best chosen to denote results in generic contexts, such as `T result = genericOperation()`. But using it to denote the return value of the current function is so common, that it's acceptable. – back2dos Feb 10 '12 at 22:50
  • @ScottWhitlock - I would call it `toAdjust` – Dawood ibn Kareem Feb 11 '12 at 03:01
  • @PéterTörök - depends. What's the method called? It could be something like `assignToManager( Employee assignee, Employee manager )`. I guess if you're linking two objects of different types (like an `Employee` to a `Department`) and you've got `link( Employee employee, Department department )`, that would be OK, since the two variables are kind of doing the same thing (being linked), and the only thing that differs about them is their type. But that would be a rare exception. – Dawood ibn Kareem Feb 11 '12 at 03:08
  • I've just realised I said "... no earthly reason ...". I guess that was too strong an absolute. But I would urge all developers to think about their variable names, and try to come up with more descriptive names than just the type name. Using the type name as the variable name is FAR TOO COMMON. – Dawood ibn Kareem Feb 11 '12 at 03:10
  • @DavidWallace, using `toAdjust` as a name would result in code like `var toAdjust = getContainer(id); toAdjust.Quantity += 1;` - to me it's not easily readable. YMMV. In my experience using variables of distinct types each is quite common. It's good to keep in mind that (variable) naming is not an end to itself - its main purpose should be making the code readable, not adhering to any (imagined or concrete) rulebook. – Péter Török Feb 11 '12 at 20:26
  • Where you're using something like Javascript, where variables are declare with "var", I'd certainly agree with you. I don't think my earlier comments apply to Javascript. But the OP is clearly using something like Java or C#, where the type of the variable is there in plain view. – Dawood ibn Kareem Feb 11 '12 at 20:31
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,380
  • 2
  • 34
  • 46
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,789
  • 4
  • 39
  • 58
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.

Péter Török
  • 46,427
  • 16
  • 160
  • 185
  • 12
    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
  • @Supr: What name would you use to describe the result of some other computation, which will only be used in the next statement or two (e.g. `if (result >= 0) numChars+=result; else break;`, and whose meaning will be obvious from the computation in question?) To my mind, the value that *will* be returned from *this* function should be called `ret`, while the value that *was* returned from the last called function should be `result`. Note that `result` may be more meaningful than a longer name if the function's return value might e.g. represent either a quantity or an error code. – supercat Jul 11 '12 at 17:42
  • @supercat, I would name it based on either what the computation was, or what the value is intended to be used for. Even if it is only used in he next computation, it still helps readability if it is named well. In your example I have no idea what the meaning of `result` is or what the code actually does on a higher level. I would have to refer to where it is set to see where its value comes from and what it is. Something like `addedChars` or `matchedChars` would be more transparent and help reveal what the code is doing, and not require mentally juggling this and the related `result = ...` :) – Supr Jul 11 '12 at 20:51
  • @Supr: The problem is that in many cases, different ranges of return values might mean different things. For example, a routine to read a packet into a buffer of specified size might return a number of bytes if a packet was received, or a negative number to indicate that a packet was (and still is) pending that's too big for the buffer, or a really big negative number to indicate some other error. Storing the return into `result` and then checking it against those criteria would seem more natural than trying to come up with a descriptive name which covers all of them. – supercat Jul 11 '12 at 20:55
  • @supercat, Using `ret` instead of `result` seems fine by me. It's a little less clear in my opinion because it is abbreviated and not noun-like, but if it is used consistently then it is equivalent to `result` . – Supr Jul 11 '12 at 20:55
  • @Supr: In that sort of situation, I would expect that the documentation for `GetPacket()` would be written to make obvious at a glance the nature of the different return values; anyone who sees the code and doesn't know what the return value means would be better served by looking at the documentation for that function than trying to guess based upon the variable name. – supercat Jul 11 '12 at 20:57
  • @supercat, Fair enough, it can't always be named completely descriptively. I'm not saying `result` should be reserved or anything, and in some domains it might be better to use it like you suggest. However in general `result` is fairly meaningless and opaque unless it refers to the result of the containing function. If it was named `packetState` then at least later on you know what the variable is concerned with. Another issue with using `result` for that purpose is in cases where you call two or more functions like that. `result1` and `result2`? – Supr Jul 11 '12 at 21:13
  • @supercat, In your example the name can't fully describe the *meaning* of all the various possible values, but it can still inform you what it contains or represents on a slightly more abstract level. Naming is actually parallel to using interfaces or abstract classes: the variable can contain an error, pending indicator, or result of completed computation, and so it could be represented by a `interface PacketState`, while the actual value would be `class PacketStateError`, `class PacketStatePending` or `class PacketStateComplete`. – Supr Jul 11 '12 at 21:29
  • @Supr: I use the non-descript `result` only to refer to the immediately-preceding operation. If I would want to persist the value for any significant amount of time, I would generally copy it into a descriptively-named variable (e.g. `result = getPacket(); if (result > 0) {int packet_size = result; ...do stuff with packet_size;} else ...`. – supercat Jul 11 '12 at 21:44
  • @supercat, Makes sense. I guess it comes down to preference if you want to use `result` like that or for the value of the containing function. Personally I prefer to reserve `result` for the latter -- `return result;` reads better than `return ret;`, and then use `packetState` or just inline the function call result :) – Supr Jul 11 '12 at 21:57
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.

Juraj Blaho
  • 390
  • 4
  • 7
  • Uhm, surely the fact that it'll say 'return' before it's returned is explicit enough? You should describe what you'll do with it, now the 'how'. Why not call it total, result, or something else descriptive of the purpose, then your code will ready "return total" or similar... – Dave Feb 10 '12 at 14:57
  • @Dave Not necessarly, especially if you've got a few objects of the same type which are all canidates to be returned, an the purpose of the method is to figure out which is the proper one to return. – Andy Feb 10 '12 at 15:10
  • @Andy I see your point, but in reality, I can't imagine writing a function like that. If that's the reason for writing a function like that, it sounds like it should be broken down into smaller more understandable functions. – Dave Feb 10 '12 at 15:19
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,794
  • 8
  • 70
  • 139
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,385
  • 2
  • 36
  • 52
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,918
  • 4
  • 35
  • 41
  • Not bad but I guess you would have to rename your variable if the return type changes. With modern IDE it's done in one or two clicks anyway I guess. – Jalayn Feb 10 '12 at 09:48
  • @Jalayn Yes, but if the type was kept out of the name then that's a change that wouldn't have to be done at all. (If a method's long enough that a simple name isn't clear, it's probably too long and should be refactored.) – Donal Fellows Feb 10 '12 at 10:05
  • @DonalFellows I agree completely with you. The less changes you see when updating from the source repository, the better. – Jalayn Feb 10 '12 at 10:07
  • Okay agreed that when you change the return type you might forget to change it also in the variable name, that is a problem. Until now it hasn't ever been a problem for me. I still like showing the double intent in the name but with smaller already good showing intent code it might also be overkill. You guys convinced me. If I feel the need to call my variables in this way from now on I will refactor until I don't feel the need any more. Thanks – KeesDijk Feb 10 '12 at 11:06
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.

Simon Richter
  • 1,568
  • 9
  • 10
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.

ctrl-alt-delor
  • 570
  • 4
  • 9
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.

user unknown
  • 797
  • 7
  • 14
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.

Fabricio Araujo
  • 371
  • 1
  • 7
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
  • 8
-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,627
  • 15
  • 23