What are the possibilities for using getter / setters in Java?

I've seen member variables set by 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 make this post the variable itself (except in cases like spring framework which depends on getter / setters for IOC, etc.). It serves a purpose.

In C #, I've seen a getter / setter with member variable capitalization. Why not make the publication of the variable itself?

+2


source to share


15 replies


To get a stable API from the first snapshot. The Java gurus believed that if you later want to have some extra logic when setting up / getting an instance member, you don't want to break the existing API by replacing the 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 due to compatibility with the binary interface . Someone asked a similar question right here on SO.



So it's all about encapsulating some logic while keeping the interface for ... future validation.

+8


source


Back in 2003, the getter and setter methods were known to be evil .



+4


source


Because interfaces only allow specifying methods, not variables. Interfaces are the building blocks of APIs.

Hence, to access a field through an interface, you must have a receiver and a setter.

+4


source


Encapsulation

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

+2


source


This is so that you can change the getter or setter implementation in your public API after it's released. By using public fields, you will not be able to check the values ​​for validity.

+2


source


This is part of encapsulation : abstraction of the class interface ("getters" and "setters") from its implementation (using an instance variable). While you may decide to implement the behavior through direct access to an instance variable today, you may want to do it differently tomorrow. Let's say you need to retrieve a value over the network instead of storing it locally - if you've encapsulated the behavior, that's a trivial change. If other objects rely on direct access to an instance variable, you're stuck.

+2


source


The most important use for getters and setters in Java is to annoy developers. The second most important thing is to clutter your code with useless noise. Plus, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Don't forget about the added ambiguity (are you calling the getter inside the class, or are you using that field directly?) They are then used to allow access to sensitive 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). For example, in Delphi you have modifiers read

and write

for the fields (in the same way as private

, static

or final

in Java). Determine if you will have a receiver or setter generated for you.

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

+2


source


Getters and setters may very well be the greatest lies ever told. They are considered a sign of good design, and vice versa. New programmers should teach proper encapsulation rather than writing dumb data carrier classes that contain nothing but getters and setters.

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

+2


source


The most common reason is poor understanding of encapsulation. When the developer thinks that encapsulating material really only means getters and setters, not encapsulating behavior.

Valid reasons for having getters / setters are:

1) You are making a generic¹ object like JComponent. Using getter / setter instead of directly accessing the variable means that you can preprocess the specified variable first (for example, check it with a given range) or change the base implementation (go from int to BigInteger without changing the public API).

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

3) (C # Binding 1) So that tools can interact with your object. Using such a simple convention, GUI tools can easily retrieve all the settings for a given component. An example of this is the UI Creator in NetBeans.

¹ Of non-generic type. Bad word to use. I know please suggest an alternative.

+2


source


Having a setter allows you

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

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

+2


source


Well,

OOP .;)

Or a little more accurate:

Getters and Setters are used to provide a specific interface to property classes. Check out the OOP link, it goes into more detail on the concepts ...

TO

+1


source


Some Java frameworks require them (JavaBeans I think).

- Change

Some posters try to talk about encapsulation. This is not true.

Encapsulation is all about hiding the implementation details of your object and showing only the relevant functions.

A get / set grant that does nothing other than the given value does not do it at all, and the only reason for them is:

  • Do some extra checking before installing / get
  • Get a variable from elsewhere
  • Integration with frameworks (EJB)
0


source


You need to encapsulate these attributes if there are, for example, limitations or do general validation or post change events or whatever. The main use is to hide an attribute from the "outside world".

0


source


There are several reasons:

  • Some Java APIs rely on them (for example, the Servlet API);
  • creating a non-final public variable is considered bad style;
  • additional code support: if in the future you need to perform some actions before each access / mutation (get / set) of a variable, you will have less problems with it. In C # constructs like

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

is just syntactic sugar.

0


source


property idea is fundamental in OOP (object-oriented programming). But the problem is that Java does not represent them in the core of the language (syntax / JVM), but (perhaps years later, as the Java historians say) as a shorthand: a pair of matched getters / setter property in a bean property concept is in libraries rather than in the core.

This poses a problem in several libraries. Is the only recipient read-only or not? That's the question. Ya in essence JPA, if you want to implement the classic method (algorithm) starting with "get" like getCurrentTine()

, is the best @Transient label to disable the interpretation as a property having a value.

In other words, I really like the concept of ownership in C #, developed 10 years later and better. The BTW C # property also has a getter / setter, but sometimes / partially hidden, visible when low level debugging. Free from the question "why getter" etc.

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

EDIT: From real life every java object has a method getClass()

, tools from the package java.beans.BeanInfo

report this as a property "class"

, but it doesn't. This is not a property (readonly property) in the full sense. I am assuming that properties like C # (with its internal hidden name get_Something1) do not conflict with the "functional" GetSomething2 ()

0


source







All Articles