Coding standards

If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program. - Linus Torvalds

Something I've noticed as I trawl through open source PHP code lately is that PHP devs just love nesting. I shouldn't complain, the overall quality of open source PHP code is pretty good now, and I'm just as guilty as anyone else of writing some awful rubbish, but the one thing that gets me is deep levels of nesting. The record I've spotted so far is 14 levels. 14! There are a lot of constructs that look like the following:

12345
for (; ;) {
  if (condition) {
    do_something();
  }
}

That's readable at the moment, but if the if's contents were longer and contained some more nesting, things start to get ugly. I much prefer to do any filtering at the start of the block and break out of it as soon as possible:

1234
for (; ;) {
  if (!condition) { continue; }
  do_something();
}

The same applies to functions - return as early as possible and you don't end up with deep levels of nesting.

Filter things right at the start and you don't have to worry about it later on. It's kind of silly to have nesting in your code when the only thing it marks is the end of a branch.

Generally the quote by Linus works pretty well, as long as you treat that as 3 logic levels (i.e. ignore any namespace, class or function indents).

Talk is cheap

Leave a comment:

HTML is not valid. Use:
[url=http://www.google.com]Google[/url] [b]bold[/b] [i]italics[/i] [u]underline[/u] [code]code[/code]