Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Don’t Add Unnecessary Checks to Your Code, Pretty Please!

DZone's Guide to

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.

· Java Zone
Free Resource

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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 .indexOf on 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).

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
programing ,maintainability ,validation

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}