Suggestion: properties should be treated as 'virtual members variables'
Reiner Pope
reiner.pope at REMOVE.THIS.gmail.com
Tue Sep 5 05:21:39 PDT 2006
While we're discussing this, I'm wondering: what is the reason that D
doesn't use explicit properties like C# does?
Somewhere, the spec says that properties are useful for turning a pure
data member into a getter/setter pair without breaking code. C#
properties allow this feature, including the required syntax for
treating them as lvalues, and I believe this is pretty safe because of
the explicit nature of declaring properties.
Walter, is there a reason you decided against such a syntax, or are you
simply not aware of it?
As to the solution for D, I like what Derek proposed:
a.func();
means func is treated as a function, with no special semantics (which
means it can't be an lval), but
a.func;
means that func is treated as a property. This means a getter is
required for rval semantics and a setter is required for lval semantics.
However, the problem with this is that it does not obviously scale. For
instance, how does this approach work with opIndex(Assign) where there
are multiple parameters? Should the solution to this only work for
opIndex, or should it apply to arbitrary functions?
I haven't given this too much thought, but my current inclinations is
that an explicit syntax is the right way to manage this. This suggestion
here would be very similar to C# properties, but can support extra
parameters:
1. Add the keyword 'property', 'value', 'get' and 'set'. Alternatively,
you could use -> and <- instead of get and set if the keywords are
already used too much.
2. Syntax looks like this:
class C
{
private int m_val;
// Looks just like C# but has the property keyword to distuinguish from
a nested function. This is the simplest type of property.
property int Val
{
get { return m_val; }
set { m_val = value; }
}
}
This would get expanded to
class C
{
private int m_val;
int __set_Val(int value) { return m_val = value; }
int __get_Val() { return m_val; }
}
However, the difference from C# is that you can give parameters to
properties:
class D
{
private int[] myArray;
property int myAccessor(int index)
{
get { return myArray[index]; }
set { myArray[index] = value; }
}
}
Being explicit like this lets you pair up arbitrary functions into
getters and setters to behave like this. To ensure against unexpected
behaviour, then you keep Derek's rule:
a.foo; // requires foo is a property or data member
a.foo(); // requires foo is a function
Thanks for following this disjointed post.
Cheers,
ReinerHmm, would it be simplier to implement properties by using virtual
tables for variables?...
(What object oriented languages did for functions, D does it for
variables! *grin*)
More information about the Digitalmars-d
mailing list