Public property VS Private property with getter?

Pouya picture Pouya · Nov 3, 2011 · Viewed 12.1k times · Source

This question has puzzled me for a while. A public property that can be accessed directly or a private property with getter? Which one is better/correct and why?

Answer

Mark Byers picture Mark Byers · Nov 3, 2011

Exposing fields directly is considered a bad practice.

It is better to keep the field private and only expose the getter and setter. One advantage is that you can choose different access levels for the getter and setter, whereas a field has only a single access level. Another advantage of using getters is that it allows you to change the implementation without changing the class interface.

Even better is to avoid getters and setters where possible. Instead use methods that encapsulate a higher-level behaviour. This is because objects shouldn't be tampering with other objects' internal state (either via directly accessing fields, or indirectly via getters and setters).

Related