When checking for parameter consistency a the top of a function body, what is the best strategy?
This one:
protected void function(Object parameter)
if (parameter == null)
return;
//... do things
}
…or this one:
protected void function(Object parameter)
if (parameter != null) {
//... do things
}
}
2
It is a matter of preference which style you choose, but I would go for your first option, for the following reasons. In my opinion….
-
It is cleaner and easier to read if you return early from the function when the function cannot be executed because of some condition.
-
Checking for equality is generally less prone to simple error than checking for inequality. For example, it is certainly easier to miss if you had written the inequality as
if (!parameter)
-
The second example means you need to indent your code an additional level.
I would recommend doing the first one because it is clearer but there is a school of thought that you should only have one exit point from a function. This is perhaps a good opportunity to use Exceptions if your language supports them usually via the throw
command. Such as…
protected void function(Object parameter)
if (parameter == null)
throw new ArgumentNullException("parameter must not be null.");
//... do things
}
This will tell the code calling the function that the problem occurred rather than allowing the application to continue under the assumption the function has completed correctly.
The first one is the better one because if you have more than one parameter to check it is much simplier to follow the flow. E.g.:
protected void function(Object a, Object b, Object c) {
if (a == null) {
return;
}
if (b == null) {
return;
}
if (c == null) {
return;
}
// Do stuff
}
Also as James noted I would use Exceptions if you language supports them.
6
I think there is not change in terms of performance because in both cases the main code of the function is not evaluated if the parameter is deemed inconsistent.
From this point of view, as superM says in his comment, there rest is pretty much up to you and should be as consistent as possible across your project.