@property Incorrectly Implemented?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 7 02:34:12 PDT 2016


On Wednesday, September 07, 2016 08:15:43 Kagamin via Digitalmars-d wrote:
> On Tuesday, 6 September 2016 at 19:37:26 UTC, Jonathan M Davis
>
> wrote:
> > but an @property function which returns by ref isn't worth
> > much, since you're then giving direct access to the member
> > variable which is what an @property function is usually meant
> > to avoid. If you wanted to do that, you could just use a public
> > member variable.
>
> It can do lazy initialization, allow to set a breakpoint, log
> access etc.

But if you return the value by ref, then you pretty much circumvent all of
that, because then someone can do something like take the address of the
return value and procede to mutate it whenever they want without hitting
your breakpoint or log messages or any of that. You can do a few things that
can't be done with a public member variable, but on the whole, returning by
ref defeats the purpose of having a property function. And there are plenty
of property functions that don't even refer to variables but instead are
calculated, in which case there is no variable to return a ref to anyway.

So, while some @property functions may return by ref, most won't, and it's
arguably a bad idea in general.

> > You're dealing with an @property function which is just trying
> > to emulate a variable.
>
> That's the whole point. It's trying to emulate a variable, so why
> not make it do it?

Because aside from a few basic operations, it's not possible. Stuff like
assignment can be made to work, but something as simple as passing by ref
falls simply cannot be done except in the case where the @property function
returns by ref - which is not the normal case. And for a large percentage of
property functions, you don't want it to be the case that taking the address
of the property function gives you a pointer to a member variable.

There are certainly some operations that we could better emulate with
@property functions that currently don't work without returning by ref (like
++ or -=), but something like taking the address of the @property function
simply isn't going to work in most cases, and neither is passing by ref.
Basically, only stuff that can be lowered to calls to the getter and setter
@property functions is going to work. Anything that would require an actual
variable with an actual memory location isn't going to work unless the
@property function returns by ref, and making taking the address of that
kind of @property function give you the address of the variable would then
not be consistent with any other @property function, which would create a
different set of problems.

It's nice that we can have property syntax rather than having to have
functions that start with get and set, but it really doesn't work to fully
emulate variables.

- Jonathan M Davis



More information about the Digitalmars-d mailing list