Why make fields private and use get/set methods?

Sureshot324

Diamond Member
Feb 4, 2003
3,370
0
71
A lot of programmers seem to be of the opinion that it is good programming style to NEVER make fields of an object public. They should always be private and there should be get/set methods for them if access outside the object is required.

Why is this? I understand if security is a concern and you want to prevent outside write access or something, but for 99% of variables were it really doesn't matter, why not keep it simple and just make them public?
 

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
They do so because fields lose the benefits of Polymorphism, which is half the advantage of OOP.

Properties can be overriden in descendant classes. Variables can not.
Properties can be used in interfaces. Fields can not.
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
It also provides special protection, using a specific set/get function allow you to put boundries on what the field can be get/set to. It also allows you to have special messages that come out of the get/set.

There are a lot of good reasons to make variables private, especially in big projects. It keeps people from incorrectly interfacing with the object and doing things that just aren't supported.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
A slight twist on what others have said: Future revisions of an object might not have the same internal variables, but its a hassle to go and change all the uses of the object when they use those variables directly. Even worse, the variables may take on new properties (e.g., can go negative in a future revision, but not in an earlier one), potentially breaking deep-seated assumptions. The same uses of the object, e.g., myObject->setX( new_x );, can still exist so long as its possible to 'fake out' the existence of an 'X' variable.
 

Sureshot324

Diamond Member
Feb 4, 2003
3,370
0
71
It also provides special protection, using a specific set/get function allow you to put boundries on what the field can be get/set to. It also allows you to have special messages that come out of the get/set.

There are a lot of good reasons to make variables private, especially in big projects. It keeps people from incorrectly interfacing with the object and doing things that just aren't supported.

Makes sense but IMO 99% of the time you don't need or want any such restrictions, except maybe making a field read only. I understand why you'd want to use get/set where it makes sense, but why is it considered bad style to ever make public fields? I was reading Google's C++ style guide and that's basically what they said.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
Makes sense but IMO 99% of the time you don't need or want any such restrictions, except maybe making a field read only. I understand why you'd want to use get/set where it makes sense, but why is it considered bad style to ever make public fields? I was reading Google's C++ style guide and that's basically what they said.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

How is
int getVal() { return val; }
and
void setVal(int newVal) { val = newVal; }

restrictive? You can use the val just like regular, the added bonus comes in the fact that when updating specific circumstances you have to look at one spot in code rather then every spot where val is gotten/set.

I'm not saying I ALWAYS follow this rule, there are cases where it is just plain dumb (You want the object to behave more like a smart struct and less like an object). However, If you are making an object that behaves like an object, it is smart that the object manages itself, not some other code outside of the object.

Good objects generally stray away from having getters/setters. You don't want your object to be a smart struct (unless you really do want that :)) You want your object to maintain itself, to do things when it is given a command.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Cogman is right. There is no rule for all situations.

In general, accessors and mutators will allow more forward-compatibility and better encapsulation than direct access, at the cost of a few more characters and a couple of parenthesis here and there.

A style guide (e.g., Google's) might mandate that there are never public data members... that's someone's opinion of what 'good' code is. The style guide exists to make a large code base homogeneous for the purposes of future maintenance by coders who didn't write the original. Its one small example of practices to follow such that all future coders will be able to quickly identify what is going on in a complicated piece of code. An equally valid rule, from the perspective of homogeneity, is to require that all data members be public, for external inspection at test-time (or to have friend clauses for test classes). One could even require that non-test applications of the object use accessors and mutators, despite data members being public... this all boils down to opinion, either of one person or a consensus opinion of a committee.

Lastly, style guides have to be written for the weakest coder (remember that thread? :)), and adhered to by all coders, including the strong ones, or it doesn't mean anything. Gurus might be able to get away without object encapsulation (though I don't recommend it except for a 'smart struct' scenario ala Cogman's post), but not all coders will understand WTF is going on.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
A style guide (e.g., Google's) might mandate that there are never public data members... that's someone's opinion of what 'good' code is. The style guide exists to make a large code base homogeneous for the purposes of future maintenance by coders who didn't write the original. Its one small example of practices to follow such that all future coders will be able to quickly identify what is going on in a complicated piece of code. An equally valid rule, from the perspective of homogeneity, is to require that all data members be public, for external inspection at test-time (or to have friend clauses for test classes). One could even require that non-test applications of the object use accessors and mutators, despite data members being public... this all boils down to opinion, either of one person or a consensus opinion of a committee.

I've read this a couple of times, and each time I end up thinking that you are suggesting that encapsulation is a matter of style and personal preference. On the other hand I can't accept that you feel that way based on your past history here :). I must be missing something.

