DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
aminmansuri profile image
hidden_dude

They are not part of encapsulation. They are the opposite.

An encapsulated class in "pure OO" does not expose its properties. But many people confuse this because their only exposure to "OO" has been through Java and C# (and their successors) and have had little exposure to a real OO system like Smalltalk.

Collapse
 
kallaste profile image
Tatiana McGarry • Edited

Yes, they are a totally legitimate part of encapsulation in the current paradigm of Object Oriented Programming, and will be mentioned as such in current literature about it. That isn't confusion, it is the maturation of programming language concepts. A lot has changed since 40 years ago when Smalltalk was invented. We had no idea what OOP was going to be back then, or in many ways how it was going to be used.

The argument that getters and setters aren't a valid part of encapsulation because Smalltalk did it differently is a little like debating what the World Wide Web is on the basis of how things were done in ARPANET. Quite simply, just not very relevant.

Thread Thread
 
aminmansuri profile image
hidden_dude • Edited

No. Its a misunderstanding about what encapsulation is.

If you have a computation like:

bankAcct.setBalance(bankAcct.getBalance() * bankAcct.getInterestRate())

Then you aren't understanding how OO is supposed to work. The correct encapsulation would be by having behavior based method:

bankAcct.accrueInterest()

Getters and Setters don't come from OO they come from "construction by parts" a style of programming made for automated UIs like in VB. It has its place, its related to OO, but it isn't encapsulation. It's the opposite. Its exposing your attributes to the outside world.

And plenty of OO was written by great programmers like Kent Beck and others that later helped influence how we did it in other languages. But the popularization of many techniques has little to do with good OO, and simply popularization of stuff that certain developers promoted.