DEV Community

Discarding setters

Aleksi Kauppila on September 08, 2018

Setters, or mutators are used very commonly when working with classes. Almost every person who's ever written a class has also written some setter ...
Collapse
 
bgadrian profile image
Adrian B.G.

Nothing is white or black, do not take it to extreme.

Use setters only when needed, not by default, prefer immutability, and that is it.

They are not the Evil or Satan, just a tool, use it when needed.

Collapse
 
olivermensahdev profile image
Oliver Mensah

That's an awesome piece. However, I find that setters have a place in value objects where mutability is really essential. But in services setters are should not be allowed as they are supposed to be immutability created.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Thanks Oliver!

I'm curious, why do you think it's essential that value objects are mutable?

final class EmailAddress
{
    private $address;

    public function __construct(string $emailAddress)
    {
        $this->address = $emailAddress;
    }
    // ...
}

What benefits would we gain if this example was mutable? Or, would it make DateTime worse, if calling $dateTime->modify("+1 day") would return a new instance of DateTime instead of altering it's inner state?

Collapse
 
olivermensahdev profile image
Oliver Mensah

Not in cases that setters and gettings will be valuable. In this case, using setters won't be of much importance. In the case that you want setters to be used, the emphasis on constructor injection is less as compared to settor injection.