What is the point of getters and setters?

JavaSetterGetter

Java Problem Overview


> Possible Duplicate:
> Why use getters and setters?

I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:

public int getX(){
    return x;
}

public void setX(int x){
    this.x = x;
}

But what is the difference from that and

...(shape.x)...   // Basically getX()

and

shape.x = 90;    // Basically setX()

If setters and getters are better, what practical problems would arise?

Java Solutions


Solution 1 - Java

Multiple reasons:

  • If you allow field access like

    shape.x = 90

then you cannot add any logic in future to validate the data.

say if x cannot be less than 100 you cannot do it, however if you had setters like

public void setShapeValue(int shapeValue){
  if(shapeValue < 100){
    //do something here like throw exception.
  }
}
  • You cannot add something like copy on write logic (see CopyOnWriteArrayList)
  • Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.

Though for constants like

public final String SOMETHING = "SOMETHING";

you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.

  • Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.

Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).

We can use the private variables in any package using getters and setters.

Solution 2 - Java

Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.

It is good practice to make member variables private so they cannot be modified directly by programs using them.

[Mutator functions][1]
[Encapsulation][2]

[1]: http://en.wikipedia.org/wiki/Mutator_method "Mutator functions" [2]: http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29 "Encapsulation"

Solution 3 - Java

A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a huge benefit.

One specific example: complex numbers in mathematics. Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.

A complex number can be written on the form a + bi with real and imaginary parts, lending itself well to [gs]etRealPart and [gs]etImaginaryPart.

However, in some cases it's easier to reason about complex numbers on polar form re^(iθ), giving [gs]etRadius (r) and [gs]etAngle (θ).

You can also expose methods like [gs]etComplexNumber(realPart, imaginaryPart) and [gs]etComplexNumber(radius, angle). Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.

The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and expose that using fields rather than getters and setters, not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(iθ) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.

Solution 4 - Java

One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client.

By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.

Solution 5 - Java

Another good reason to user getter and setter can be understand by the following example

public class TestGetterSetter{
	private String name ;


	public void setName(String name){
		this.name = name ;
	}


	public String getName(){
		return this.name ;
	}
}

The point of getters and setters is that only they are meant to be used to access the private variable, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.

Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.

public class TestGetterSetter{
	private String name ;


	public void setName(String name){
		this.name = name ;
	}


	public String getName(){
		if (this.name == null ){
			setName("Guest");
		}
		return this.name ;
	}
}

There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)

Solution 6 - Java

Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of "X" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.

If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.

One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, "x" might be a variable, or it might be a value that is calculated on the fly.

This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.

Solution 7 - Java

Originally, getter/setter pattern was created to promote good object-oriented design by encapsulating the internals of a class from its external interface.

  • Hiding the internal representation of the property

this is the best answer of your question Why use getters and setters?

Solution 8 - Java

There are lots of reasons. Here are just a few.

  1. Accessors, getters in particular, often appear in interfaces. You can't stipulate a member variable in an interface.
  2. Once you expose this member variable, you can't change your mind about how it's implemented. For example, if you see a need later to switch to a pattern like aggregation, where you want the "x" property to actually come from some nested object, you end up having to copy that value and try to keep it in sync. Not good.
  3. Most of the time you are much better off not exposing the setter. You can't do that with public fields like x.

Solution 9 - Java

Before get into the answer, we gotta know something prior...! "JavaBeans".
JavaBeans are java classes that have properties. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed from outside of their class is through 'methods'in the class.
The methods that change a propertiy's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

Solution 10 - Java

I would say that neither the getters/setters nor the public members are good Object Oriented design. They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.

Solution 11 - Java

This is done by applying the encapsulation principle of OOP.

> A language mechanism for restricting access to some of the object's components.

This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:

  • Private: Only the class can see and use the attributes/methods.
  • Protected: Only the class and its children can see and use the attributes/methods.
  • Public: Every class can see and use the attributes/methods.

When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the [ArrayList][2] class: it has a size property to know the actual size of the inner array. Only the class must change its value, so the code is something like

public class ArrayList<E> {
    private int size;
    private Object[] array;
    public getSize() {
        return this.size;
    }
    public void add(E element) {
        //logic to add the element in the array...
        this.size++;
    }
}

In this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):

public void someMethod() {
    List<String> ls = new ArrayList<String>();
    //adding values
    ls.add("Hello");
    ls.add("World");
    for(int i = 0; i < ls.size(); i++) {
        System.out.println(ls.get(i));
    }
}

Solution 12 - Java

Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.

Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,

Solution 13 - Java

Because we are using Object oriented programming language. Here we are using Data hiding and encapsulation. The variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so

shape.x

is not correct. Getter and setter method are used to get and set the value of x which is the way to achive encapsulation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnonymous181View Question on Stackoverflow
Solution 1 - JavamprabhatView Answer on Stackoverflow
Solution 2 - JavaJustinDanielsonView Answer on Stackoverflow
Solution 3 - JavauserView Answer on Stackoverflow
Solution 4 - Javansfyn55View Answer on Stackoverflow
Solution 5 - JavaBhavik AmbaniView Answer on Stackoverflow
Solution 6 - JavacoydogView Answer on Stackoverflow
Solution 7 - JavaSumit SinghView Answer on Stackoverflow
Solution 8 - JavaJudge MentalView Answer on Stackoverflow
Solution 9 - JavaSachin MhetreView Answer on Stackoverflow
Solution 10 - JavaAndrew LandsverkView Answer on Stackoverflow
Solution 11 - JavaLuiggi MendozaView Answer on Stackoverflow
Solution 12 - JavaJasper SprengersView Answer on Stackoverflow
Solution 13 - JavaxrcwrnView Answer on Stackoverflow