views:

606

answers:

14

I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).

Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.

In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?

A: 

Some Java frameworks require them (JavaBeans I think).

-- Edit

Some posters are trying to say this is about encapsulation. It isn't.

Encapsulation is about hiding the implementation details of your object, and exposing only relevant functions.

Providing a get/set that does nothing but set a value does not accomplish this at all, and the only reason for them is:

  • Perform some additional validation before set/get
  • Get the variable from somewhere else
  • Integrate with frameworks (EJB)
Noon Silk
It's about **later** encapsulation, while still preserving the interface.
Ionuț G. Stan
actually, if you re-read the question, it is about encapsulation:"I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).Why not then make the variable public itself?"The answer is: encapsulation.
metao
Okay, I am not interested in continuing this argument. I have made my point in comments on this topic, and I think they are sufficient. I do suggest those that think this is encapsulation actually do a bit of research. Because you are wrong.
Noon Silk
+1  A: 

Well,

OOP. ;)

Or to be a little more precise:

Getters and Setters are used to provide a defined interface to a classes properties. Check the OOP link, it describes the concepts more in detail...

K

KB22
+2  A: 

Encapsulation

You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.

Taylor Leese
No, encapsulation is not the reason. Encapsulation is about *not setting properties at all*, but calling generalised functions against the class, that manipulate properties as they wish. The get/set that does nothing but get/set is NOT incapsulation.
Noon Silk
Sure it is encapsulation. The point is that you can change it later to do something else.
starblue
I'd consider having validation logic in the setters to be encapsulation. Having an "empty" setter than does no validation still provides for easily adding this later if needed.
Taylor Leese
starblue: no, you're wrong. That is not encapsulation. Taylor: You are also wrong. That is not encapsulation, that is about hiding how the variable is set. Encapsulation is never worrying about variables of other classes.
Noon Silk
silky, in my opinion the formulation "hiding how the variable is set" denotes encapsulation. OK, is not a very complicated encapsulation, especially with empty getters/setters, but still, you hide something so that future changes of the implementation don't affect the interface.
Ionuț G. Stan
It _is_ encapsulation, what it is not is _abstraction_.
soru
+5  A: 

Even back in 2003 it was known that getter and setter methods are evil.

A: 

You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".

PepperBob
+2  A: 

This is done so you can change the getter or setter implementation in your public API after you release it. Using public fields, you wouldn't be able to check values for validity.

Jorn
+7  A: 

In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.

In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.

So, it's all about encapsulating some logic while still preserving interface for... future proofing.

Ionuț G. Stan
I'd like some reason for down votes. I may be wrong and it's ok, but I'd like to learn something from this whole SO thing. I'm not hear to help others for nothing, ok?
Ionuț G. Stan
I downvoted you, for saying it's about encapsulation, don't take offense :) The main reason is for integration, not for encapsulation, because it is not encapsulation to do this. The public API is affected the same, if the underlying type changes. If you write your class in a truly 'encapsulated' way, the caller will be shielded from such changes.
Noon Silk
No problem silky, I don't take offense, I'm only interested in the reason, for which I thank you. It helps me improve myself.
Ionuț G. Stan
+2  A: 

It's part of encapsulation: abstracting a class's interface (the "getters" and "setters") from its implementation (using an instance variable). While you might decide to implement the behaviour through direct access to an instance variable today, you might want to do it differently tomorrow. Say you need to retrieve the value over the network instead of storing it locally—if you have encapsulated the behaviour, that's a trivial change. If other objects are relying on direct access to an instance variable, though, you're stuck.

Paul A. Hoadley
A: 

There are several reasons:

  • Some Java APIs rely on them (e.g. Servlet API);
  • making non-final variable public is considered to be a bad style;
  • further code support: if sometime in future you`ll need to perform some actions before each access/mutation (get/set) of the variable, you will have less problems with it. In C# constructions like

    public int Age { get { return (int)(today() - m_BirthDate); } }

are are just syntactic sugar.

folone
+2  A: 

The most and foremost use for getters and setters in Java is to annoy the developers. The second most important use is to clutter the code with useless noise. Additionally, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Not to forget the added ambiguity (do you call the getter inside the class or do you use the field directly?) Next, they are used to allow access to private data but that's just a minor side effect ;)

In other programming languages, the compiler will generate them for you (unless, of course, you provide your own implementations). In Delphi, for example, you have read and write modifiers for fields (just like private, static or final in Java). The define if you'll have a getter or setter generated for you.

Unlike the Delphi guys, the Java guys wanted everything to be explicit. "If it's not in the source, it's not there". So the only solution was to force people to write all the getters and setters manually. Even worse, people have to use a different name for the same thing.

Aaron Digulla
The Zen of Python states: "Explicit is better than implicit". But this only makes sense in a dynamically types language like Python.
I really like the sarcasm in this answer, +1.
Ionuț G. Stan
@lutz: That only applies to rarely used things. For something like getters and setters, that you encounter every day, you can have more complex, implicit.
Aaron Digulla
+2  A: 

Getters and setters may very well be the greatest lie ever told. They are considered a sign of good design, while the opposite is true. New programmers should be taught proper encapsulation, not to write dumb data carrier classes that contain nothing but getters and setters.

(The idea that you need getters and setters to future-proof your code if you want to change the implementation later on is an obvious case of YAGNI. But that is really beside the point.)

waxwing
Getters and setters are still part of a good design using proper encapsulation - just not dumb getters and setters for everything.
Michael Borgwardt
The real problem is that getters do *not* future-proof your code. They make it harder to change the type of a property without breaking client classes. Getters are much worse than setters in this respect.
finnw
+2  A: 

The most common reason is a poor understanding of encapsulation. When the developer believes that encapsulating stuff really just means getters & setters rather than encapsulating behavour.

The valid reasons for having getters/setters are:

1) You are making a generic¹ object such as JComponent. By using a getter/setter rather than direct access to the variable means that you can do some pre-processing on said variable first (such as validate it is with a set range) or change the underlying implementation (switching from an int to a BigInteger without changing the public API).

2) Your DI framework does not support ctor injection. By having just a setter you can ensure that the variable is only set once.

3) (Ties in with #1) To allow tools to interact with your object. By using such a simple convention then GUI tools can easily get all the settings for a given component. An example of this would be the UI builder in NetBeans.

¹ Of the not-Generic type. Bad word to use I know, please suggest an alternative.

mlk
+3  A: 

Because interfaces only allow for specifying methods, not variables. Interfaces are the building stones of API's.

Hence, to access a field through an interface, you need to have the getter and setter.

Thorbjørn Ravn Andersen
+1  A: 

Having a setter allows you

  • perform validation
  • to fire a property changed event if the new value is different from the previous value

In the case in question there is no need for getter and setter if the value is simply read or written.

paul
+1 for firing property changed events.
uckelman