Collections and Primitive Obsession

1. Preamble

Primitive Obsession is an anti-pattern that takes place when you overuse primitive types, especially to model your domain.

  • The use of string to represent email addresses. A custom-built Email class (a value object) would be much better here.
  • The use of int to model the concept of money, instead of introducing a Money value object.

2. Custom collection classes

But what about primitive obsession with collections?

public class Customer
{
public IReadOnlyList<Order> Orders { get; }
}
public class Customer
{
public OrderList Orders { get; }
}

2.1. Collection of related entities

Let’s first discuss a collection of related entities. Our initial example is exactly this: a list of orders related to a customer.

public class Customer
{
public IReadOnlyList<Order> Orders { get; }
}
  • Make sure the Orders property can’t be modified directly. This is already done by representing that property as an IReadOnlyList.
  • Introduce a separate method in Customer with all the required checks baked in.
public class Customer
{
private List<Order> _orders;
public IReadOnlyList<Order> Orders => _orders;
public void AddOrder(Order order)
{
if (_orders.Contains(order))
throw new Exception();
_orders.Add(order);
}
}

2.2. Root-level collection of entities

On the other hand, if the collection doesn’t belong to any other entity, then it does make sense to create a separate class for it.

public class OnlineUsers
{
private List<User> _users;
public void ForceLogOff(long userId)
{
/* Log off the user */
}
}

3. Summary

  • Primitive obsession is the use of primitive types (instead of custom-built types) to model the domain.
  • You may or may not need a custom class for a collection.
  • If the collection is a collection of related entities that are attached to a parent entity, then that parent entity essentially acts as the custom class. You don’t need a separate class for the collection itself.
  • If the collection is a root-level collection, then you do need a custom class for it (assuming additional functionality is needed on top of that collection).

4. Related

Subscribe

Subscribe to read more articles like this: https://enterprisecraftsmanship.com/subscribe

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store