Don’t Add Unnecessary Checks to Your Code, Pretty Please!
Wondering if you should add checks to your code? They may be unnecessary. Read on to learn about why you'd better not chiggity check your code, lest you wriggity wreck your code.
Join the DZone community and get the full member experience.Join For Free
Defensive programming suggests that we should add various checks to our code to ensure the presence and proper shape and type of data. But there is one important rule – only add a check if you know that thing can really happen. Don’t add random checks just to be sure – because you are misleading the next developer.
Imagine you need to call
product_code. You might be tempted to add
if (!_.isString(product_code)) return false;
Now you are safe and your code can’t fail. But when I read this code, I immediately think:
Oh, I believed product_code to be always a string but obviously it is not always the case. It must have happened in the past or the author wouldn’t have added this check. I wonder what are the possible non-string values. And what does it mean and how should I handle them?
So by adding this check you have eroded significantly my trust in the data or rather trust in my mental model of the data (domains, possible values) and it has become much more fuzzy. Now I have to always assume that product_code can be something (what?!) else than a string, check for it everywhere and wonder what to do about it.
I have maintained a lot of legacy code, often encountering checks like this – and it always lead to an erosion of my understanding of the system and increased insecurity. So, pretty please, do not add such checks just for the sake defensiveness. After all, you don’t want to be practicing Programming by Coincidence, do you?
Sometimes you need checks because the data comes from outside the system that you control. Then you should add the checks (only) to the boundary of the system so that every internal part of it can then rely on the data being as expected. (Here we would add the code to check/ensure that product_code is a string to the module that fetched product catalog information from an external service).
Opinions expressed by DZone contributors are their own.