Why are there Properties in D?

Rikki Cattermole alphaglosined at gmail.com
Fri Feb 14 01:54:53 PST 2014


In most languages, people utilise getters and setters for member 
variables of e.g. classes.

So instead of code like this:

Person getAuthor() {
     return this.author;
}

In D we can have:

@property Person author() {
     return this.author_;
}

(I appended an underscore to make it not conflict between 
internal property and the method).

Like most features you can over use them as you said.

This is a highly flexible method of setting and getting 'meta' 
internal data. This could be transformed and manipulated. You 
cannot do this with a plain old property on the class.

Other languages like C# have their own solutions to this. In C# 
they utilise:
public string Name
{
    get
    {
       return name;
    }
    set
    {
       name = value;
    }
}

As a property declaration.
A little less powerful but one I would love D to have (although 
doable via mixin templates).
It can also be simpler to the point of:

accessor type name {get; set}

If I remember right.

With D property function, you can still utilise them with the 
brackets.
e.g.
Person authorOfMyFavouriteBook = book.author();

But it infers that its taking action, instead of a internal 
'meta' data.

On the note of having to reread declarations ext. You have to do 
this at any rate. If you don't understand the code then you need 
to go work it out, before you can use it.

This is more of a D.learn post. But no worries.


More information about the Digitalmars-d mailing list