dagblog.
← Archive

Getters and setters are a bad habit in OOP


Allen Holub takes on another myth. After giving inheritance a drubbing in Why extends is evil
(Dagblog — Inheritance vs. Implementation),
he turns to accessors. Accessors, also known as get and set methods or getters and setters, are used
to encapsulate an object’s non-public fields.

Encapsulation is a fundamental rule of OOP.
An object exposes only a public interface through which the outside world can interact with it. Everything outside that public
interface is the object’s internal representation. It’s hidden from the outside world so that it can
change if needed.

class Bar{
public int foo = 10;
}
The field can be encapsulated using set and get methods like this.


class Bar{
private int foo = 10;
public void setFoo(int foo){
this.foo = foo;
}
public int getFoo(){
return this.foo;
}
}
You’ll see this or similar code in 90 percent of the material on
OOP. The article explains why
these accessors aren’t all they’re cracked up to be.
Why getter and setter methods are evil.
It’s technically excellent, and I highly recommend studying it.

Medium version

Related articles

Related CZ Podcast episodes