Here is a very simple question, which I'm still very uneasy about:
Why is it widely accepted now for a class to return a reference to its private member through an accessor method? Doesn't this totally break the encapsulation principle? If this is OK, then why not just make the member public!?
public class EncapsulationViolator
{
private object abuseMe;
public object AbuseMe
{
get { return abuseMe; }
}
}
Edit The case I was considering is this
EncapsulationViolator ev = new EncapsulationViolator();
object o = ev.AbuseMe;
o.SetValue(newValue);
Now ev's state has change through transitivity because its member abuseMe's state has changed.
In the context of DDD, this is not OK if the object is an Aggregate Root. I quote
Allow external objects to hold references to the root only. Transient references to internal members can be passed out for use within a single operation only. Because the root controls access, it cannot be blindsided by changes to the internals.
[Domain-Driven Design, Eric Evans]
... setters schmetters ...
return
is fired, that is basically a public field but where people need to do something before set/get. Also getters and setters are widely used in java too. – Stimson