Page 1 of 1

I found a use for properties :)

Posted: Sat Dec 30, 2006 3:58 pm
by timvw
Perhaps you still remember, but a while ago i asked myself (here): Do we really need properties?

At the time i considered properties to be syntactic sugar (and nothing more) for methods we would otherwise call GetX and SetX...

Earlier this week i figured out that properties actually can do something which methods can't do: They give you the power to replace a variable with the result of a method.

Eg: Originally Foo had a field $bar.. And now some business changes have occured and instead of using a simple value $bar you need to calculate it instead. So you would have to update all the places that use $myInstance->bar with $myInstance->GetBar()...

Well, properties give you the chance to actually leave the external code as is.. The only thing that you have to do is remove the $bar field.. and implement __get/__set so that they call GetBar/SetBar...

Posted: Sat Dec 30, 2006 8:47 pm
by julian_lp
wouldn't be enough just never call a member field directly?

I mean, one never should call

$val = $obj->var_name;

instead, it'd be much more convenient doing

$val = $obj->Get_var_name();

I really work this way cause it seems to me very confusing not using parenthesis on an object call...

Posted: Sun Dec 31, 2006 4:53 am
by timvw
julian_lp wrote:wouldn't be enough just never call a member field directly?I mean, one never should call
$val = $obj->var_name;
The problem is that you don't always have control over code that was already written... Anyway, here's the situation which made me realise there was a good use for properties...

Code: Select all

public class BusinessParamters {
  public const int MyLimitation = 5;
}
As long as MyLimitation is a constant, it makes perfect sense not to wrap it in a function. But as i noticed, if the rules change it can be easily changed into:

Code: Select all

public class BusinessParameters {
 public static int MyLimitation {
  get {
    // calculate some things...
    return 10;
  }
 }
}
But perhaps properties are less useful for php... (Since __set and __get can't be static...)