This is the second post in the
Poka-yoke design series - also known as
encapsulation .
Many classes tend to consume or disclose primitive values, such as int, or string. While such primitives exist on any platform, their use can lead to procedural code. Moreover, they usually break encapsulation, allowing the assignment of incorrect values.
This problem has been discussed many times. Years earlier,
Jimmy Bogard provided an excellent
interpretation of the problem, as well as a guide to solve it . In connection with the development of
AutoFixture , I was also
affected by this problem some time ago . In fact, this post is a "placeholder".
It should be noted that both my post and Jimmy post show that strings and integer types do not sufficiently encapsulate concepts such as the postal code or phone number.
- If the zip code is represented by a string, then it is possible to assign a null, string.Empty, “foo”, a very long string, etc. The ZipCode class, written by Jimmy, encapsulates the concept, ensuring that an instance can only be created with the correct value.
- If the Danish phone number is represented by an integer, then it is possible to assign it 98, 0, int.MaxValue, etc. The DanishPhoneNumber class from the previous example encapsulates the concept, ensuring that an instance can only be created with the correct value.
The encapsulation remains broken as long as the concept represented by the primitive value can assume any of the possible values of the primitive type. However, this is rare.
"Smell" designThe class consumes a primitive type. However, further analysis shows that not all possible values of the type are valid.
')
Revised designWe encapsulate a primitive value in an object-value that contains the corresponding protective expressions, etc., in order to ensure that only correct instances can be created.
Primitives tend to be unreliable, but the value objects of such a propensity do not.