DEV Community

Discussion on: Getters And Setters used in JavaScript Objects....How?

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

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.