Strongly identify type identifiers

When working with service-oriented applications, we often use system types to identify / query our business objects.

IList<Product> GetProductsByUserAndCategoryId(int userId, int categoryId); 

However, we cannot prevent developers from passing another identifier that is not a "User Identifier" and not a "Category Identifier", or, possibly, inverts the identifiers when the method is called.

Thus, the solution is to use strong type identifiers, for example:

 IList<Product> GetProductsByUserAndCategoryId(UserId userId, CategoryId categoryId); GetProductsByUserAndCategoryId(new UserId(123), new CategoryId(456)); 

What do you think about this? Pros and cons?

+4
source share
2 answers

Pros and cons?

Well, firstly, it only shifts the moment of verification; this should happen, preferably as soon as UserId (...) is created. You should also see if this really has any advantages in your system.

On the other hand, I believe that it prevents errors by eliminating the ambiguity between internally ambiguous numbers. Providing the same int type means two completely unrelated things that can be dangerous.

In a recent code review (for a university course) no. One mistake made by students was to use an integer in the wrong way. Using different types, as in your example, would effectively prevent this source of errors altogether.

So, in general, I do not think this is an empty answer, but I generally support such idioms . This is one of the real advantages of a strict type system.

+3
source

The only real conflict for me is to enter an additional code. The code is becoming more rigidly defined, which is good, but now there is additional friction to actually write it. It is simply a question of how to spend the extra time and effort to defeat saved service and reliability later.

The same with any methodology. TDD guys spend time scaffolding and testing ahead, hoping that it will make the code more reliable and more easily maintained. - Many of them say that this also saves time ... but I have doubts :) -

Ultimately, I agree with Mr. Rudolph. This is the power of strict type systems; Use it to your advantage.

+1
source

Source: https://habr.com/ru/post/1302730/


All Articles