Try Doing That with a Field
by Jake Vinson
in CodeSOD
on 2009-03-18
Years ago I was talking to a friend who was just starting to learn about coding. He'd looked at some of my code, and asked why I used class properties with getters and setters instead of public fields. "Isn't it just more code for no real benefit?" he asked. And he was right; in every case, I had a getter and setter simply acting as a public interface to a private field.
I thought about his question for a second, not really knowing the answer. Frankly, it was just The Way I Learned To Do It. And to my dismay, he didn't just go away while I struggled to think of an answer. I eventually waved my hands dramatically and yelled "encapsulation!" Yes, that'll do nicely, I thought. Later that day I was thinking about it some more, and realized that in most cases, he was right. Still, getters and setters are great for inherited classes in which a method of calculation may be different. Accessors certainly have their place, but that place isn't necessarily everywhere.