Validation logic in Setter methods vs Validation classes/objects

While reading Antnee’s articles on some OOP techniques, I came across this thought about validation logic. In his article the validation logic is directly placed in setter methods, while sometimes I also see people creating validator objects which are used as service objects for the sole purpose of validating, especially in model layers.

So I wonder, have you considered this yet? What are the difference between the choice of putting validation logic in setter and in validator object? The latter seems to provide an additional layer of abstraction, but its arguable whether this layer of abstraction is beneficial or detrimental. In an earlier thread I made, there was a discussion of validation logic in domain models/services:

But now I want to expand the topic in a bit more broad way, just validation logic in a general sense. Do you prefer putting validation logic in the very class that needs validation itself with setters taking care of it, or to write separate validation logic for this. If you use both, what is a rule of thumb to determine when to use setters validation and when to use validation classes/objects?

Similar discussion:

I think it’s crucial that the validation is encapsulated within the object. However, it’s not unreasonable to provide a validation method if needs be, if you have a nice validation interface.

There are different levels of validation though. There is no such thing as an email type in PHP, there is only a string. Unless you have an email value object then you’ll be passing in a string into any method that needs an email address. In PHP7 we can type hint a string, but until then we have to do things like is_string()… Yuk!

Anyway, at some point you need to validate that the email address is actually an email address, and if you don’t want to validate in the object itself then you need to be absolutely sure that mistakes aren’t being made upstream. How many entry points are there to this object? If there’s just the one then sure, put the validation upstream, but if there are many then you’re going to be needing to validate all over the place. The only thing that really cares is the class on which you’re setting this property.

As with many things, there are loads of right answers, and only if you properly understand your domain will you be able to make the right decision. If you build it well and realise that you put it in the wrong place then you should be able to move it later easily.

Don’t be afraid to make mistakes. Try it the way you think is best, and if it’s wrong try it a different way. Just be sure to share your experiences as others may benefit from it too.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.