Advantage of Set and Get Methods VS Public Variable

Advantage of set and get methods vs public variable

What I have seen someday on SO, as answer (written by @ChssPly76) why to use getters and setters

Because 2 weeks (months, years) from now when you realize that your
setter needs to do more than just set the value, you'll also realize
that the property has been used directly in 238 other classes :-)

there are much more advantages:

  1. getters and setter can have validation in them, fields can't
  2. using getter you can get subclass of wanted class.
  3. getters and setters are polymorphic, fields aren't
  4. debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
  5. they can hide implementation changes:

before:

private boolean alive = true;

public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }

after:

private int hp; // change!

public boolean isAlive() { return hp > 0; } // old signature
//method looks the same, no change in client code
public void setAlive(boolean alive) { this.hp = alive ? 100 : 0; }

EDIT: one additional new advange when you are using Eclipse - you can create watchpoint on field, but if you have setter you need just a breakpoint, and... breakpoints (e.g. in setter method) can be conditional, watchpoints (on field) cannot. So if you want to stop your debugger only if x=10 you can do it only with breakpoint inside setter.

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.

Public variables bad practice vs Getters and Setters functions?

First of all, a struct is completely equivalent to a class, but with the default member access being public rather than private.

Now, in Object Oriented Programming (OOP), it's not considered good practice to have public data members (variables), because that makes all your code dependent on the internals of the class, and thus breaking a primordial principle of OOP, and that is...

Holy and Sacred Encapsulation

Encapsulation is the coding philosophy that states that a class should englobe both data and the code that manages it in a single tight entity. That is, you don't access data directy, but rather you use methods from the class to manipulate such data. This has several design advantages, such as that you'll know that no code except the one inside the class may incorporate bugs with respect to the manipulation of such information.

Now, get()ers and set()ers, otherwise known as accessors, are a complete lie! With accessors, you're tricking yourself into thinking that you're respecting encapsulation, when you're rather breaking it! It adds bloat, unnecessary verbosity, bugs, and everything but encapsulation. Instead of having a class Person with unsigned getAge() and void setAge(unsigned), have it with a unsigned getAge() and a void incrementAge() or however you want to call it.

Now, to your question's core...

"Plain old" structs

Encapsulation is not always desired. Although you should (usually) not do this on header files (again, for at least some bit of encapsulation), you may create static plain old structs that are private to a single translation unit. My recommendation is to make them even "older" than they already are, i.e...

  • All data members are public.
  • No methods.
  • No constructors (except implicit ones).
  • Inheritance is always public, and only allowed from other plain old structs.
  • I repeat, don't put them on header files!

Now, another use for plain old structs is (ironically) metaprogrammatic exporting of constexpr data and types, otherwise known as modern-hardcore-template-metaprogramming-without-having-to-type-public-everywhere, for example...

template<bool B, typename T>
struct EnableIf {};

template<typename T>
struct EnableIf<true, T> {
typedef T type;
};

template<bool B, typename T>
using SFINAE = typename EnableIf<B, T>::Type;

Public vs Private{get, set}

Yes, the difference is that you have a property. Properties in C# are a syntax sugar over having a pair of get and set method. The compiler in fact takes the code blocks and creates two separate methods: get_PropertyName and set_PropertyName, where PropertyName is the name of your property. These methods have the exact logic you implement in the get and set blocks respectively, and the code using your property will in fact be calling these methods behind the scenes.

The advantage of this is that you have full control over the way the value is set and retrieved.

Example - imagine you want to store age:

public int Age;

Now anyone using your class can easily set the age to any value they please - 1000, -1, anything.

Now if you have a property, you can make sure that doesn't happen:

private int _age = 0;

public int Age
{
get { return _age; }
set { if ( value >= 0 && value < 120 ) _age = value; }
}

Most of the time it is beneficial to declare public fields as public properties even though you don't need any validation logic, because you might need to add one in the future and if you act proactively by creating a property in the first place, other code using your library won't need to be recompiled to work.

Properties also give you more fine-grained control over the visibility of getters and setters. You can have a public property with public getter and private setter to make sure only the class itself can change the state of the property.

public Connected { get; private set; }

In addition, there are places where you really need to have a property. One of those is using the INotifyPropertyChanged interface in the MVVM pattern for WPF, UWP and others. Data binding requires a property to be bound to (although this is not completely true if you don't need notifications, as the new {x:Bind} syntax in UWP can bind to ordinary fields).

What's the point of get/set method if you can declare the field as public?

You should not set your field as public. This is encapsulation in java. Others doesn't know how the values are populated in to the private variables, they may change it from several places, atlast it become a huge mess. But they have access to some method which is public. I didn't say Getters/Setters.

So up to your point Getter/Setter . Don't use that if you follow java encapsulation. This is same as public variable then (May be some more logic added to it, but user can alter that using setter).

What you have to do is, expose public method in the same class, do whatever manipulation you want to do with instance variables and return only the required results that user need to know.

Eg: Take a class CocaCola . You write a method createCola(). inside that you create the cola and return the result. User doesn't need to know the ingredients of Cola. If you create Getter/Setter otr make the ingredient public that is worse.

These are just standards or best approach in java, that experts suggest. So if you don't want to follow, you don't need to .

Refer:

Java Getters/Setters are evil

Public Data members vs Getters, Setters

Neither. You should have methods that do things. If one of those things happens to correspond with a specific internal variable that's great but there should be nothing that telegraphs this to the users of your class.

Private data is private so you can replace the implementation whenever you wish (and can do full rebuilds but that's a different issue). Once you let the Genie out of the bottle you will find it impossible to push it back in.

EDIT: Following a comment I made to another answer.

My point here is that you are asking the wrong question. There is no best practice with regard to using getters/setters or having public members. There is only what is best for your specific object and how it models some specific real world thing (or imaginary thing perhaps in the case of game).

Personally getters/setters are the lesser of two evils. Because once you start making getters/setters, people stop designing objects with a critical eye toward what data should be visible and what data should not. With public members it is even worse because the tendency becomes to make everything public.

Instead, examine what the object does and what it means for something to be that object. Then create methods that provide a natural interface into that object. It that natural interface involves exposing some internal properties using getters and setters so be it. But the important part is that you thought about it ahead of time and created the getters/setters for a design justified reason.

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.

what is the benefit of get set for simple variables

This question was asked many times here.
There is no clear benefit evidence fo these cases (no logic inside property).
Would say more, that using a field, you get some minimal (nano) speed benefit, but not relevant for 99.99% cases.

The guideline defined by MS suggests using properties, for expandibility and maintanability of your code. So following that guideline make easier work for someone that not familiar with the code to reading it.



Related Topics



Leave a reply



Submit