What methods should Value Objects contain?

Value objects can contain methods. Otherwise they are just anemic models. Those methods prevent the feature envy code smell and ease refactoring. They manipulate object internals promoting cohesion and low coupling. But don't forget about the Open/Closed principle. If you add that method to the object, is the code still open to extension without modification?

Imagine a value object encapsulating a collection. Now you need a method to sort the items in the collection. Should the "sort" method be part of the collection object? If is there a way to change the sorting algorithm without code modification, then the answer is yes. Otherwise the answer is no. Move the "sort" method to a specific class whose responsibility is sorting.

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.