Why do we use getters and setters instead of making fields public, and what is the architectural benefit of this boilerplate?
Last updated
Accessors turn a raw field into a controlled entry point: they let you add validation, lazy computation, or change internal representation later without breaking callers, whereas a public field freezes your implementation into the public API.
Preserve invariants: A setter can reject invalid input (e.g. negative age), so the object can never enter a bad state.
Decouple interface from representation: You can change the backing storage (compute a value, rename, cache) while
getX()stays stable.Enable extra behavior: Logging, change notifications, lazy loading, or read-only fields (getter, no setter) become possible.
Architectural benefit: A public field is a binding contract: once callers touch it directly, you can't intercept access without breaking them. Accessors keep that seam.
Caveat: blind getters/setters on every field are an anti-pattern (an anemic model); expose behavior, not raw state, when you can.
- https://www.igmguru.com/blog/oops-interview-questions
- https://tryrehearsal.ai/technical-questions/explain-oops-concepts
- https://github.com/Devinterview-io/oop-interview-questions
- https://www.hirist.tech/blog/top-30-c-oops-interview-questions-and-answers/
- https://www.interviewbit.com/oops-interview-questions/
- https://blog.stackademic.com/dont-just-code-the-15-essential-practices-senior-developers-want-you-to-learn-now-84246fb2f6ed
- https://www.reddit.com/r/ExperiencedDevs/comments/1mpaewh/how_should_i_deal_with_junior_devs_that_debate/
- https://www.scaler.com/topics/oops-concepts-in-cpp/
- https://javatechonline.com/interview-questions-object-oriented-programming/
- https://henko.net/blog/my-favorite-interview-questions/
- https://utkrusht.ai/blog/python-interview-questions
- https://www.digitalocean.com/community/tutorials/oops-interview-questions-answers
- https://www.scribd.com/document/510810151/Fragile-base-class