When working with service oriented applications we often use system types to identify / query our business entities.
IList<Product> GetProductsByUserAndCategoryId(int userId, int categoryId);
However we can’t prevent developpers to pass another identifier which is not a “User Identifier” and not a “Category Identifier”, or maybe inverse the ids on method call.
So a solution is to use Strongly Type Identifiers, like this :
IList<Product> GetProductsByUserAndCategoryId(UserId userId, CategoryId categoryId);
GetProductsByUserAndCategoryId(new UserId(123), new CategoryId(456));
What do you think about this ? Pros and cons ?
Well, first off, this only shifts the moment of validation; it still has to happen, preferably as soon as a
UserId(…) is instantiated. You also have to see whether this really has any benefits in your system at all.On the other hand, I do think that it prevents bugs by disambiguating between inherently ambiguous numbers. Letting the same type
intstand for two completely unrelated things can actually be dangerous.In a recent code review (for a course at University) the no. 1 error students had made was to use an integer in the wrong way. Having used different types as in your example would effectively have prevented this source of errors altogether.
So, in summary, I don’t think there’s a blanked answer but I am generally in favour of such idioms. This is one of the real benefits of a strict type system.