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?

Did you find this post useful? Show some love!

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 May 18

Why do employers check job candidates' GitHub profiles?

It seems to me like a pretty weak way to get an apples-to-apples impression of ...

READ POST
Follow @ben to see more of their posts in your feed.
Guilherme Soares Valdevieso
Member since Oct 24, 2017
Trending on dev.to
What are your programming blogs?
#discuss
Ever feel like you have "Programming Synesthesia"?
#discuss #programming #productivity
What's your approach to fixing a "long-term" hairy bug?
#discuss
Follow Friday!
#discuss
Which contentious opinions in programming actually matter?
#discuss #webdev #programming #grannyrulescomments
Does anyone else feel bothered when people term us as coders instead of developers or programmers..?
#discuss
How do you get a decent estimate on the time it will take to complete a task?
#discuss #work
When is code "too clever" / how do you think about readability/cognitive load?
#discuss