Re: How to emluate "properties" in Java?
Peter Duniho wrote :
Right now, in Java, "a.b = 5" is always going to set a field in the object
A to 5. If you had properties, the same syntax could also mean to call a
function with an argument of 5, which may or may not set a field to 5. It
could also just decide to sneer in your face for the heck of it.
Let's compare:
a.b = 5;
a.setB(5);
How does the second line of code in any way tell you what the method is
doing? If anything, a property carries with it a strongly implication that
the _object_ itself will be modified. A method named "setB()" could do
anything.
And if Java had properties, an implied function (um, method) would be
called which: "could also just decide to sneer in your face for the
heck of it."
The difference is that a.b=5 WILL set b to 5, whereas having properties
it may or may not. Exactly as a setB() could do.
I do not like implied actions (and I really do not like operator
over-loading).
By contract setB() will eventually set b to 5, though it may do some
other processing along the way. And that is just fine, as the class has
the right (and responsibility) to make sure that the 5 is a valid
value. It may also decide to add 5 to some other internal field which
is hidden from view.
Consider: a.setName("Wojtek");
A.setName(String theName)
{
this.theName = theName;
}
The class is distributed, then users complain that the values sort
funny. Investigation shows that a sort value is never set by some end
programmers (silly people).
So now you can send out a strongly worded letter to all the programmers
using your class, OR:
A.setName(String theName)
{
if(getSort().length()==0)
setSort(theName);
this.theName = theName;
}
The class ensures that if a name is set, and a sort value has not
already been set, that there will be a sort value. You send out an
update and the issue is fixed.
Using a.theName="Wojtek" would completely prevent you from issuing a
fix and you would need to rely on the goodness of the end programmer to
use your class "properly".
And if the sort is case insensitive:
A.setSort(String sortValue)
{
this.sortValue = sortValue.toLower(sortValue);
}
No. I greatly prefer using get/set for ALL changes to class properties.
--
Wojtek :-)