Code quality via static typing — Part 2

Improve code quality by methods input/output strict typing

Guy Yogev
2 min readApr 21, 2022

Part of Bitesize software building blocks series.

Photo by Andreas Felske on Unsplash

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.
The “getByEmail” method is weak, it allows the passing of invalid input, which can lead to unexpected behavior.

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.

https://khalilstemmler.com/articles/typescript-value-object/

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.

  1. The caller must create an Email with a factory, which would validate it.
  2. The getByEmail accepts only Email inputs.

--

--