Question

Is there a benifit to using:

private var _someProp:String;

public function set someProp(value:String):void
{
    _someProp = value;
}
public function get someProp():String
{
    return _someProp;
}

As opposed to just using:

public var someProp:String;

I realise using getter/setter can be useful when you need to further processing or need to be notified of when the property is changed like so:

public function set someProp(value:String):void
{
    _someProp = value;
    _somePropChanged = true;
    doSomethingElse();
}

But if you don't need this, then is there any reason to use getter/setter over just using a public var?

Thanks!!

Was it helpful?

Solution

Depending on your language, you should prefer getter/setter up front because you can't introduce them later (I'm looking at you, Java) if it turns out you do need them.

OTHER TIPS

This really depends a bit on the language/framework/toolkit you are using -

However, there are often benefits when using getters and setters related to versioning and API compatibility. This can be a very useful reason to use them, all on its own.

This really can't be answered without knowing the language. Getters and Setters cost more in most languages, but they buy you flexibility down the road. In some languages you can't change a public to a Getter/Setter without changing the code in the callers because the use syntax changes. But this is not an issue with C#, which I what I write in mostly.

Getters and Setters let you do parameter validation. They let you delay creation of objects until first reference. They have a lot of advantages, and I use them whenever I need one of those advantages from the beginning.

But I use getters and setters ONLY when I need them right away, or when I'm pretty sure I'm going to need the flexibility. Otherwise I view them as bloat.

As a side note, you can start with a public var and if necessary convert it to a getter / setter later in code.. depending on the language you are using.

If your property is totally dumb, and has no side effects on the rest of the class - then by all means just expose it as a public field.

Its just that in many cases your properties will have side effects, so you need to control how they are set and accessed.

As a trivial example, what happens if your public variable is not set to something in your constructor? Are you ok with this being returned as null? Or would you like to set this variable to something rather than return null? This is a simple example where a custom getter is worthwhile.

Getters and Setters also give you more control over what values the variable can be set to.

bool setAge(int age){
   bol retVal = true;

   if(age <= 0)
       retVal = false;

   return retVal;
}

Without the setter, the value could be set to zero and bad things could happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top