How Do Getters and Setters Work

How do getters and setters work?

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted to the class.

public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}

How do getters and setters work in Python?

The reason to use a getter and setter, is if you want to do something more complex than just set and attribute with foo.bar. In your case, set_age has an

isinstance(new_age, int) & new_age>0 & new_age<120

check, which is not possible to do with a raw attribute. (Side-note: you should use and instead of &.)

Yes, someone can still do p1._age = -1, and then their code won't work, but why would they? It just makes their code not work.

Your get_name function is less useful than the age one. It basically makes name read-only, which might or might not be useful.

When creating setters and getters in Python, it is usual to use the @property decorator. This means the functions can be called as if they were attributes, so instead of p1.get_name() you can just do p1.name. Similarly p1.set_age(3) becomes p1.age = 3.

You probably want to use the age setter in __init__, because then the age of the Person is validated when it is created.

Here is a version that makes these changes (and a couple of other readability improvements).

class Person:
def __init__(self, name, age):
self._name = name
self.age = age

@property
def age(self):
return self._age

@age.setter
def age(self, new_age):
if isinstance(new_age, int) and 0 < new_age < 120:
self._age = new_age

@property
def name(self):
return self._name

def __str__(self):
return f"Person[{self.name}] is {self.age}"

p1 = Person("Sandeep", 49)

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.

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.

How to properly set Getters setters and convertmintosec?

Let me try to explain to you the concept of getters and setters.

Your class Song has some private data fields. It means that they are hidden from the outside world. Now, if any entity outside this class needs to use these fields, it will have to go through an additional step. This step is either a getter or a setter method.

The getter method(s) helps the entities get (or retrieve) the value from these fields. And the setter method(s) helps set (or assign) values to these fields.

Remember that getters and setters are to get from/set to the fields, and not the whole class. Which is why there is a problem with the following:

public String getyearReleased() {
return Song;
}

In the above code, you first say that you want to return a String from the getyearReleased() method, but you see that you are actually returning Song, which is a class.

Here is a simple example of your class with 2 fields and how you get/set them through a main() method in an outside class.

public class Song {
private String songName;
private int yearReleased;

// Getter method for Song Name
public String getSongName() {
System.out.println("Getting the song name.");
return songName;
}
// Getter method for Year of Release
public int getYearReleased() {
System.out.println("Getting the year of release.");
return yearReleased;
}

// Setter method for Song Name
public void setSongName(String mySong) {
System.out.println("Setting the song name.");
this.songName = mySong;
}
// Setter method for Year of Release
public void setYearReleased(int mySongYear) {
System.out.println("Setting the year of release.");
this.yearReleased = mySongYear;
}

}

You should note that the setters don't return anything because they are just setting the values.
But the getters return the same data type as of the field being retrieved.

Here is the class from which you can call the getter and setter methods. This class will contain the main() method:

public class SongDemo {
public static void main(String[] args) {
Song demoSong = new Song();

// call the setters
demoSong.setSongName("Summer of 69");
demoSong.setYearReleased(1988);

// call the getters and print the values returned
System.out.println(demoSong.getSongName());
System.out.println(demoSong.getYearReleased());
}
}

This is what your output looks like:

Setting the song name.
Setting the year of release.
Getting the song name.
Summer of 69
Getting the year of release.
1988

Hope it helps.

What are getters and setters for in ECMAScript 6 classes?

These setter and getter allow you to use the properties directly (without using the parenthesis)

var emp = new Employee("TruMan1");

if (emp.name) {
// uses the get method in the background
}

emp.name = "New name"; // uses the setter in the background

This is only to set and get the value of the property.

How do getters and setters change properties in Dart?

Instance variables in Dart have implicit getters and setters. So for your example code, it will operate in exactly the same way, since all you have done is changed from an implicit getter and setter to an explicit getter and setter.

The value of explicit getters and setters is that you don't need to define both if you don't want. For instance we can change your example to only define a getter:

main() {
Car car = new Car();
print(car.doors); // 4
car.doors = 6; // Won't work since no doors setter is defined
}

class Car {
int _doors = 4;
int get doors => _doors;
}

Additionally, you can also add extra logic in a getter or setter that you don't get in an implicit getter or setter:

class Car {
int _doors = 4;
int get doors => _doors;
set doors(int numberOfDoors) {
if(numberOfDoors >= 2 && numberOfDoors <= 6) {
_doors = numberOfDoors;
}
}
}

Getters and setters in pure C?

First of all, don't listen to anyone saying "there is no object-orientation in language x" because they have truly not understood that OO is a program design method, completely apart from language syntax.

Some languages have elegant ways to implement OO, some have not. Yet it is possible to write an object-oriented program in any language, for example in C. Similarly, your program will not automagically get a proper OO design just because you wrote it in Java, or because you used certain language keywords.

The way you implement private encapsulation in C is a bit more crude than in languages with OO support, but it does like this:

// module.h

void set_x (int n);
int get_x (void);

// module.c

static int x; // private variable

void set_x (int n)
{
x = n;
}

int get_x (void)
{
return x;
}

// main.c

#include "module.h"

int main (void)
{
set_x(5);
printf("%d", get_x());
}

Can call it "class" or "ADT" or "code module" as you prefer.

This is how every reasonable C program out there is written. And has been written for the past 30-40 years or so, as long as program design has existed. If you say there are no setters/getters in a C program, then that is because you have no experience of using C.



Related Topics



Leave a reply



Submit