A common object paradigm is to include getter and setter method as attributes. Getter and Setter methods get and set the properties of an object.
Advantages:
- You can check if new data is valid before setting a property
- You can perform an action on the data which you are getting or setting on a property.
- You can control which properties can be stored and retrieved.
An Example showing how Setter is used is shown below:
let person = {
_name: 'Johnson Ogwuru',
_age: 137,
set age(newage){
if(typeof newage === 'number'){
this._age = newage;
console.log('valid input')
}
else{
console.log ('Invalid input');
}
}
};
We prepended the property names with underscores _
. Developers use an underscore to indicate a property or value should not be modified directly by other codes. The setter here makes sure only valid values are added to a particular property, validity here is for the value to be a number, but what happen when we try to add a string to this property? Lets see what adding this line below our code would do;
person.age = 'Thirty-nine';//returns invalid input
console.log(person._age);
From the above we see that on running the Application, we got logged in the console 'invalid value' and we also noticed the value of the age
property wasn't changed. But how about we try modifying the age
parameter now with the right value. lets see what happens, change the string in the previous code to any number of your choice;
person.age = 'Thirty-nine';//returns invalid input
console.log(person._age);
From the above image, our value was accepted as valid and also the value of the age property was modified successfully. That's it for Setters
.
Getters are used to get the property value inside of an object. Adding a getter method to our previous example, we would have something like;
let person = {
_name: 'Johnson Ogwuru',
_age: 137,
set age(newage){
if(typeof newage === 'number'){
this._age = newage;
console.log('valid input')
}
else{
return 'Invalid input';
}
},
get age(){
console.log(`${this._name} is ${this._age} old`);
return this._age
}
};
person.age = 'Thirty-nine';
person.age = 39;
console.log(person.age);
Running the above code we have;
In Summary:
Getter
and Setter
methods allow you to process data before accessing or setting property values.
Let's see how we can use setter
and getter
methods in Es6 classes..... in my next post. LOL
Top comments (5)
/also to hide/encapsulate your details and to input details in either function invocation or using get/set/
function details (){
var name;
var age;
for (var i=0; i<arguments.length; i++){
var arc = arguments[i];
if(typeof arg[0] !== "string") throw " invalid first argument ";
if(typeof arg[1]!==" number") throw "invalid second argument";
};
return {get: function () {return this.name+ " is " +this.age;},
set: function (name, age){
this.name = name;
this.age = age;
}
}
}
var personal_details = details ();
personal_details.set(" Dreplica "," gg");
console.log(details())
Hi Ogwuru, thank you for writing about getters and setters. Long ago when I was studying my Java tutor told me that they were an important building block for encapsulation in object oriented languages. But now I think that getters and setters are an anti-pattern.
If being used for type checks (as in your example) there are better ways to do that, even in languages that are not strictly typed (e.g. React PropTypes).
If being used for additional functionality I dismiss their use even more, because this kind of functionality is hidden functionality. Nobody wants to read all your getters and setters to build the puzzle of what your class is doing.
And last, but not least - setters are changing the state of an object, which leads to several other problems. Functional programming teaches us better practices like immutability, meaning that it is better to throw away an object (old state) and create a new one with the new state.
Hey I reevaluated my last comment code, it runs well now
Aiit
great article!
how about disadvantages ?
Both setters and getters are a code smell
Code Smell 28 - Setters
Maxi Contieri ・ Nov 19 '20 ・ 2 min read