Properties

Chad J gamerchad at __spam.is.bad__gmail.com
Thu Jan 8 10:07:13 PST 2009


Michiel Helvensteijn wrote:
> Nick Sabalausky wrote:
> 
>> 2. You shouldn't have to manually define a private var to go along with
>> the property. In languages with real properties, the following idiom is
>> used constantly:
>>
>> private int _var;
>> public property int var {
>>    get { return _var; }
>>    set { _var = $; }
>>    void opIncrement() { _var++; }
>> }
>>
>> Why should that be needed? It should be like this:
>>
>> public property int var {
>>    // int internalValue; // Automatically created (but named better)
>>    get { return internalValue; }
>>    set { internalValue = $; }
>>    void opIncrement() { internalValue++; }
>> }
>>
>> In the minority of cases where a property doesn't need this variable,
>> "internalValue" can just be optimized away.
> 
> If you really want that behavior, you should just use a public variable.
> Even changing it to a real property later would not matter for the public
> interface.
> 

That's not quite why it was suggested.

I actually like the idea.

It is true that a public member would be preferred in the trivial case.
In the general case though, people will have some internal value they
are working with and whenever someone works with it they want side
effects to happen.
Here's an example:

int nTimesVarRead = 0;

public property int var
{
    get
    {
        nTimesVarRead++;
        return internalValue;
    }

    set { internalValue = $; }
}

compare against:

int nTimesVarRead = 0;
int m_var; // Annoying extra declaration that is common practice.

public property int var
{
    get
    {
        nTimesVarRead++;
        return m_var;
    }

    set { m_var = $; }
}

Thus I rather like that idea.

Perhaps, since the compiler knows the name of the property, the name of
the generated internal value could just be the name of the property:

public property int var
{
    get { return var; }
    set { var = $; }
}

public property int foo
{
    get { return foo; }
    set { foo = $; }
}

etc.



More information about the Digitalmars-d mailing list