Appreciating the value of Value Objects
In my most recent employment, I got to work on refactoring some legacy code and one of things that I've learned to appreciate is the use of Value Objects.
The domain focused on money and tax rates of various sorts so the code was filled with decimal variable types. The following is a simplified example:
As the codebase grows larger, and variables like Tax are coming in from the database or maybe an API, it becomes harder for the developers to keep track whether Tax is in percentage or decimal value form. This is where making use of value objects can help developers work efficiently by eliminating the ambiguity.
The added benefit is that whenever an operation is required such as salary * taxRate, there is no accidentally multiplying the rate 100 times more than it should be. If we want to take it a step even further, we can encapsulate such operations to avoid mistakes entirely:
Here we add the ApplyTo behavior to the Rate class in order to remove the thinking entirely. This is one of the ways where we can start moving domain understanding into the code.
While this may seem overkill for this simple example, we start appreciating it when we have complex models. An invoice can for example be comprised of different components: invoice items, expenses, etc. where various types of taxes are applied to the various parts.
Taking the time to build domain models that correctly represent the domain logic can save a lot of time especially for new developers just getting into the code.
Senior Software Engineering Manager at Unity Technologies. 3x AWS, 2x Google Cloud certified. Non-fungible.
3 年Salary * 100 sounds like a nice problem fo have. ??