DEV Community

Guilherme Soares Valdevieso
Guilherme Soares Valdevieso

Posted on

What about getters and setters?

I would like to know, your opinion about the use of getters and setters in several languages as PHP, C#, JavaScript, etc. It's a good way to encapsulate behaviors, validations?

Top comments (2)

Collapse
 
courier10pt profile image
Bob van Hoove • Edited

Getters and setters work well when updating the object at the property level is what you want. For instance when you manipulate ORM generated data transfer objects.

But for 'domain objects' I think there's an advantage to have a dedicated method with a meaningful name for any modification to the entity. The method may even return a Failed result or raise an Exception.

A typical example could be a bank account. The rules for adding / withdrawing may be very different whereas they both manipulate the balance.

// implicit logic in the setter
//
public class Account1
{
    // typical account details omitted ...

    private decimal _balance;

    public decimal Balance
    {
        get { return _balance; }
        set
        {
            // both logic for adding and withdrawing cash would
            // end up here
        }
    }
}

// explicit methods with their own rules
//
public class Account2
{
    // typical account details omitted ...

    public void Add(decimal amount)
    {
        // adding rules go here
    }

    public void Withdraw(decimal amount)
    {
        // withdrawal rules go here
    }

    public decimal Balance { get; private set; }
}
Collapse
 
gsvaldevieso profile image
Guilherme Soares Valdevieso

Thank you for detailed response! I definitely agree with you!