I would not consider it a valid rule if, for testing purposes, I was required to make all data members public. Encapsulation of object state behind a stable interface is a basic building block of good code. I would hesitate to lecture you on this, so again I feel I must be missing something in your point.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
I've read this a couple of times, and each time I end up thinking that you are suggesting that encapsulation is a matter of style and personal preference. On the other hand I can't accept that you feel that way based on your past history here :). I must be missing something.

I would not consider it a valid rule if, for testing purposes, I was required to make all data members public. Encapsulation of object state behind a stable interface is a basic building block of good code. I would hesitate to lecture you on this, so again I feel I must be missing something in your point.

The part missing might be my lack of emphasis on from the perspective of homogeneity. I mean to point out that rules are somewhat arbitrary, but they must be followed in large codebases to promote code uniformity. Sadly, my example about making data members public was a poorly chosen one, as it cause more confusion than it cleared.

Anyway, to reiterate: Style guides are essentially arbitrary. Some also happen to be good ideas, but their purpose is to promote readability through uniformity. 'Occasional' violations are just as bad as frequent ones, from this perspective.

Lastly, encapsulation is a matter of style and personal preference -- just like choice of language. Use C if you don't care about encapsulation. However, encapsulation (and style) are pretty darn handy for bug-avoidance and code cleanliness, but code can still be correct without either of these things. Hard to maintain, yes, but correct.
 
Sep 29, 2004
18,665
67
91
Rules pertinant to this conversation ...

Rule 1:
Write code properly and elegantly and be sure that it works. This is what matters. Make sure your code is easy to understand and is consistent. This means, use getters/setters.

Rule 2:
Only optimize when optimization is needed. Provide direct access to fields only when you realize that a performance gain can be made.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,247
3,835
75
Yeah, I've always found getters and setters cumbersome, but they seem to be the preferred style. Probably my favorite feature of C#, as opposed to other languages, is its getter/setter shorthand.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
The part missing might be my lack of emphasis on from the perspective of homogeneity. I mean to point out that rules are somewhat arbitrary, but they must be followed in large codebases to promote code uniformity. Sadly, my example about making data members public was a poorly chosen one, as it cause more confusion than it cleared.

Anyway, to reiterate: Style guides are essentially arbitrary. Some also happen to be good ideas, but their purpose is to promote readability through uniformity. 'Occasional' violations are just as bad as frequent ones, from this perspective.

Lastly, encapsulation is a matter of style and personal preference -- just like choice of language. Use C if you don't care about encapsulation. However, encapsulation (and style) are pretty darn handy for bug-avoidance and code cleanliness, but code can still be correct without either of these things. Hard to maintain, yes, but correct.

That last paragraph could open up an entirely different discussion, but unfortunately I don't have time to pursue it today as I have some new doors to prime and rehang :). I suspect we don't have a definition of "correct code" that is of any practical utility in modern software.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
That last paragraph could open up an entirely different discussion, but unfortunately I don't have time to pursue it today as I have some new doors to prime and rehang :). I suspect we don't have a definition of "correct code" that is of any practical utility in modern software.

