Meal Maker - why does dev walkthrough ignore getter and setter methods?

Hi! I’ve just finished the “Meal Maker” project. It was by far the toughest so far!

Anyways, I watched the pro dev walkthrough once I’d finished, to compare approaches, and noticed his addDishToCourse (…) and getRandomDishFromCourse(…) methods totally bypass the getter and setter methods.

GET RANDOM DISH
menu = {

get appetizers(){
return this._courses.appetizers;
},

}

pro dev code:
getRandomDishFromCourse(courseName) {
const dishes = this._courses[courseName]; // grabs course dishes from the private _courses[courseName] directly.

},

My code:
getRandomDishFromCourse(courseName) {
const dishes = this[courseName]; // uses the getter to get the array of course dishes

},

ADD DISH TO COURSE
My code:
menu = {

set appetizers(appetizerIn){
this._courses.appetizers.push(appetizerIn);
},

},
addDishToCourse (courseName, dishName, dishPrice) {
const dish = {dishName,
dishPrice};
if (courseName === ‘appetizers’) {
this.appetizers = dish; // pushes the object to the setter method, and the setter pushes to _courses.
}

Dev code:
set appetizers(appetizers) {
this._courses.appetizers = appetizers // does this even ever get used?!?
},

addDishToCourse (courseName, dishName, dishPrice) {
const dish = {name: dishName, price: dishPrice,};
return this._courses[courseName].push(dish); // pushes the dish directly to the private _courses[courseName] object
};

As far as I can tell he not once uses the setter methods we were asked to create, as he mutates the course object directly.

I thought the whole point of getter and setter methods was to call these, so that you didn’t have to directly manipulate values of a ‘private’ key?!?

Any help making sense, with regards to best practices greatly appreciated. It just doesn’t seem best practice to ignore methods we’ve bothered creating. Or am I missing something?

unfortunately, JS doesn’t enforce this. The underscore is just a convention. We can still manipulate the property directly (bypassing the getters and setters). I ran into a similar problem in python today, where private variable aren’t truly private, they are just “hidden”.

Although getters and setters are useful for a number of reasons:

  • You can check if new data is valid before setting a property.
  • You can perform an action on the data while you are getting or setting a property.
  • You can control which properties can be set and retrieved.

but in this course, the getters and setters add little value.

1 Like