Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthias Noback:
Modelling quantities - an exercise in designing value objects
Mar 29, 2018 @ 16:50:30

Matthias Noback has a new post on his site with his thoughts about the design of value objects. He makes use of an example he recently saw in the code he was working with: the idea of "quantities" of items.

I recently came across two interesting methods that were part of a bigger class that I had to redesign. [...] What happens [in the methods] is: we have an order line, which keeps track how much of a certain product has been "ordered", and then how much of it has been "delivered" so far. It also keeps track of how much is currently still "open". Changes to these "delivered" and "open" quantities happens when we "process" a delivery, or "undo" a delivery.

I was reminded of a recent blog post by Nicolò Pignatelli where he quoted a question from another programming website. Adopted to the situation at hand: "Which variable type would you use for representing a quantity? Integer, Float or String" It's a trick question, because all the answers are wrong. Nicolò advises not to use a primitive type value, but to design a value object that can represent a quantity.

He then walks through the process for refactoring this quantity handling out into a value object replacing the current float handling. He recommends applying more thought to how the object will be used and how the different types (open, ordered and delivered) relate to each other. He also includes examples of how to replace the add/subtract operations in the original code while still using value objects as immutable constructs.

tagged: value object model design tutorial quantity

Link: https://matthiasnoback.nl/2018/03/modelling-quanities-an-exercise-in-designing-value-objects/


Trending Topics: