Tuesday, June 10, 2008

Multiple Returns in a Method

I read an article today on the usage of multiple return statements in methods (for the uninitiated, it's about best practices in writing source code) by Remi Sabourin.

A commonly encountered scenario that I can think of with multiple exit points for a method is in map values. Example:


public string GetStringForCode(int aCode) {
switch (aCode) {
case 1:
return "Operation Successful";
case 2:
return "An error occurred";
default:
throw new Exception("Invalid input");
}
}


You would probably say that there's nothing wrong with the method above and it executes perfectly fine, and I agree with you there. Given the right input, it returns the desired input. However, it's not very elegant in terms of coding style (think along the lines of having to add a suffix, such as a period, to all of the strings when we've got a dozen cases to handle) and perhaps would make the code a little harder to comprehend for the green. If you ask me, I'd change the same code to:


public string GetStringForCode(int aCode) {
String retVal;

switch (aCode) {
case 1:
retVal = "Operation Successful";
case 2:
retVal = "An error occurred";
default:
throw new Exception("Invalid input");
}

return retVal;
}


The above can then be easily modified to:


public string GetStringForCode(int aCode) {
String retVal;

switch (aCode) {
case 1:
retVal = "Operation Successful";
case 2:
retVal = "An error occurred";
default:
throw new Exception("Invalid input");
}

retVal += ".";

return retVal;
}


I'm not insisting that we change the tons of old code to make it more maintainable - that wouldn't be very cost effective and may break what already works well. I'm simply suggesting that we be a little more considerate to the developers who would have to work with our code in future, when writing new code.

For more, check out the original article (and the try-finally tip at the bottom of the article) at:
http://geekswithblogs.net/RSabourin/archive/2008/06/09/multiple-function-exit-points---bad.aspx

No comments: