Code quality via static typing — Part 2
Rule of thumb
Create domain spesific data structures with Value Object Factories
Every system has its own domain-specific requirements. Those requirements can be enforced by static typing. However, basic types can go so far.
For example, say we need to represent a User, and one of its requirements is
email
— A valid email address
If we define email
as a simple string, methods that expect email
input would need to validate it on run time (in the method, the caller, or both).
We can add input validation, to make the code is safer, but it would result in
- More complex, less readable code.
- Requires more unit tests in order to reach 100% coverage.
If we provide strict well-typed methods, we can achieve high code quality, with less code, and fewer unit tests.
Value Objects
The Value object pattern encapsulates data that is not unique.
One of its perks is that it encapsulates the object fields.
Value Objects Factories
Using Factory pattern we define a single place in our code base that can instantiate a value object. In the case of Email
factory.
Now our getByEmail
is type-safe. There is a single path to reach it.
- The caller must create an
Email
with a factory, which would validate it. - The
getByEmail
accepts onlyEmail
inputs.