"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What are Getters and Setters and When Should You Use Them?

What are Getters and Setters and When Should You Use Them?

Published on 2025-01-26
Browse:959

What are Getters and Setters and When Should You Use Them?

Understanding Getters and Setters for Data Manipulation

Getters and setters are crucial accessor methods used in object-oriented programming to control data access and manipulation within an object. They provide a controlled way to retrieve and update internal object properties.

What Getters and Setters Do

  • Getters: Define a method that returns the value of a private or protected property.
  • Setters: Define a method that allows the assignment of a value to a private or protected property.

When to Use Getters and Setters

Using getters and setters is highly recommended when:

  • Maintaining data encapsulation (keeping properties private or protected).
  • Validating data before assigning it to a property.
  • Performing additional operations before or after accessing/modifying a property.

Simple Examples

Consider the following example in JavaScript:

class Person {
  #firstName;
  #lastName;

  get fullName() {
    return `${this.#firstName} ${this.#lastName}`;
  }

  set fullName(name) {
    const [firstName, lastName] = name.split(" ");
    this.#firstName = firstName;
    this.#lastName = lastName;
  }
}

const person = new Person();
person.fullName = "John Doe";
console.log(person.fullName); // Output: "John Doe"

In this example:

  • The getter fullName returns the full name (concatenated first and last name).
  • The setter fullName takes a new full name, splits it into first and last name, and updates the corresponding private properties.

Additional Considerations

As demonstrated in the example, setters can also be used to update related values. For instance, if you had a birthday property, you could use a setter to validate the date and perform calculations related to the individual's age.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3