Let’s say I have a function that does x
. I pass it a variable, and if the variable is not null, it does some action. And I have an array of variables and I’m going to run this function on each one.
Inside the function, it seems like a good practice is to check if the argument is null before proceeding. A null argument is not an error, it just causes an early return.
I could loop through the array and pass each value to the function, and the function will work great.
Is there any value to checking if the var is null and only calling the function if it is not null during the loop?
This doubles up on the checking for null, but:
- Is there any gained value?
- Is there any gain on not calling a function?
- Any readability gain on the loop in the parent code?
For the sake of my question, let’s assume that checking for null will always be the case. I can see how checking for some object property might change over time, which makes the first check a bad idea.
Pseudo code example:
for(thing in array) {
x(thing)
}
Versus:
for(thing in array) {
if(thing not null) x(thing)
}
If there are language-specific concerns, I’m a web developer working in PHP and JavaScript.
Is there any value to checking if the var is null and only calling the
function if it is not null during the loop?
In practical terms, very little unless you’re using a language that imposes incredibly high function call overhead.
If your function claims it will “do x if the thing you pass is not null
, nothing if it is,” then inside the function is where that behavior should be determined. Otherwise, the first time the function is called with a null
pointer, you run the risk of unpredictable or undesired behavior. Additionally, if you want to change the function’s behavior in the presence of a null
, you only have to change it in one place.
3
If passing null
is legal from the point of view of the function that you call, adding an additional check outside the loop is superfluous, and should be avoided.
The classic example is C’s free
function which allows NULL
s: technically, null-checking before the call does no harm, but it clutters the code, and has negative impact on readability.
With that said, you can save yourself some CPU cycles when you pass other parameters that must be prepared:
var index = 0
for(thing in array) {
if(thing not null) x(thing, prepareOtherParameters(index))
index++
}
is faster than the same call without a “guard”, because calls to prepareOtherParameters
is avoided.
I don’t know how you populate the array, but if it is a database query, you can tell the SQL to omit the rows where that column is null. Maybe the correct thing to do is the array not having null values to begin with.
Either way, since parameter beeing null is not an error, then the first option is OK.
for(thing in array) {
x(thing)
}
There shouldn’t be any apreciable difference in performance, etc.