@property get/set or public varaible?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 4 12:44:05 PST 2016


On Sunday, December 04, 2016 15:30:22 vladdeSV via Digitalmars-d-learn 
wrote:
> Hello!
>
> I have a question not directly related to D as it is with coding
> standards.
>
> My issue at hand is if I have one variable for a class, which I
> want to be directly accessible for anything else, should it be
>   1. public, or
>   2. private, with @property get/setters?
>
>  From what I have been told is that variables should be private.
> But if I do not want to make any checks whatsoever when setting a
> variable, I see no benefit to the private approach.
>
> Are there any other reasons to use get/setters?

The big reason to use getters and setters over public variables is that
converting public variables to property functions is _not_ seemless.
Property functions act like variables for some basic operations like
assignment, but you try and do much more than that, and they start behaving
drastically differently. For instance, what happens if someone takes the
address of a property? Or passes it by reference? As long as that property
is a member variable, it works like a variable, but if it's changed to a
property function, then those operations either have different types and
don't compile with existing code, or the operations don't work at all. Even
basic operations such as ++ don't work with property functions.

I'm sure that there are folks in the D community who favor using public
variables rather than property functions if they're not going to do anything
beyond getting or setting, but you're at serious risk of code breakage if
you do - especially if you're doing it in an API that you're distributing to
other people. For your own personal stuff or stuff that is internal to
whatever project you're doing where you can change all of the code that uses
the property, then it can work to use a public variable and then change the
code later if necessary if and when it becomes a property function. And
since most public variables don't get turned into property functions later,
you probabably will only have to deal with code breakage rarely, and it will
be easy for you to fix the few places where the property was used in a way
that works for a public variable but not for a property function. But if
you're distributing a library with a property that's a public variable, you
can't change all of the code using that property, and changing it to a
property function could easily break other people's code.

So, do what you want for internal stuff, but don't use public member
variables in libraries that you're distributing unless it's certain that
they will never be anything but public variables.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list