Making code clearer with Value Objects
Imagine you have a todo project. You have this in your code to get a todo
and check if it’s due today:
Looks reasonable and simple enough if we have simple use case. But what if we have other date properties?
todo.IsToday
seems ambigous now since we have other dates to think about in our class. Are we trying to imply the todo is due today? Or it is created today?
We can make this better understandable by making the calls more explicit i.e.
Good enough. But what if we need to handle more use cases related to due date and for other dates? We could arrive with this code:
We will now have a very fat model with methods and operations that matters only to specific property.
Also, we can’t reuse some of the operation like isCreatedToday
in other classes that might have that property. We would have duplicate implementation of createdAt == DateTime.Now
A better approach then is to introduce value objects. Like this:
Methods, validations and operations specific to the property are now grouped into their respective classes, cleaning our Todo
model.
Here’s our partial code:
A plus in doing this is that we will have simple mapping from our domain object to data-transfer object. Here’s a sample JSON output:
Cool right?
Thanks!