@
@
@Twitt2019-05-11 14:01:07
PHP
@Twitt, 2019-05-11 14:01:07

ValueObject - why?

Learned about ValueObject, and "smell" - Obsession with primitives. Here is an excerpt on the reasons for the appearance:

The programmer needed a field to store some data. He thought that creating a field of elementary type is much easier than starting a new class. This is what was done. Then another field was needed, and it was added in a similar way.

Let's say in the User class, there will be an orderBy field, I made a field, made setters, getters, in which I directly indicated by typing that setOrderBy(int $orderBy) would take a parameter and return an integer number, which I lose here compared to the one what would I have to do with the OrderBy class in which value would be validated to an int in the constructor? There are a lot of such examples, as for me, these are just extra classes that are not needed. Maybe someone can give an example why exactly ValueObject and not the way I described above?
At the same time, can you tell me why we need primitives if we can make a ValueObject?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maksim Fedorov, 2019-05-11
_

Such a Value Object was apparently created so that the logic for, for example, its creation is not fenced in the entities themselves, for example, this VO may have its own specific constructor. Also, this object may have sorting direction methods , up to the most interesting ones - this knowledge can also be superfluous for our essence ... There can be a lot of things, up to the fact that you need to look at some other data and build a sorting strategy. And in order not to violate the SRP - this whole logic was taken out into an independent object that is not an entity, which means in generally accepted terms - this is VO.
This can be with anything - with dates, with meta tags (the Meta object for different entities will usually have the same signature), for Id, and even there can be a Name object (it can contain the formation of short, long, abbreviated and all kinds of other states )
If you have a question, I note - reasonable, then you simply do not need such an abstraction due to the simplicity of this system node. Use int, but then name it with a friendly property like position or priority

E
Evgeny Romashkan, 2019-05-11
@EvgeniiR

Value Objects are always valid. You can't create a "date" VO, such as a DateTimeImmutable VO, and write April 35, 2019 into it.
They can consist of several primitives, for example Point from {x, y} or {x, y, z}
You can conveniently cram static constructors into it.
It is possible at the level of types to require a valid date at once.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question