Benefits of Setters and Getters in OOP in JavaScript
In the previous lesson we made a getter and setter for each property. You might wonder why we need such complexity, because in fact the same effect can be achieved by making the properties public instead of private.
The thing is that getters and setters have an advantage: before accessing the property, you can perform some checks. For example, in our case, when writing the first and last name, we can check that the new value is not an empty string:
class User {
#name;
#surn;
setName(name) {
if (name.length > 0) {
this.#name = name;
} else {
throw new Error('name is incorrect');
}
}
setSurn(surn) {
if (surn.length > 0) {
this.#surn = surn;
} else {
throw new Error('surn is incorrect');
}
}
getName() {
return this.#name;
}
getSurn() {
return this.#surn;
}
}
Let's check how it works. First, let's create an object of the class:
let user = new User;
Now let's try to write the correct value:
user.setName('john');
Now let's try to write something incorrect:
user.setName(''); // error
In the Employee class, in the age setter, check that the age must be between 0 and 120.
In the Employee class, in the salary getter, make it so that when reading the salary, a dollar sign is added to the end of its value.