Why do getters and setters often have the same name, and how does that not cause problems?

I’m pretty new to learning to program seriously, but I have dabbled in many different languages over the years, and I am trying to get my head around how it is possible that a getter and a setter can have the same name, and this not cause problems for the parser.

So for example in this lesson the correct solution is to add a setter with the same name as the getter which is already there.

How does this not cause confusion and conflict I wonder, both for the parser, and for humans reading the code?

getters and setters in JavaScript use protected keywords (i.e. set and get) to define what should happen when object properties are accessed in specific ways. Getters react to when you’re trying to read the property of an object, and setters react when you’re trying to write to the property of an object.

You could create separate functions with names that clearly distinguish what’s happening, like getNumOfSensors and setNumOfSensors, or you can more directly access and mutate those properties. It’s merely a matter of preference, but it isn’t confusing when using the accessor notation because the syntax is just like how you’d use it normally. For example,

const me = {
  _firstName: 'Taylor',
  get firstName(){
    return this.firstName
  },
  set firstName(newFirstName){
    this.firstName = newFirstName
  },
}

// What's your name?
console.log(me.firstName)

// I want to change my name
me.firstName = 'John'

The way I accessed and changed my first name is no different than if I had never defined a getter and setter, so the syntax is simple and consistent. However, by defining a getter and setter, I can put restrictions or make sure certain checks occur when the first name is being accessed. Like I might want to make sure that I don’t accidentally set my first name to an empty string. So I can make sure there’s a check in the setter for that.

I could also write it like this:

const me = {
  firstName: 'Taylor',
  function getFirstName() { 
    return this.firstName
  },
  function setFirstName(newFirstName) {
    this.firstName = newFirstName
  },
}

console.log(me.getFirstName())

setFirstName('John')

It’s really just 2 different ways of doing the same thing. I prefer functional programming overall, so I like the second one better, but I understand the first one just as well and I get its’ appeal.

3 Likes

Circular reference can be a problem.

1 Like