Property discussion wrap-up

Zach the Mystic reachBUTMINUSTHISzach at gOOGLYmail.com
Mon Jan 28 21:39:13 PST 2013


Just for kicks I decided to rewrite std.array.front in the way my 
suggested syntax would define it. there are two overloads. With 
comments removed, the current code is:

//---- Code ----
@property ref T front(T)(T[] a)
if (!isNarrowString!(T[]) && !is(T[] == void[]))
{
     assert(a.length, "Attempting to fetch the front of an empty 
array of " ~
                      typeof(a[0]).stringof);
     return a[0];
}

@property dchar front(A)(A a) if (isNarrowString!A)
{
     assert(a.length, "Attempting to fetch the front of an empty 
array of " ~
                      typeof(a[0]).stringof);
     size_t i = 0;
     return decode(a, i);
}
//---- End -----

With what I am calling Highlander structs ("there can be only 
one"), it would look like this:

//---- Code ----
front struct
{
   ref T opGet(T)(T[] a)
   if (!isNarrowString!(T[]) && !is(T[] == void[]))
   {
       assert(a.length, "Attempting to fetch the front of an empty 
array of " ~
                        typeof(a[0]).stringof);
       return a[0];
   }

   dchar opGet(A)(A a) if (isNarrowString!A)
   {
       assert(a.length, "Attempting to fetch the front of an empty 
array of " ~
                        typeof(a[0]).stringof);
       size_t i = 0;
       return decode(a, i);
   }
}
//---- End -----

Three things stood out to me:
1. The identifier "front" only appears once now, prominently at 
the top of all the definitions.
2. Definitions of "front" cannot be scattered willy-nilly 
throughout the file anymore.
3. Without @property, the signatures are shorter, and the only 
price paid is the three extra lines it takes to wrap the whole 
thing with "front struct { ... }".

I don't think this is a bad exchange at all, considering you now 
have all the semantics of structs at your disposal for absolute 
total control over the look and feel of your properties.




More information about the Digitalmars-d mailing list