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:

value-object

Looks reasonable and simple enough if we have simple use case. But what if we have other date properties?

value-object

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.

value-object

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:

value-object

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:

value-object

Methods, validations and operations specific to the property are now grouped into their respective classes, cleaning our Todo model.

Here’s our partial code:

value-object

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:

value-object

Cool right?

value-object

Thanks!


Join my newsletter and get monthly articles on productivity, habits, and decision making in your inbox.