Over a million developers have joined DZone.

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

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

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

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

programing ,maintainability ,validation

Opinions expressed by DZone contributors are their own.


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.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}