Welcome Guest, Not a member yet? Register   Sign In
Avoiding nesting everything inside IF statements
#6

[eluser]n0xie[/eluser]
I'm just adding my 2 cents.

We've been taught that any function should only have one exit point, which I abide to religiously, because it makes debugging, much much easier. (btw there is also a large group who things you should exit as soon as possible so it's not a silver bullet) The only exception to this rule is precisely your example: exit a function because of a failed precondition. What I mean by that is, code indentation is there to show you the 'paths' of your application. In a sense it is there to show what routes code should take. But these are based on the fact that you actually want the code to execute.

Whenever you have a condition where you do NOT want the code to execute, it's probably easier to exit as soon as possible.

For instance, I always do a sanity check against function parameters (because I don't trust my users and neither should you). If my sanity check fails, there isn't a code path to follow, it just means either something 'unexpected' happened OR something bad happened. Neither is something I like, and in no way would I want to execute any code. Therefor you will find tons of these codeblocks in my code:
Code:
function foo($bar)
{
  if ( ! do_some_sanity_check($bar)) { return/redirect/raise an error/write to log/bake a cake }

  // real code goes here
}
So if something fails my sanity check, the standard action would be to redirect and at the same time write a message to the error log, so I know something happened. The oneliner at the beginning of your function provides an extra exit point but it makes sense. It also doesn't 'indentclutter' your code.

tldr:
I do what you did in your example all the time.


Messages In This Thread
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 08:46 AM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 09:06 AM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 09:26 AM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 09:34 AM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 01:00 PM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 04:26 PM
Avoiding nesting everything inside IF statements - by El Forum - 09-29-2009, 06:17 PM



Theme © iAndrew 2016 - Forum software by © MyBB