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.

23
  • 29
    You fail to mention the main reason sane persons write getters/setters: For validation or other more complex logic on getting/setting, and for future-proofness in case you need to add some of this. Commented Mar 13, 2011 at 9:13
  • 2
    @delnan indeed, but KeesDijk's answer already pointed to that information so I saw no need to repeat it @Thorbjørn MyConfig is just a simple sample of a class of which all members have as requirement they need to be read from and written to within the application, hence needing both getters and setters. Or, if no validation/whatever required, are suitable candidates for making them public and omitting the getters/setters. Commented Mar 13, 2011 at 10:11
  • 2
    @stjin: But if you're condemning X, you should at least mention that there are legimitmate use cases (assmuning there are, of course). Your answer as-is, on its own, is barely better than "you must always write getter/setters", as it implies getters/setter have no reason to exist. Also, the validity of a struct-like class is questionable from a pure OOP perspective. Commented Mar 13, 2011 at 10:20
  • 4
    Don't be so hard on the professors. There are valid educational reasons for enforcing rules that are almost always valid. I'd consider "never make variables public, except if the class/struct is a bundle of related data with no behavior" a good rule. Once the student is experienced enough, he or she will know why the rules are there and when to break them. Commented Feb 8, 2012 at 14:54
  • 5
    @stijn: This question is all about OOP. Asking this question outside the context of OOP is pointless. Your answer comes down to "No, not all fields must have accessors. Look at how this piece of bad code becomes even worse when I add them." Your example is extremely bad to start with in a question tagged "best-practices". Commented Feb 8, 2012 at 16:31