Getters And Setters used in JavaScript Objects....How?

Johnson Ogwuru on May 13, 2018

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. ... [Read Full]
markdown guide
 

/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.

 
code of conduct - report abuse