Reply to comment

It depends on the context

If you are sure the context for a given object will always be the same, then yes, the behavior can be built in. But suppose that validation for a given chunk of data, say the core data for an invoice/order, changes with the context. What do you do then? Every time you have a new business rule that comes up where the validation for that telephone number has to validated in a different way, do you add a new method:

order.isValid() v. order.isValidForXYZ() v. order.isValidForABC()?

or order.isValid(someExternalRule)?

For each of those you are doing something that is making the code fragile and/or requires the code to be changed and/or requires you to make a subclass, all of which will have to be tested in some way.

Now, if instead you have some simple value object (DTO, whatever you want to call it), with no or minimal behavior, the object itself can be validated externally - preferably by an object implementing some interface so as business rules change and/or are added to, it is the rule that needs to be tested, not the object simply holding the data. Yes, some external object has knowledge of some of the internals of the value object (as much as you care to expose), but you don't have a value object that needs to know every single context it may be used in. In my experience, value objects like this are often used in many different contexts, or you wind up with duplicates of these objects for the different contexts, or you wind up with an object that has all this behavior internal to itself and may be very fragile and/or bloated as a result.

No one solution is golden or a big steaming pile of feces, although the fragile and bloated know it all object that can handle every context is usually to be avoided (IMO). It depends on the context, and that is where the judgement of the developer comes into play. Yes, by all means, talk about the disadvantages, but also mention the advantages and different contexts.

Reply

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.