DIP4: Properties
Michiel Helvensteijn
m.helvensteijn.remove at gmail.com
Mon Jul 27 01:56:29 PDT 2009
BLS wrote:
>> I think people got it. But it's not a property. Your one-liner seems to
>> be equivalent to a field. Except, I guess, that you can't take the
>> address.
>>
>> The whole idea of a property is that it can have non-trivial
>> getter/setter functions. Like a read-only property of a Line, that
>> returns its length automatically calculated from its two points. Or a
>> getter and setter that keep a log of all accesses to the information.
>>
>> My favorite example is of a Color class, that internally stores its value
>> in the RGB model, but has properties to read and change its value through
>> the HSV and HSL models as well.
>
> ...
Again, what is the difference between your one-liners and simple fields?
immutable property uint theAnswer = 42;
bool has_cojones;
A property is much more sophisticated. The whole point is to write your own
setter and getter methods. Only in very few cases do you want a property
with simple field semantics. I will give you that Line class I was talking
about. Tell me how you can do this with your one-liner:
class Line {
private:
Point _a;
Point _b;
public:
this(Point a, Point b) { _a = a; _b = b; }
property float length {
auto get() {
float absX = abs(_a.x - _b.x);
float absY = abs(_a.y - _b.y);
return sqrt(absX * absX + absY * absY);
}
}
// insert trivial properties to read/write points
}
You see, the length property doesn't have its own storage. It deduces its
value from the points of the line.
--
Michiel Helvensteijn
More information about the Digitalmars-d
mailing list