DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
nallack profile image
cgray

You should never write public variables for a class in object-oriented programming.

  • You are exposing internal state, thus making it easy for someone put your class into an invalid state, it is now impossible for the class to determine if and when it is being put into an invalid state, and is why poorly designed software breaks.
  • Your class may need to perform extra functionality or provide a view of an implementing instance on a call to an accessor or mutator. You don't want to waste time swapping over instead of writing it the correct way to begin with.
  • You cannot provide an interface to public member variables, thus is not ideal to use when writing a library because the API layer can't provide access to everything needed to use your class anymore.
  • Engineers have spent thousands of hours incorporating accessors and mutators into languages to encourage their use for these reasons.

(However, in "some cases" a struct can be more suitable than a class (as seen in math libraries) where member variables should instead always be public. The only limitation you have for writing a struct is that all variables are also invariant. Some languages also don't have structs (e.g. Java), in which case you need to use a class to create a struct-like object that has no responsibility for preventing invalid state e.g. java.awt.Point has public x and y members. An awt ui object however will never return its internal state, accessors will always return a clone of an internal Point instance.)