Why Use Getters and Setters/Accessors

Why use getters and setters/accessors?

There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.

Here are the some of the reasons I am aware of:

  • Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
  • Hiding the internal representation of the property while exposing a property using an alternative representation.
  • Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
  • Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
  • Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
  • Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
  • Allowing the getter/setter to be passed around as lambda expressions rather than values.
  • Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.

Why do we actually use getters and setters?

Getters and Setters are abstraction wrappers around your object implementations. You may have a property of an object that is actually (as an example) computed based on the value of other field members, but not stored or persisted within the class, thus a getter creates the illusion that the property itself is native to the class, while its implementation is substantially different. Also, getters without setters allow you to create read-only properties and protect internal members of the class from inadvertent and possibly destructive modification.

It's all about separating the external representation consumed by other applications from the internal implementation plumbing. Those are the basics.

What is the point of getters and setters?

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.

Should I always use getter/setter methods in Java classes or are there times when its okay to use public attributes?

Encapsulation is one of the core concepts of object oriented programming. Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will.

Typical example, consider having a dateOfBirth parameter. With a setter and getter you can have a small validation process, making sure that the user was not born in the future, or is impossibly old. You can also use the setter to update some other fields, such as age.

This minor validation can also enhance code re-usability since you do not need to have to make this check in any other class which invokes these getters and setters.

Why are getter and setter method important in java?

The basic "private field with public getter and setter that do nothing but return or set the field" pattern is indeed completely pointless when it comes to encapsulation, except that it gives you a chance to change it later without changing the API.

So don't use that pattern unthinkingly. Carefully consider what operations you actually need.

The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.

  • You can have only a getter. Then the property is read only. This should actually be the most common case.
  • You can have only a setter, making the property configurable, but communicating that nothing else should depend on its value
  • A getter can compute a value from several fields rather than return one field.
  • A getter can make a defensive copy
  • A getter can perform an expensive fetch operation lazily and use a field to cache the value
  • A setter can do sanity checks and throw IllegalArgumentException
  • A setter can notify listeners of changes to the value
  • You can have a setter that sets multiple fields together because they belong together conceptually. This doesn't adhere to the JavaBeans specification, so don't do it if you depend on frameworks or tools that expect JavaBeans. Otherwise, it's a useful option.

All of these things are implementation details that are hidden behind the simple "getter and setter" interface. That's what encapsulation is about.

Why use getters and setters/accessors?

There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.

Here are the some of the reasons I am aware of:

  • Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
  • Hiding the internal representation of the property while exposing a property using an alternative representation.
  • Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
  • Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
  • Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
  • Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
  • Allowing the getter/setter to be passed around as lambda expressions rather than values.
  • Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.

Why is it (or isn't it) good practice to use Getters / Accessors in Python OOP?

Because in Python you have properties:

 class Foo:
def __init__(self, value):
self.__value = value

@property
def value(self):
return self.__value

@value.setter
def set_value(self, that):
if that < 0:
self.__value = 0
else:
self.__value = that

Properties make it appear that you are dealing with an attribute but in fact, you're dealing with setters and getters. This allow for better useage of one of Python's defining traits: Duck Typing.

Hence, I can do the following:

 class Bar:
def __init__(self, value, other):
self.value = value
self.other = other

def __str__(self):
return ''.join(['Oh joy', str(self.value), str(self.other), '!'])

And then in the function:

 def stuff(x):
return x.value + 1

I could pass either a type of Bar or a type of Foo and it wouldn't matter. Duck typing would let it "just work."

What is the point of setters and getters in java?

The point of getters and setters, regardless of language, is to hide the underlying variable. This allows you to add verification logic when attempting to set a value - for example, if you had a field for a birth date, you might only want to allow setting that field to some time in the past. This cannot be enforced if the field is publicly accessible and modifyable - you need the getters and setters.

Even if you don't need any verification yet, you might need it in the future. Writing the getters and setters now means the interface is kept consistent, so existing code won't break when you change it.

what is the use of getter and setter method?

The purpose is that you can always change the setter and the getter method with more sophisticated logic, if needed (for example validity check). If you don't use getter/setter you must write them and then change the code everywhere you change the field, which can lead to errors which will be very hard to find.



Related Topics



Leave a reply



Submit