2

The following two codes are equivalent and provide the same results:

1

const menu = {
    _courses: {
        appetizers: [],
        mains: [],
        desserts: [],
    },
  
    get appetizers() {
      return this._courses.appetizers;
    },
    set appetizers(appetizer) {
        this._courses.appetizers= appetizer;
    }
}

menu.appetizers.push(['food']);
console.log(menu.appetizers);

2

const menu = {
    _courses: {
        appetizers: [],
        mains: [],
        desserts: [],
    },
}

menu._courses.appetizers.push(['food']);
console.log(menu._courses.appetizers);

1st method uses getter/setter whereas second directly access the property, so my question is..for me 2nd method is more understandable then why getter/setter is "Better" way?

There are many threads proposing why getter/setter should be used, but I was curious to know for the example I have given, which way is better?

Community
  • 1
  • 1
Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • Simple usecase: *I want to create a property **Age** which should only accept numbers* – Rajesh Sep 19 '19 at 11:41
  • can you elaborate your comment and post it as answer as i dont get it – Abhay Maurya Sep 19 '19 at 11:41
  • 1
    https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors – Figaro Cat Sep 19 '19 at 11:42
  • @FigaroCat i understand the rush for closing but please read the question, its not the same – Abhay Maurya Sep 19 '19 at 11:43
  • @nickzoum its not, i checked that one...i wouldnt ask it if it was... – Abhay Maurya Sep 19 '19 at 11:43
  • 3
    @Learner it's "better" because you can transparently change what `menu.appetizers.push` writes to. If you change your data structure to `{ _meals: { starters: [] }}` then you just need to change a single line of code to have your codebase use it - the body of `get appetizers` becomes `return this._meals.starters` and you're done. Otherwise you have to change every single code that uses `._courses.appetizers`. And this is basically what the proposed dupe already says - getters and setters will hide the internal representation to allow greater flexibility of the interface. – VLAZ Sep 19 '19 at 11:48
  • @VLAZ can you add your comment as an answer so that i can accept it? good explanation, thanks! – Abhay Maurya Sep 19 '19 at 11:50
  • 1
    @Learner why? That's already covered by the other question. – VLAZ Sep 19 '19 at 11:50
  • @VLAZ right, my bad – Abhay Maurya Sep 19 '19 at 11:51
  • 4
    I read it. It is still a duplicate; the link nicely lays out the multitude of reasons why accessors are used. Specifically, VLAZ's comment is covered by "Hiding the internal representation of the property" and "Insulating your public interface from change". If you think it is not the same, _you_ need to demonstrate which case is not covered, not just claim it is not the same. – Amadan Sep 19 '19 at 11:57

2 Answers2

1

Getters and setters are data abstraction and provides an opportunity for validation check.

Sample:

Based on my comment,

I want to create a property Age which should only accept numbers

following is a sample that adds intelligence to the class properties about their possible values. This is one of the simple usecase where getters and setters are helpful

function SimplePerson(name, age) {
  this.name = name;
  this.age = age;
}

function SmartPerson(name, age) {
  // Private validators
  function isNameValid(value) {
    return /^[a-z']+$/i.test(value);
  }

  function isAgeValid(value) {
    return /\d+/.test(value)
  }

  // Private property
  var name = '';
  var age;
  Object.defineProperty(this, 'name', {
    get: function() {
      return name;
    },
    set: function(value) {
      if (isNameValid(value)) {
        name = value;
      } else {
        console.log('Value passed for Name is incorrect')
      }
    }
  })

  Object.defineProperty(this, 'age', {
    get: function() {
      return name;
    },
    set: function(value) {
      if (isAgeValid(value)) {
        name = value;
      } else {
        console.log('Value passed for Age is incorrect')
      }
    }
  })
  
  this.name = name;
  this.age = age;
}

var simplePerson = new SimplePerson(123, 'Foo Bar');
var smartPerson = new SmartPerson(123, 'Foo Bar');

console.log(simplePerson, smartPerson)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

As getter/setter gives more freedom to write logic before setting/getting the value. I.e. you can keep check of the type of etc.

Why use getters and setters in JavaScript

A difference between using a getter or setter and using a standard function is that getters/setters are automatically invoked on assignment. So it looks just like a normal property but behind the scenes you can have extra logic (or checks) to be run just before or after the assignment.

So if you decide to add this kind of extra logic to one of the existing object properties that is already being referenced, you can convert it to getter/setter style without altering the rest of the code that has access to that property.

Community
  • 1
  • 1
tejp124
  • 356
  • 3
  • 12