2

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?

unwind
  • 391,730
  • 64
  • 469
  • 606
Ajay
  • 7,378
  • 18
  • 57
  • 75
  • consider if your app is to scale to something more than one user/PC, in situation where you have to ensure synchronization between 800 classes accessing that single property you declared public. Or, simpler, consider some business logic changed and therefore changing of that property is not anymore just changing its value, you need to do few checks for boundaries or something.. – ante.sabo Aug 28 '09 at 09:39

15 Answers15

8

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.

Community
  • 1
  • 1
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 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 Aug 28 '09 at 08:58
  • 1
    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 Aug 28 '09 at 09:02
  • 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 Aug 28 '09 at 09:10
4

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

4

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
  • 73,784
  • 33
  • 194
  • 347
2

Encapsulation

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

Taylor Leese
  • 51,004
  • 28
  • 112
  • 141
  • 3
    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 Aug 28 '09 at 08:52
  • 3
    Sure it is encapsulation. The point is that you can change it later to do something else. – starblue Aug 28 '09 at 08:59
  • 2
    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 Aug 28 '09 at 09:00
  • 1
    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 Aug 28 '09 at 09:03
  • 2
    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 Aug 28 '09 at 09:23
  • It _is_ encapsulation, what it is not is _abstraction_. – soru Aug 31 '09 at 15:07
2

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
  • 20,612
  • 18
  • 79
  • 126
2

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
  • 1,518
  • 1
  • 13
  • 17
2

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
  • 321,842
  • 108
  • 597
  • 820
  • The Zen of Python states: "Explicit is better than implicit". But this only makes sense in a dynamically types language like Python. –  Aug 28 '09 at 09:24
  • 1
    I really like the sarcasm in this answer, +1. – Ionuț G. Stan Aug 28 '09 at 09:24
  • @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 Aug 28 '09 at 11:30
2

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
  • 18,547
  • 8
  • 66
  • 82
  • Getters and setters are still part of a good design using proper encapsulation - just not dumb getters and setters for everything. – Michael Borgwardt Aug 28 '09 at 09:31
  • 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 Sep 11 '09 at 16:21
2

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.

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
2

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
  • 13,312
  • 23
  • 81
  • 144
1

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
  • 6,899
  • 9
  • 43
  • 52
0

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
  • 54,084
  • 6
  • 88
  • 105
  • 3
    It's about **later** encapsulation, while still preserving the interface. – Ionuț G. Stan Aug 28 '09 at 09:01
  • 3
    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 Aug 28 '09 at 09:02
  • 1
    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 Aug 28 '09 at 09:05
0

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
  • 719
  • 3
  • 8
0

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.

George
  • 8,368
  • 12
  • 65
  • 106
0

property idea is core in OOP (Object oriented programming). But problem is that Java introduce them not in core of language (syntax / JVM), but (probably few years later??? historics of Java say better) as convention: pair of consistent getters/setter is property in bean, concept of property is in libraries, not in core.

This generate problem in few libraries, framework. Is single getter a read only property or not? That is the question. I.e.in JPA entities if You want implement classic method (algorithm) beggining with "get" like getCurrentTine() is the best mark by @Transient to disable interpretation like property having value.

In other words, I like very much property concept in C# designed 10 years later and better. BTW C# property has getter/setter too, but sometimes/partially hidden, visible at low level debugging. Free from question "why getter" etc ...

In Java world is interesting to read about Groovy concept of property (hidden getter/setter in different way than C#) http://www.groovy-lang.org/objectorientation.html#_fields_and_properties

EDIT: from real life, every java object has getClass() method, tools from java.beans.BeanInfo package report this as property "class", but this not true. It isn't property (readonly property) in full sense. I imagine properties like C# (with his internal hidden name get_Something1) hasn't conflict with "functional" GetSomething2()

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22