Don’t rely entity setters (order)

What this code does?

It’s a simple class that represent a DateTimeInterval with a flag named allDayLong that let an object of DateTimeInterval class to fill all day.

You can see that setFrom and setTo are affected from allDayLong flag: if is set, time of these DateTime are changed in order to fill all day.

But what happens when you don’t (can’t) control directly the order of setters calls? For example, if this entity is managed from other service (i.e.: symfony form type) and you can’t predict (trust) setters alternation? What happen if allDayLong is called after other setters? As you can imagine, object is not consistent as from and to has not the proper values.

Moreover this object represent a DateTimeInterval and is pretty senseless to create it without from and to interval bounds.

Value objects

To avoid setters order problems and object instantiation without any data, change DateTimeInterval class to be a value object and to avoid setters (as this kind of objects should be immutable)

To recap

  • Don’t need to care about setters order (of calls)
  • Entity is valid from instantiation to persist/unset
  • Changes to this object are not possibile as it’s a value object; if you need to change it, create a brand new one

Everything said there is valid and a good practice not only for this particular type of class, but whenever you need to check other members and you don’t want to rely on setters order of calls and whenever you are forced to call setters right after object instantiation just to make it “valid” (or initialized). Of course it’s not always possible to remove setters because they can have sense somewhere: you should never take a solution as a “pattern” and apply it here and there without evaluating your scenario.

Soon we will write and publish a post with an example of value object and symfony form. Stay tuned!

Articoli: 21

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.