Getters and Setters

I get how Getters and Setters work but I am having a hard time telling when to use them and when not to use them. Can someone help me tell when to use Getters and Setters and when not to use them?

Sure. It largely depends on how you’re desigining your objects.

  • If you intend for them to be completely encapsulated (or as encapsulated as javascript will allow), then it becomes easy. If you are trying to hide every property from the end user, then you’ll need getters and setters for every property you want the end user to access.

  • If you are taking a value and transforming it before it gets stored into a property, then you’ll likely want to use a setter. Likewise, if data needs to be transformed before the end user can consume it, then you’ll likely want a getter.

  • If you are designing for your own use, it’s largely at your discretion. It may be good practice to use getters and setters, but hardly necessary. If you aren’t trying to simulate “private” properties, they can be overkill.

Here’s an example of how I recently used getters and setters, and it was very useful in my case:

I created a Timer class, and tried to make it as extensible, and as encapsulated as possible. I wanted it to be truly plug-and-play, but I also wanted great flexibility. So when you create one, using

let myTimer = new Timer({
  time: 180, 
  onTick: ()=>{
    console.log(`There are ${myTimer.time} seconds remaining!`);
    // Note that myTimer.time is a getter!
  onComplete: ()=>{
    console.log(`The timer has completed. Let's do it again!!`);
    myTimer.time = 360; // <-- THIS is a setter!
    myTimer.onComplete = () => { return true; } // <-- this is ALSO a setter. 
                                // I do the above so we don't keep looping.

So in my case, I wanted the user to be able to set and get the time in seconds, but I might convert it to milliseconds OR to a given end datetime, before I save it to a pseudo-private property. It wasn’t so much about the privacy of my variables, I gave them funky enough names internally that they’re pretty safe – but before they are stored, they’re converted to something else. And, when the user wants to use the getter, they’re converted back.

If you need to evaluate an expression before returning a value, use a getter. Its basically just a function disguised as a property.

1 Like