andrewducker: (Default)
andrewducker ([personal profile] andrewducker) wrote2010-02-11 03:11 pm

Thinking about code

  If I have a method:
int DoSomething(string someStuff)
{
  //Do Stuff
  return 42;
}
then effectively I have an unnamed variable that gets set by the return statement, yes?

That being the case, wouldn't it be in some ways clearer to have an explicit, named, variable that gets set instead?

int DoSomething(string someStuff)
{
  //Do Stuff
  returnValue = 42;
}

where "returnValue" is a keyword that's used to return the value.

As it is I frequently end up with code that creates (or sets) a variable at various points through the code just so it can be returned at the end.  Making this an explicit part of the language just makes sense to me.

I assume there are languages out there that do this.

[identity profile] lpetrazickis.livejournal.com 2010-02-11 04:22 pm (UTC)(link)
I prefer having multiple return statements. Languages that have this sort of a variable also tend to not allow for early function termination, forcing you to wrap your code in layers of conditionals.

Languages with a return variable:

function monkeys() {
if (foobar) {
return = 42;
} else {
// ...
if (dagnabit) {
return = 13;
} else {
// ...
if (consarnit()) {
return = e^(-i*pi)
} else {
// ...
}
}
}
}
// fall out of function
}


Language with a return statement:

function monkeys() {
if (foobar) return 42;
// ...
if (dagnabit) return 13;
// ...
if (consarnit()) return = e^(-i*pi);
// ...
}


I find the latter preferable.
ext_8559: Cartoon me  (Default)

[identity profile] the-magician.livejournal.com 2010-02-11 05:16 pm (UTC)(link)
VB has the "exit" command for exiting loops

For nRow = 1 To nLastRow
If ws.Cells(nRow, nColumn).Address = "$A$7" Then
Debug.Print "Found cell. Exiting for loop."
Exit For
Else
Debug.Print ws.Cells(nRow, nColumn).Address
End If
Next

In some ways I like having the function name as the return variable, since the calling line will have something like

b = f(a) + 4;

and the code will have

int f(int a){
f = 3*a;
}

so mentally f is a function that returns an int *and* is an int. Of course in some languages you'll then have problems if you ask for the address of f (is it a pointer to the nominal variable, or a function pointer?)

And it gets even more fun with recursive calls!

I quite often have code like (vastly simplified)

string center(string astring) {
string mystring;
mystring = "";
if len(astring) > 0 then mystring = "<center>" + astring + "</center>";
return mystring;
}