I'm doing some coding in JavaScript, and I am having a lot of instances where I have to check some stuff before I proceed. I got into the habit of returning early in the function, but I'm not sure if I am doing this right. I am not sure if it have an impact on the complexity of my code as it grows.
I want to know from more experienced JavaScript coders, what is a better general practice out of the following two examples. Or is it irrelevant, and they are both OK ways of writing this particular IF block?
1) Returning Early or "Short Circuit" as I call it (Guard Clause).
ServeAlcohol = function(age)
{
if(age < 19)
return;
//...Code here for serving alcohol.....
}
..Or...
2) Wrap code into an IF statement.
ServeAlcohol = function(age)
{
if(age >= 19)
{
//...Code here for serving alcohol.....
}
}
In my opinion, as a best practice, I think it is more important to consistently use braces with your control blocks, even if their body is only one line.
Consistent
Not consistent
But even still, this is completely subjective.
As for when to break out of a function, and levels of indentation, that's subjective too. Research and experience have shown that exiting a function at only one point (the end) is easier to debug, optimize, etc. On the other hand, multiple levels of indentation can make a function difficult to read.
There are some people who think that each function should have a single exit point. However, I find it clearer when quick conditional checks like the one you mentioned are done at the beginning. It also avoid some code from being unnecessarily run.
Alternatively, since JavaScript is scheme in disguise
The idiom for selecting the function isn't that important, rather that if you are doing complex validation and then have multiple processes, factor these to separate functions rather than making one big one, unless it's in a very performance critical bit of code.
Personal choice. For me, if there are some "stop" conditions I can check at the beginning of the method, I prefer using the "return" pattern. But only if I can do them all in the beginning of the method.
Usually I have input-validation return right away. Imagine if you had a bunch of conditionals, you'd get a mess of nested
if
s right away.Generally once I get past input validation I avoid multiple returns, but for validation I return right away. Keeps it cleaner IMHO.
I prefer the first one, because it's a guard condition and you exit directly. But I don't think there is performance issues with either, just that it's your preference... Both will return execution directly...