Re: News for Java?
On 1/5/11 2:33 AM, Arved Sandstrom wrote:
There are no real problems having setters??? Come on, Arne, are you just
being rambunctious these past few or what? Leaving aside getters
completely (and all the real-world problems associated with over-use of
those), every setter on a class introduces a vulnerability: it's an
additional worry when you reason about what external code is modifying
instances of that class. [...]
Red herring.
You guys can debate the question of abuse of setters 'til the cows come
home. It will never have any relevance to the question of
language-supported properties. If a programmer is likely to overdo it
with the setters with language-supported properties, they are just going
to overdo it without language-supported properties too.
After all, it's not that Java doesn't have "properties" per se today.
It's just that the syntax is indistinguishable from the syntax for
methods, other than following some simple conventions regarding naming.
So, if I'm a programmer who would write this:
private int _value;
public int Value
{
get { return _value; }
set { _value = value; }
}
Instead of this:
private int _value;
public int Value
{
get { return _value; }
}
Then I'm also a programmer who would write this:
private int _value;
public int getValue()
{
return _value;
}
public void setValue(int value)
{
_value = value;
}
Instead of this:
private int _value;
public int getValue()
{
return _value;
}
Language-supported properties neither encourages nor discourages that
kind of program.
Note also that, at least in the C# implementation (other languages may
have similar rules), you can write this:
public int Value { get; private set; }
That declares the backing field, and both accessor methods all in one
line of code. The setter is private, thus allowing the property to be
read-only to the public. Typically, the declaring class would use the
private setter in the constructor only, and of course that would be de
rigueur for immutable types.
Pete