[.net] C# Symantic Question

Started by
12 comments, last by BradSnobar 18 years ago
I've been reading Beginning C# Objects—From Concepts to Code by Jacquie Barker and one of the chapters talking about methods says that the following code while perfectly legal is poor grammer due to using multiple returns.

public bool MyStringMethod()
{
    if (gpa >= 3.5)
    {
       return true; // first return statement
    }
    else 
    {
      return false; // second return statement
    }
}

I do this all the time! I was curious if some of the more veteran .Net programmers have any opinions on this?
Advertisement
Calling something poor grammer just means "I don't like it but I don't know why/I don't want to explain why"

The former is just a poor statement, the latter leaves out the important information when to omit this "rule"

I think the idea behind this guideline is to make functions easier to verify.

Just don't have to much of them nested in very different conditions.
I think this might be a better way to write the code:

public bool MyStringMethod() {  bool gradeCheck;    if (gpa >=3.5)     gradeCheck=True;  else     gradeCheck=false;  return gradeCheck; }


T!
return (gpa >= 3.5);


That's my opinion.
GPA doesn't have to be a bool for that to work.
Heh, Long Dog Studios had a post above mine, but I see that he quickly deleted it when he realized his error.
Here's some helpful information about how C/C++/C# expressions work:

operator >= and similar operators work the same way as a function would; in this case, it takes two similar number arguments and returns a bool.

this means that when the return sees the expression, it will return the boolean.
Yeah I had a brain F%$# for a second.

T!
Some instructors in my school explained that the reason for having only one return statement is to make code verifiable by automated tools as well as reduce spagetti code. I suppose a mathematical proof of a function is easier to construct if only one return exists.
Weird. Validation tools worth their salt should be able to track multiple returns. They have to track through loops and branches anyway which will affect the return result.


Anyway, I think that the book mentioned by the OP wasn't explicitly saying that multiple returns are bad, but that in that particular case it is unnecessary because your return value is the exact result of a comparison that you've already done.

This topic is closed to new replies.

Advertisement