When should I make property functions?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Nov 19 20:36:42 UTC 2018


On Monday, November 19, 2018 1:11:11 PM MST Trent Caprico via Digitalmars-d 
wrote:
> In Java, it is considered best to always make all member
> variables private, and make getters/setters for the 'public'
> members.
>
> In D, should I create @property functions for all 'public' fields
> when I first define the class, or is it best to wait until a
> property function is actually needed?

In general, you should prefer to keep the fields private. While property
functions do simulate variables, they don't really follow the same semantics
(e.g. taking the address doesn't do the same thing, and you can pass a
variable by ref, but you can't pass a property function by ref). So, if you
change a public member variable to a property function later, you risk
running into problems - this is especially true if you're providing a
library for other people to use as opposed to simply writing a type for use
in your own application where you control all of your code. Another
consideration is that invariants are called before and after public
functions are called (assuming that you don't compile with -release), so if
your type has an invariant, it will be called before and after a call to a
public property function, whereas if you have a public member variable, the
invariant isn't checked at all.

These considerations are of course lessened if we're talking about a type
that is just inside your application where you're in complete control of all
code that uses it, so you if you later change the type, you can change all
code using it (whereas with libraries that you make available, you have to
be far more careful), but the basic reasons for why you would make member
variables private in languages such as Java still apply. Ultimately,
property functions in D are pretty much just a nice syntactic improvement
over getters and setters. They don't really change the fundamental issues
surrounding public member variables.

- Jonathan M Davis





More information about the Digitalmars-d mailing list