0

Is it generally accepted to be better programming practice to use a structure like:

if (x == 1) {
  if (y != 1) {
    [code]
  }
}

or to use a guard like this:

if (x == 1) {
  if (y == 1)  return;
  [code]
}

The first style has a more logical structure, where it's clear at a glance which code depends on what.

But the second style results in a more simple visual style and fewer lines of code.

Is the second style considered a bad habit? Or is it just a style choice?

[update] this is a duplicate

Community
  • 1
  • 1
Andy Swift
  • 2,179
  • 3
  • 32
  • 53
  • This is a common 'holy-war' [question](http://programmers.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement) – StuartLC Nov 24 '14 at 11:09
  • Both are good but in different situations. The debate is an example of [Parkinson's law](https://en.wikipedia.org/wiki/Parkinson%27s_law_of_triviality), a.k.a. "bikeshedding". – molbdnilo Nov 24 '14 at 12:10
  • 1
    As for code clarity, early returns are winners unless you have some cleaning to do first (`javascript` and `perl` not being in this category unlike ie. `C`). So return early as possible, and your code won't turn into endless spaghetti indentation nightmare. – mpapec Nov 24 '14 at 13:20

2 Answers2

1

Whatever your 'house style' says.

The thing with coding style is - it really doesn't matter, as long as it's consistent throughout your code. And the code of all your colleagues.

Clarity is king - if your code is clear what it's doing, it's good code. If it's not clear what it's doing, it's bad code. (and if everyone's using a different style, it's not going to be clear, and therefore all your code is bad). And that's all. Don't worry about saving lines of code - the compiler doesn't care.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
1

The question should not be 'Is it better to use nested ifs or use guards' but 'When is it better to use nested ifs and when guards'!

There are pro's and con's in both ways. Using ifs promotes single point of exit but can become difficult to read when nesting is deep. Guards reduce nesting and easier to read but create multiple points of exit.

it does not matter which you chose as long as your functions are short!

Konstantin
  • 3,294
  • 21
  • 23
  • `Single point of exit` sounds almost like some kind of implicit benefit, but I'm rather skeptic if it is not accompanied by code clarity. – mpapec Nov 24 '14 at 13:29
  • ```single point of exit``` is only relevant when function is long and complex. That's why i personally prefer writing guards and keeping my functions very short with the least levels of indenting – Konstantin Nov 24 '14 at 13:45
  • Thank you for the vocabulary. I'll integrate it into the question. – Andy Swift Nov 24 '14 at 16:53