0

Possible Duplicate:
Are Getters and Setters evil?
Why use getters and setters?

I've been asking myself this for awhile but why do we actually use Getters and Setter methods? They take up extra space in our code, can someone explain. I've posted some code below for a better understanding.

public class Test2
{
   public int _ChangeThis = 0;
}

--- Other way ---

public class Test1
{
    public int _ChangeThis = 0;

    public setChangeThis(int ChangeThis)
    {
        _ChangeThis = ChangeThis;
    }

}

--- Main code ---

Test2 testclass = new Test2();

//What is the difference and why do we use the setter? I cannot understand the advantage.
testclass.setChangeThis(1);
testclass._ChangeThis = 1;
Community
  • 1
  • 1
Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95
  • check object composition & strategy pattern --there can occour situations in which you ll have to set an objects properties to itself and retrive it to avoid complaxities – Athul Harikumar Aug 30 '12 at 12:57
  • Are you sure, that your first example will work? You want be able to change *private* field of some object within other object without setter function. – Xentatt Aug 30 '12 at 12:58
  • 1
    because it helps to maintain your project by giving you an abstraction so that if your variable needs to be changed it will affect only one file and not the whole projrect ? – midnight Aug 30 '12 at 12:58
  • I don't know either... is it really warranted? Not so sure anymore... – Jaco Van Niekerk Aug 30 '12 at 12:58
  • Look at groovy if you don't like to deal with getters/setters. They will be generated but you don't have to use them. – maba Aug 30 '12 at 13:08
  • http://en.wikipedia.org/wiki/Information_hiding – Mr. Ghiandino Aug 30 '12 at 13:25

1 Answers1

6

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.

David W
  • 10,062
  • 34
  • 60