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!
DISCUSSION (2)

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 12

What Developers Should Know from Microsoft Build

We're clearly entering a new era for Microsoft and for developers that moves from tools and platforms to cloud and services.

READ POST
Follow @remotesynth to see more of their posts in your feed.
Guilherme Soares Valdevieso
Member since Oct 24, 2017
Trending on dev.to
What code snippets do you use?
#discuss #javascript #snippets
How do you shift between the coding mindset and other head spaces?
#discuss
Redesign of my portfolio
#showdev #webdev #career #frontend
Writing Beautiful Code
#webdev #productivity #php
We need a post-inbox era therapist
#google #discuss #productivity
How to start contributing to open source as a junior or newbie?
#discuss #beginners
Why Your Best Work is Hardest to Finish
#productivity #career #beginners
Lessons I learned from training with special forces that I use in software development
#beginners #career #motivation #dieliving