Shall I use guard clause, and try to avoid else clause?

15,411

Solution 1

This is arguable and pure aesthetic question.

Early return has been historically avoided in C and similar languages since it was possible to miss resource cleanup which is usually placed at the end of the function in case of early return.

Given that Java have exceptions and try, catch, finally, there's no need to fear early returns.

Personaly, I agree with you, since I do early return often - that usually means less code and simpler code flow with less if/else nesting.

Solution 2

Guard clause is a good idea because it clearly indicates that current method is not interested in certain cases. When you clear up at the very beginning of the method that it doesn't deal with some cases (e.g. when some value is less than zero), then the rest of the method is pure implementation of its responsibility.

There is one stronger case of guard clauses - statements that validate input and throw exceptions when some argument is unacceptable, e.g. null. In that case you don't want to proceed with execution but wish to throw at the very beginning of the method. That is where guard clauses are the best solution because you don't want to mix exception throwing logic with the core of the method you're implementing.

When talking about guard clauses that throw exceptions, here is one article about how you can simplify them in C# using extension methods: How to Reduce Cyclomatic Complexity: Guard Clause. Though that method is not available in Java, it is useful in C#.

Solution 3

Have them read http://www.cis.temple.edu/~ingargio/cis71/software/roberts/documents/loopexit.txt and see if it will change their minds. (There is history to their idea, but I side with you.)

Edit: Here are the critical points from the article. The principle of single exits from control structures was adopted on principle, not observational data. But observational data says that allowing multiple ways of exiting control structures makes certain problems easier to solve accurately, and does not hurt readability. Disallowing it makes code harder and more likely to be buggy. This holds across a wide variety of programmers, from students to textbook writers. Therefore we should allow and use multiple exits where appropriate.

Solution 4

I'm in the multiple-return/return-early camp and I would lobby to convince other engineers of this. You can have great arguments and cite great sources, but in the end, all you can do is make your pitch, suggest compromises, come to a decision, and then work as a team, which ever way it works out. (Although revisiting of the topic from time to time isn't out of the question either.)

This really just comes down to style and, in the grand scheme of things, a relatively minor one. Overall, you're a more effective developer if you can adapt to either style. If this really "makes it difficult ... to follow their coding style", then I suggest you work on it, because in the end, you'll end up the better engineer.

I had an engineer once come to me and insist he be given dispensation to follow his own coding style (and we had a pretty minimal set of guidelines). He said the established coding style hurt his eyes and made it difficult for him to concentrate (I think he may have even said "nauseous".) I told him that if he was going to work on a lot of people's code, not just code he wrote, and vice versa. If he couldn't adapt to work with the agreed upon style, I couldn't use him and that maybe this type of collaborative project wasn't the right place for him. Coincidentally, it was less of an issue after that (although every code review was still a battle).

Share:
15,411

Related videos on Youtube

chance
Author by

chance

programmer

Updated on May 18, 2022

Comments

  • chance
    chance almost 2 years

    I've read (e.g. from Martin Fowler) that we should use guard clause instead of single return in a (short) method in OOP. I've also read (from somewhere I don't remember) that else clause should be avoided when possible.

    But my colleagues (I work in a small team with only 3 guys) force me not to use multiple returns in a method, and to use else clause as much as possible, even if there is only one comment line in the else block.

    This makes it difficult for me to follow their coding style, because for example, I cannot view all code of a method in one screen. And when I code, I have to write guard clause first, and then try to convert it into the form with out multiple returns.

    Am I wrong or what should I do with it?

    • KajMagnus
      KajMagnus over 8 years
      With "I cannot view all code of a method in one screen", did you mean that they've if-elsed so much so the code has become indented so much so that it gets outside the right edge of the screen? Or that if-else takes a bit more space so the method is longer (taller) than what it needs to be? B.t.w. I like guard clauses.
    • icc97
      icc97 over 8 years
      "even if there is only one comment line in the else block" - one source for this comes from the book Code Complete. It sounds like they are being too dogmatic about applying it though.
  • biziclop
    biziclop about 13 years
    If my memory serves me right, another reason for avoiding early returns (or breaks from loops) was that it was easier to theoretically prove that your code was correct. (a.k.a formal verification)
  • Joeri Hendrickx
    Joeri Hendrickx about 13 years
    +1 for pointing out it's arguable. I prefer early return, too, for readability.
  • HelloWorldNoMore
    HelloWorldNoMore almost 8 years
    There is too much to read in that article. Can you please mention the essential idea ?
  • btilly
    btilly almost 8 years
    @HelloWorldNoMore The principle of single exits from control structures was adopted on principle, not observational data. But observational data says that allowing multiple ways of exiting control structures makes certain problems easier to solve accurately, and does not hurt readability. Disallowing it makes code harder and more likely to be buggy. This holds across a wide variety of programmers, from students to textbook writers. Therefore we should allow and use multiple exits where appropriate.
  • MC Emperor
    MC Emperor over 6 years
    I prefer early return, too, as long as it roughly takes the form of guard clauses, and do not result in numerous hazy return statements. Breaking out of a for loop, for instance, is perfectly fine. for (Object o : objects) { if (someCondition) { return o; }}
  • aka.nice
    aka.nice almost 6 years
    Style matters: there are several ways of swimming, but at the end, the front crawl wins for some reasons...
  • jxramos
    jxramos over 4 years
    I'd say it's more than purely aesthetic, I would argue it keeps our mental stack shallow and thereby lowers cognitive load.
  • cambunctious
    cambunctious over 3 years
    It's entirely subjective, but people who prefer nesting conditions are wrong.