qben
qben

Reputation: 833

Is there a general argument about return style for a "conditional" method?

I've seen a lot of methods in these two style:

1.
void foo() {
  if(!good) {
    return;
  }
  doFoo();
}

2.
void foo() {
  if(good) {
    doFoo();
  }
}

I wonder if this is just a matter of taste or one is actually better than the other. Does anyone know any evidence about this? (Style-checker rules, book, etc.) I'm thinking mainly about this code written in Java.

Upvotes: 0

Views: 43

Answers (4)

Anastasiia
Anastasiia

Reputation: 325

First variant handle extra nesting. It depends on your project's code style conventions and your method logic. I advice you to read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin

Upvotes: 0

Predrag Maric
Predrag Maric

Reputation: 24433

Between these two, second option is better IMHO. If there are more if-else branches, you could end up with multiple return statements which makes the code hard to navigate (in most cases, but sometimes it does good to your code).

Upvotes: 0

pushpendra chauhan
pushpendra chauhan

Reputation: 2375

i believe its all depend on your program logic and requirements, In your first example doFoo() will be called only if your if condition is not satisfied and in your second option doFoo() will be called when if condition is satisfied..

you can read coding convention for java programmer it is pretty good http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

Upvotes: 0

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

Depends on your project team's code style rules.

If if statement checks method contracts I prefer fast fail approach.

Upvotes: 2

Related Questions