Possible @property compromise

Jonathan M Davis jmdavisProg at gmx.com
Tue Jan 29 18:21:59 PST 2013


On Wednesday, January 30, 2013 02:40:45 TommiT wrote:
> On Wednesday, 30 January 2013 at 00:25:41 UTC, Jonathan M Davis
> 
> wrote:
> > On Wednesday, January 30, 2013 00:55:13 Rob T wrote:
> >> [..]
> >> You know a lot more about implementing compiler magic than I
> >> do, so I'll ask you if you think the effort is doable enough
> >> to justify having property functions that can act like a
> >> drop in replacement for existing variables?
> > 
> > I believe that two main things are needed: [..]
> 
> I always thought that having public member variables is a bad
> style of programming because of the lack of encapsulation. So, if
> there's a language feature that enables you to write public
> member variables, and later on, replace them with property
> functions, wouldn't that mean that the language is encouraging
> this particular kind of bad style of programming?

Aside from the ability to take the variable's address, what really is the 
difference between

struct S
{
 int prop;
}

and

struct S
{
 @property int prop() @safe const pure nothrow
 { return _prop; }

 @property int prop(int value) @safe const pure nothrow
 { return _prop = value; }

 private int _prop;
}

At the moment, stuff like ++ and += wouldn't work with @property, but that 
could be fixed. But as far as access goes, there's no real difference. You have 
full read-write access in both cases. That being the case, why bother with the 
property functions? What you're supposed to be able to do (and C# let's you 
do, but we can't with our current implementation of properties), is start with

struct S
{
 int prop;
}

The code's shorter and simpler. You don't need any checks on the data, and you 
don't need to do any operations when the property gets set. So, a variable is 
just fine. Then when you actually need to do something extra when the property 
is set, you change it to a property function.

struct S
{
 @property int prop() @safe const pure nothrow
 { return _prop; }

 @property int prop(int value) @safe const pure nothrow
 {
 validate(value);
 _prop = value;
 doSomethingElseWhichCaresAboutPropChanging();
 return _prop;
 }

 private int _prop;
}

And no code is broken. That works in C#, but it works there, because they 
actually have a good property implementation, and you can't take the address 
of a variable in C# like you can in D. If we want the same, we need to fix it 
so that the compiler does proper rewriting of code like s.prop++ and make it 
so that we can mark variables as properties (so that you can't take their 
address or pass them by ref or do anything else that you can't do with a 
property function). e.g.

struct S
{
 @property int prop;
}

But a public variable isn't a problem if the language allows you to swap it 
out with a property function without breaking code.

- Jonathan M Davis


More information about the Digitalmars-d mailing list