3 ms·
Yeah, the problem with outlawing "retval" in particular is that there's no good variable name in this situation: int sum(Collection<Integer> c) { int r
by philwelch 11y ago
Yeah, the problem with outlawing "retval" in particular is that there's no good variable name in this situation:
int sum(Collection<Integer> c)
{
int retval = 0;
for(int i = 0; i < c.size(); i++){
retval += c.get(i);
}
return retval;
}
What the hell should I call retval? If I call it sum, that's redundant with the method name. Also, while it might work in Java, it would be more dangerous in a language like Ruby where the equivalent code:
def sum(c)
sum = 0
c.each do |e| retval += e end
sum
end
would, due to lexical scoping, make it impossible to call the method recursively.
- Splines 11y agoI'd call your method SumCollectionInteger and call your return value sum. This doesn't really work if you use function overloading though.
- munificent 11y agoCall it "result": - "val" in "retval" carries no meaning. Everything stored in a variable is a value. - "ret" is an annoying abbreviation for "return" that makes it harder read. - "return" focuses on an implementation detail—that the function produces its value using the language's "return" statement. It doesn't matter how the result is emitted, just that it is. If a function is simple enough that the variable storing the result doesn't need a more specific name, "result" is a good default. You could call it "sum" here, but that shadows the function itself—a common problem for result variables—and doesn't really tell us anything we don't already know. We know we're inside a "sum" function.
- seanc722 11y ago"result" was also included in the list. I honestly don't see anything wrong with either.
- philwelch 11y agoI usually go for "result", but that was also on OP's list. I wish it was a convention to use "r" for retval variables.
- vanderZwan 11y agoProblem with that (for me) is that I use that for radius all the time, as in r * sin( a * t )