I saw following recently in a pull request I was supposed to review. A ValueObject was used as an property – for a validator class.
class ValueObjectValidator { private ValueObject object; public ValueObjectValidator(ValueObject object) { this.object = object; } public bool isValid1() { // do something with the value object if (this.object) { return true; } return false; } public bool isValid2() { // do something with the value object if (this.object) { return true; } return false; } }
This has a couple of disadvantages in my point of view. First of all, although it is a validator, I can only use it once for one ValueObject. Of course getter and setter could be use, but than there is still a state in the validator. Is there any need for a state within a validator?
Generally speaking, I’d say no. A validator object provides a (or multiple) methods for validating a ValueObject. But the calls of the validator methods should be independent and thus avoiding side-effects.
ValueObjects should be used as parameters for methods, but not as properties – apart from representing a state.
In most cases ValueObject shouldn’t be a property of a class, but rather a parameter for a method and this method is then working on the ValueObject. Of course, if your class needs a state, then the state is most often be represented by a ValueObject (or a string).
There is one more thing to say: what to use as a property? Dependencies are used for properties. Dependencies are objects, which are needed by your concrete object to fulfill its work. Examples can be for example a DateTimeLibFacade for a validator performing some validation rules which are operating with DateTime.