2

I have this code:

        public int GetNumber()
    {
        if (Foo() > 8)
        {
            return 10;
        }

        if (Foo() == 4)
        {
            return 0;
        }
        if (Foo() == 3)
        {
            return 1;
        }

        return 10;
    }

And I would like to use patterns with ReSharper to verify if my method has multuple "return" statements and display a suggestion, and if I have this method:

    public int GetNumber2()
    {
        var result = 0;

        if (Foo() > 8)
        {
            result = 10;
        }

        if (Foo() == 4)
        {
            result = 0;
        }
        if (Foo() == 3)
        {
            result = 1;
        }

        return result;
    }

The suggestion won't be displayed.

  • 9
    Just out of interest, *why* do you want to do this? Using "early out" approaches like the first implementation can make code much easier to read. Many of the disadvantages of multiple return points simply don't exist in C#. I would far rather read your first implementation than the second. Also note that they're not equivalent - your second implementation *always* calls `Foo()` three times... – Jon Skeet Jul 02 '14 at 15:36
  • 1
    Single-exit is a "structured programming" idiom, from the 60's... I don't think it's very applicable to modern languages and paradigms like object-oriented programming. – Peter Ritchie Jul 02 '14 at 15:38
  • 1
    http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement – Eugene Podskal Jul 02 '14 at 15:45
  • At any point in a method you have the value and did everything you need, it is usually better to return right then and there. In your example, you just called `Foo()` 2 extra times for no reason. Of course that should normally be set to a variable up top. – TyCobb Jul 02 '14 at 15:53

0 Answers0