Language: EN

que-son-getters-y-setters-en-programacion

What are getters and setters

The getter and setter methods allow to control how the internal state of an object is accessed and modified.

They provide a controlled way to update the internal state of an object, allowing validations and restrictions on the values that can be assigned.

The getter methods allow access to the value of a private or protected property of a class.

On the other hand, setter methods allow modifying the value of a private or protected property of a class.

Both getter and setter methods can include additional logic, such as data transformation or controlled access, before returning the value.

Otherwise, the getter or setter method has nothing special. It’s just a naming convention we use. But otherwise, they are absolutely normal instance methods.

Practical case

Suppose we have a Person class that has a private variable name. Creating a getter and setter method for this property is as simple as creating two methods.

  • The GetName() method that returns the name variable
  • The SetName() method that replaces the name variable

That is, something like this,

public class Person
{
    private string name;

    // Getter
    public string GetName()
    {
        return name;
    }
    
    // Setter
    public void SetName(string value)
    {
        name = value;        
    }
}

As we can see, it’s just a naming convention for two methods that have minimal logic to manage the private variable name.

Examples in different languages

Let’s look at an example of implementation in different programming languages,

In C#, the getter and setter functions are implemented using conventional methods to access and modify private fields of a class.

public class Person
{
    private string name;

    // Getter
    public string GetName()
    {
        return name;
    }

    // Setter
    public void SetName(string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            name = value;
        }
    }
}

// Usage
Person person = new Person();
person.SetName("Juan");
Console.WriteLine(person.GetName());

In C++, access methods (getters) and modification methods (setters) can be defined to interact with private fields of a class.

#include <iostream>
#include <string>

class Person {
private:
    std::string name;

public:
    // Getter
    std::string getName() const {
        return name;
    }

    // Setter
    void setName(const std::string& value) {
        if (!value.empty()) {
            name = value;
        }
    }
};

// Usage
int main() {
    Person person;
    person.setName("Juan");
    std::cout << person.getName() << std::endl;
    return 0;
}

In JavaScript, there are no getter and setter functions as in other languages, but they can be simulated using methods to access and modify private fields of an object.

class Person {
    constructor() {
        this._name = "";
    }

    // Getter
    getName() {
        return this._name;
    }

    // Setter
    setName(value) {
        if (value) {
            this._name = value;
        }
    }
}

// Usage
const person = new Person();
person.setName("Juan");
console.log(person.getName());

In TypeScript, properties can be defined using the get and set syntax to interact with private fields of a class similar to C#.

class Person {
    private name: string = "";

    // Getter
    getName(): string {
        return this.name;
    }

    // Setter
    setName(value: string): void {
        if (value) {
            this.name = value;
        }
    }
}

// Usage
const person = new Person();
person.setName("Juan");
console.log(person.getName());

In Python, decorators @property and @name.setter can be used to define getter and setter methods as part of a property.

class Person:
    def __init__(self):
        self._name = ""

    # Getter
    def get_name(self):
        return self._name

    # Setter
    def set_name(self, value):
        if value:
            self._name = value

# Usage
person = Person()
person.set_name("Juan")
print(person.get_name())

Best practices Tips

Like almost anything in programming, getter and setter methods are not exempt from some controversy. Some people defend them, while others think they are not even necessary.

Among the detractors, the main argument is that it doesn’t make much sense to create methods for all variables, simply to access them. Why not just use the variables directly for that?

I tell you the classic version in favor of their existence. In theory, the variables of an object should always be private, as they constitute the internal state of the instance.

Access to them must be “controlled”, and for this, there are getter and setter methods. Just as you don’t let anyone mess around with your belly and touch your kidneys.

In this way, getter and setter methods allow to hide the internal implementation of a class and expose only what is necessary. This protects data integrity, adds validations, and avoids uncontrolled access.

On the other hand, by accessing through getter and setter methods, it always gives me a certain freedom to modify and maintain the behavior of a class, for example, in the face of future changes.

In addition, unlike variables, I can override the behavior of getter and setter methods in child classes. This is a great advantage and also facilitates tasks such as testing.

In any case, if you use getter and setter methods, the first rule is to keep them simple and clear. They have to be very light functions, just to do minimal validation and nothing else.

Nothing reading from a database, doing a complicated calculation, or any other heavy or side effects task. getter and setter methods have to be simple and fast.

To ease the overhead of having to define getter and setter methods for all variables, many languages implement the concept of Properties, which we will see in the next article.