property-like data members

Ali Çehreli acehreli at yahoo.com
Sun Jan 2 13:46:40 PST 2011


spir wrote:
 > Using properties allows travesting a method call into direct data 
access. What if the underlying member actually is plain data? Would it 
be possible to provide a real data member where the language expects a 
property (for instance as range empty & front properties)?

There has been a lot of discussions on properties and their syntax.

There is a complexity in your proposal: should we allow write access to 
@property members? We would need to come up with a way to limit write 
access.

 > Is there any difficulty for the compiler to check whether a data 
member of the same name and correct type exists? To help it, we could 
mark said data member with an @property hint. For instance:
 >
 > struct String {
 >     char[] cs;
 >     private uint index = 0;     // for traversal
 >     @property char front;
 >     @property bool empty;
 >     this (string characters) {
 >         this.cs = characters.dup;
 >         this.empty = (this.cs.length == 0);
 >         if (this.cs.length > 0)
 >             this.front = this.cs[0];
 >     }
 >     @property void popFront () {
 >         ++ this.index;
 >         this.empty = (this.index >= this.cs.length);
 >         if (this.index < this.cs.length)
 >             this.front = this.cs[this.index];
 >     }
 > }
 > unittest {
 >     auto s = String("abc");
 >     // works fine
 >     while (! s.empty) {
 >         auto c = s.front;
 >         write(c,' ');
 >         s.popFront;
 >     }
 >     writeln();
 >     // works not
 > //~     foreach (char c ; s) write(c,' ');
 >      writeln();
 > }
 >
 > Here, popFront does not only advance, it correctly sets empty and 
front, so that a single method is needed. But the language expects a 
method-property (actually, it complains for missing opApply *).

Phobos is happy with 'empty' being a static member. The following member 
would make an infinite range:

   static enum bool empty = false;

But I know that you don't want that. :)

The actual problem in your example is the missing front() function.

 > I'm a bit troubled to implement methods where plain data does the job 
and conceptually better matches my model (maybe it's only me: I wish the 
code to mirror my views).

Having never used a language that had properties, I am very happy how D 
handles them. Having to write a one-liner doesn't bother me.

Ali


More information about the Digitalmars-d mailing list