For a read-write property the underlying field is exposed to the
outside and there isn't any encapsulation to care about. One might as
well make the field public. This gives clearer, crisper and easier to
maintain code. The rule "Never use public fields" isn't proper
encapsulation.
I suppose that depends on your definition of "encapsulation". But the
definition I use definitely includes "never use public fields" as a
mechanism to achieve encapsulation.
The field is an implementation detail. The property is the behavior
exposed by the class. Proper encapsulation hides implementation details
while preserving behaviors. By hiding implementation details, the class
implementation can change arbitrarily, and as long as the class
continues to provide its publicly declared behavior, there's no problem.
There is no way to change from a public field to a public property after
the fact. The difference between the field and a property is a
_behavioral_ difference, and only by changing the _behavior_ of the
class can you modify that part of the design of the class.
But if you use a property from the outset, you can modify your
implementation however you like without having to change the behavior.
This is what encapsulation is all about, and that's why never using
public fields when you can instead use a property is very much part of
proper encapsulation.
Proper encapsulation is to hide fields that are not
needed from the outside,
See, here's the fundamental difference in opinion: you believe that
encapsulation is only about "hiding" things that "are not needed from
the outside".
That's certainly one way to describe it, but it's my opinion that
encapsulation is different from that. The difference is subtle,
granted. But IMHO it's a very real difference.
but also to realize that once in a while some
internal data of an object must be exposed and public fields are a
good candidate to implement this behavior.
Well, how about that? I would agree that if "some internal data of an
object must be exposed", then you have to expose it and you have to use
public field to do that. But when does that actually happen? Can you
provide an example?
I'll start out with the obvious one: a class that is actually more like
a struct, and doesn't really have any behavior but is rather just a
place to keep data. All such a class would have is a bunch of public
fields and perhaps a constructor. I agree, no real need for properties
there.
But other than that degenerate class example, in what case is it true
that "some internal data of an object MUST be exposed"?
Pete