Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • 6
    A way too narrow view of the subject matter. There are cases where public field access is warranted, even preferred Commented Apr 11, 2012 at 19:59
  • One certainly can design objects whose state cannot be changed (immutable objects), but this is not a general rule applied to all classes. In my experience, most objects make it very easy for others to change the state of the object. Commented Jul 12, 2014 at 23:41
  • 1
    @DavidK Maybe what bbb meant to say is that "private variables prevent others from going in and indiscriminately changing the state of the object." Public methods may change the private state of the object, but only in ways that are necessary and consistent for the functioning of the object. Commented Jul 17, 2014 at 20:57
  • @Max Nanasy: Yes, one can control how the state is changed when one offers only methods in the public interface. For example, there might be a relationship among the members that must be satisfied in order for the object to be "self-consistent", and you could allow a self-consistent state to be changed only to another self-consistent state. If all those variables are public then you cannot enforce this. But there can also be objects where you do not want to allow any change, so it is important to make clear which of these things we're talking about. Commented Jul 17, 2014 at 21:30