Maybe we can short-circuit the whole debate by pointing out that compiled code is in binary form -- its source is gone, its encapsulation is gone, and its been boiled down into a set of good ol' von Neumann primitives (or their CISC equivalents). So... if, when run, that compiled binary fulfills the spec, I would be tempted to call that 'correct'. Now, lets debate the spec... :)
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
Maybe we can short-circuit the whole debate by pointing out that compiled code is in binary form -- its source is gone, its encapsulation is gone, and its been boiled down into a set of good ol' von Neumann primitives (or their CISC equivalents). So... if, when run, that compiled binary fulfills the spec, I would be tempted to call that 'correct'. Now, lets debate the spec... :)

Maybe that was a short-circuit, but it sounded a lot like cleats contacting pigskin :).

Sure, if you have a spec, and can prove that the compiled code fulfills that spec, then you can assert that the code is correct.

And if that is the definition of correct I refer back to my statement that the definition is of little use in modern systems. But in any case you're right about one aspect of it, which is that all of the syntactic mechanisms we use to organize textual source and make it comprehensible and maintainable are discarded by the compilation process. On the other hand, if we don't have the tools to assert that compiled code is "correct" then I am left with at least a strong sense that any modern definition of "correct" has to include good source code structure and organization.
 

Apathetic

Platinum Member
Dec 23, 2002
2,587
6
81
Makes sense but IMO 99% of the time you don't need or want any such restrictions, except maybe making a field read only. I understand why you'd want to use get/set where it makes sense, but why is it considered bad style to ever make public fields? I was reading Google's C++ style guide and that's basically what they said.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

What Cogman was refering to was all the special business rules you can run into such as a value can't be negative or an inventory number is two characters (upper case) followed by six digits, etc.

The setter provides an ideal place to put all of this validation logic without cluttering up the parent code. You can quickly review the rules for a given field and add, alter, or remove them with minimal effort all while preserving the programs correctness. While you can do these things without a setter, are you SURE you added the change to EVERY place a variable can be altered?

Dave
 
Sep 29, 2004
18,665
67
91
I should add that modern IDEs often support auto complete. With eclipse, there is nothing better than typing xyz.get<ctrl-space> to get a list of available getters. Same for setters.

The only way getters/setters are functional in this regards is if their use is consistent.
 

vshah

Lifer
Sep 20, 2003
19,003
24
81
A slight twist on what others have said: Future revisions of an object might not have the same internal variables, but its a hassle to go and change all the uses of the object when they use those variables directly. Even worse, the variables may take on new properties (e.g., can go negative in a future revision, but not in an earlier one), potentially breaking deep-seated assumptions. The same uses of the object, e.g., myObject->setX( new_x );, can still exist so long as its possible to 'fake out' the existence of an 'X' variable.


in the same vein, the get/set methods can be deprecated
 

Sureshot324

Diamond Member
Feb 4, 2003
3,370
0
71
I should add that modern IDEs often support auto complete. With eclipse, there is nothing better than typing xyz.get<ctrl-space> to get a list of available getters. Same for setters.

The only way getters/setters are functional in this regards is if their use is consistent.

Auto complete works for public fields as well.
 

brandonb

Diamond Member
Oct 17, 2006
3,731
2
0
The reason I use get/setters is because it makes the class look cleaner to the parent classes. In visual studio you can look in the object browser and see the properties, etc when they are grouped together rather than the class variables. Also, alot of coding standards want variable names like:

intm_VARIABLENAME

And it looks funny to parent classes if it's just a public. I always use the type/scope/use formula to my variable names. Properties on the other hand you can make it say whatever.
 

Fox5

Diamond Member
Jan 31, 2005
5,957
7
81
A lot of programmers seem to be of the opinion that it is good programming style to NEVER make fields of an object public. They should always be private and there should be get/set methods for them if access outside the object is required.

Why is this? I understand if security is a concern and you want to prevent outside write access or something, but for 99% of variables were it really doesn't matter, why not keep it simple and just make them public?

Because if you don't, you end with a Windows style API that drives developers crazy trying to determine what 'hidden functionality' and side effects a function call is having.