How many checks against null are suitable?

I have this problem when a variable is missing a field and the user receives a warning that this or the same variable does not have this or that property. In the simple case, this is very straightforward.

if(field) doSomething(field.subField); 

However, in empirical situations, I found myself getting to this absurd bust.

 if(!data || !data.records || !data.records[0] || !data.records[0].field || !data.records[0].field.id) return null; doSomething(data); 

I mean, c'mon is like a pipe if I'm a plumber, not a developer. Thus, I have a very strong feeling that my checks, although sufficient, may be a little too much - too crowded. Is there an agreement in JS about when to validate?

+6
source share
2 answers

I am going to come up with a conflicting opinion.

In JavaScript, do not check for null values ​​in places where this should not really happen. In other words, your idea of ​​checking each nested property for zeros is a bit overdone and only complicates your script.

In my experience, I learned to just skip the script error. This is somewhat contrary to intuition for someone writing C code or database code where raw null can cause a server crash or data corruption, however, in the script world it is better to find out about your error sooner rather than later. If your page continues to load without indicating that something unexpected happened, it will simply appear as strange errors later when the user clicks a button or submits a form.

My advice :

Check for null only if you are ready to do something. If you have a web service that can return null if something goes wrong, check this and display an error message. If you return a nonzero value, assume it is a valid value and continue. There is no reason to prevent your whole script from checking zero, which will not actually bring any real benefit to your program.

+6
source

You should usually make sure that if an object exists, it always has a basic set of properties that makes it usable.

For example, if the data variable has a value at all, it will be an object with the records attribute, which is always an array, even if it is empty. If the array contains anything, it should always be objects that have the field property, which is an object that always has the id property. This will lead to a reduction in checks:

 if (!data || data.records.length == 0) { return null; } 
+2
source

All Articles