Getter functions in Javascript

Photo by Christopher Gower on Unsplash

In object-oriented programming, it’s a common practice to use functions to access the properties of an object. JavaScript provides a syntactic sugar for this pattern through getter functions. With the get keyword, you can define a function that will be used to access a property as if it was an attribute. Let’s explore how getter functions can make your code more intuitive and maintainable.

Traditional Function vs Getter

Consider a class Person with a method to return a full name:

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}

const person = new Person('Jane', 'Doe');
console.log(person.getFullName()); // Output: Jane Doe

This is straightforward, but the method getFullName needs to be called as a function (getFullName()). Let’s see how getters can simplify this.

Introducing Getters

Transforming getFullName into a getter allows us to access the full name as a property:

class Person {
constructor(public firstName: string, public lastName: string) {}

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

const person = new Person('Jane', 'Doe');
console.log(person.fullName); // Output: Jane Doe

With the getter fullName, you access the full name just like any other property, without the need to invoke it as a function.

Advantages of Using Getters

  1. Readability: Accessors (getters) provide a way to read object properties intuitively, improving the readability of your code.
  2. Encapsulation: By using a getter, you can control how a property is accessed and even compute its value on-the-fly without the consumer knowing the underlying logic.
  3. No Side-Effects: It becomes clear that fullName is not a method that performs operations or changes state; it’s simply a way to get information.
  4. Maintainability: If the logic for deriving a full name becomes more complex over time, you can handle it within the getter without affecting how it’s accessed.

Best Practices

While getters are powerful, they should be used judiciously. Here are a couple of best practices to keep in mind:

  • No Heavy Computation: Avoid using getters for properties that require significant computation or have side effects. Getters are expected to be fast and idempotent.
  • Consistency: If a property has a getter, it should also have a corresponding setter if the property is meant to be modified. This ensures consistency in property access patterns.

Conclusion

Getters provide an elegant way to access properties on objects, helping you to write code that’s easy to read and maintain. By converting simple functions that return values into getters, you make it more evident that there’s no computation or side effects — just a straightforward retrieval of information. It’s a subtle but impactful enhancement to the expressiveness of your code.

,