What is the best practice for when to check if something needs to be done?
Posted
by
changokun
on Programmers
See other posts from Programmers
or by changokun
Published on 2012-10-26T16:36:04Z
Indexed on
2012/10/26
23:16 UTC
Read the original article
Hit count: 392
programming-practices
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.
© Programmers or respective owner