loading...
markdown guide
 

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; }
}
 

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

Classic DEV Post from Dec 29 '19

The Dream of C# 9.0

As part of the final entry in the C# Advent series of 2019, Calvin Allen touched on some proposals in...

Guilherme Soares Valdevieso profile image

Hey there reader...

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❤️