Defensive Programming: Why You Shouldn't Check Input Parameters for Validity
Do you check input parameters of methods for validity? Well, maybe you shouldn't, and instead you should use validating decorators.
Join the DZone community and get the full member experience.Join For Free
do you check the input parameters of your methods for validity? i don't. i used to, but not anymore. i just let my methods crash with a null pointer and other exceptions when parameters are not valid. this may sound illogical, but only in the beginning. i'm suggesting you use validating decorators instead.
let's take a look at this rather typical java example:
, right? if we remove these validations, the code will be much shorter, but it will crash with rather confusing messages if
is provided by the client. moreover, if the file already exists, our
will silently overwrite it. pretty dangerous, right?
yes, we must protect ourselves, and we must be defensive.
but not this way, not by bloating the class with validations that have nothing to do with its core functionality. instead, we should use decorators to do the validation. here is how. first, there must be an interface
then, a class that implements the core functionality:
and, finally, a number of decorators that will protect us:
now, the client has the flexibility of composing a complex object from decorators that perform their specific tasks. the core object will do the reporting, while the decorators will validate parameters:
what do we achieve with this approach? first and foremost: smaller objects. and smaller objects always mean higher
class will always remain small, no matter how many validations we may invent in the future. the more things we need to validate, the more validating decorators we will create. all of them will be small and cohesive. and we'll be able to put them together in different variations.
besides that, this approach makes our code much more reusable , as classes perform very few operations and don't defend themselves by default. while being defensive is an important feature, we'll use validating decorators. but this will not always be the case. sometimes validation is just too expensive in terms of time and memory, and we may want to work directly with objects that don't defend themselves.
i also decided not to use the java validation api anymore for the same reason. its annotations make classes much more verbose and less cohesive. i'm using validating decorators instead.
Published at DZone with permission of Yegor Bugayenko. See the original article here.
Opinions expressed by DZone contributors are their own.