In C#, they have introduced automatic properties for that purpose
of "initial encapsulation":
public int i { get; set; } //get and set can be modified with
private etc
Then the getter and setter methods are automatically implemented.
I'm not closely following the discussions involved in the
re-design of properties, but I disagree with the people that
believe properties are glorified fields. IMO, they are
essentially functions, accessed like fields, that can set and/or
expose state. I'm also against 2-parametrized properties btw.
Example: define a interface for geometric figures with a "area"
property and then implement it for square, circle, hexagon,
triangle etc
On Thursday, 7 February 2013 at 20:26:10 UTC, Jonathan M Davis
wrote:
It works as long as you can limit the variable in some way. But
I believe that
the main purpose in using public variables rather than actual
property
functions when all they would do is get or set the variable is
to avoid lots
of boilerplate code. It's incredibly common to get stuff like
struct S
{
int i() @safe const pure nothrow
{ return _i; }
int i(int value) @safe pure nothrow
{ return _i = value; }
private int _i;
}
That's a lot of extra code whose only benefit is encapsulation.
So, it would be
great if you could just do
struct S
{
int i;
}
And with the ability to replace the variable with a property
function later if
it ever needs to do more than just get or set makes it so that
encapsulation
isn't a problem - except for the fact that there are certain
operations that
you can do on a variable that you can't do on a property
function (e.g. taking
its address or passing it by ref). Simply making it so that
doing
struct S
{
@property int i;
}
lowered into something like the first example would allow you
to avoid all of
that boilerplate code and still have full encapsulation.
It's definitely true that you can never make a property
function completely
emulate a variable, but all of the boilerplate required for
simple getters and
setters is kind of ridiculous. I believe that avoiding that is
the primary
reason that people want to be able to swap between variables
and property
functions, and with a small addition to the language, we can
obviate that
boilerplate.
- Jonathan M Davis