Properties: a.b.c = 3

Chad J chadjoan at __spam.is.bad__gmail.com
Thu Jul 30 00:07:49 PDT 2009


Zhenyu Zhou wrote:
> Chad J Wrote:
>> Zhenyu Zhou wrote:
>>> What about:
>>>
>>> class Widget
>>> {
>>>  	Rectangle _rect;
>>>  	immutable(Rectangle) rect() const { return _rect; }
>>>  	Rectangle rect(Rectangle r) { return _rect = r; }
>>> }
>> You'll fall into the trap unless you know about immutable.  Said another
>> way: the default is unsafe.  Also this still isn't very useful, as it
>> still requires the calling programmer to manually break apart the
>> accesses and will not work for things like "array.length++;" which were
>> errors already.
>>
>> So even if newbies were omniscient and always made their getters
>> immutable, all you'd have accomplished is turning a debugging session
>> into an annoyance.  Noble, but all too bitter when a complete solution
>> is within grasp.
> 
> Maybe this is what you want
> ref rect() { return _rect; }
> 
> But I would still return const type because it's unsafe to change the rect without calling its setter
> 

The point is to make sure that when a property's member appears on the
left-hand-side of an assign expression, the setter will be called.  All
this is doing is outright forbidding the property's member to appear on
the left-hand-side of an assign expression at all.  It's a step in the
right direction, but we can do better.

(Some of what I said there is probably wrong at a technical level, but
I'm trying to be clear and not pedantic.)

> e.g.
> Rectangle rect(Rectangle r) {
>   _rect = r;
>   redraw(); 
>   return _rect; 
> }
> 
> If you allow
> widget.rect.w = 200;
> widget.rect.h = 100;
> you will have to write much more code to handle the painting correctly. 
> and we don't want to call redraw twice here
> 
> 

meh, it's not going to cost anything to resize until the next frame is
rendered anyways ;)

Widgets and Rectangles are just an arbitrary example used to show where
people can get trapped by the language's misfeature.  Solving this only
for Widgets and Rectangles will, well, only do that much, and thus be a
waste of time since we've already acknowledged the problem and know how
to hack around it in existing code.



More information about the Digitalmars-d mailing list