I came across with an article about proper way of encapsulation. It really got my attention and solved some of my prior confusion. Then I thought about it's implementation. There must not be any property or ( getter method ) that expose any common reference. In order to achieve this, each inner field must be constructed freshly. But it is not always possible to know construction logic or even find a proper constructor. So I thought that deep cloning might be used for this purpose.
There are some ways to achieve deep cloning ( one way, some other ways ).
My questions are:
1- Does my approach make sense or is it completely nonsense?
2- Are deep cloning operations dangerous or uncertain? If yes, would it be proper to use such dynamic ( or uncertain) behaviors for such a core module ( on business models getters )?
PS: Even if Java is used in the article, I ask questions for .NET or C#. I am not really sure but Java might have different deep cloning ability. I don't feel comfortable with Java.
Java and C# are close enough where the implications are the same.
To me, this article would be better left off unpublished, as the only thing it serves is to confuse people and send them down paths like "I need to deep clone all my exposed objects in an interface so they can't be changed."
This is not the essence of encapsulation. The essence of encapsulation is such that - for example - the calculation for an age, given a public birthdate, is not exposed:
class foo {
public DateTime Birthdate { get;set;}
public int Age { get { return (DateTime.Now - Birthdate).ToYears(); } }
}
Thus, the "inner workings" of how an age is calculated is not exposed. Or rather, that logic is encapsulated
Now, there may be times where you really do want to make sure an exposed object is entirely immutable, but on the general, that's rubbish. (deep cloning is no simple feat, at all, and this article doesn't give enough insight to the more broad scope of the problem to do anyone any good).
Drop the idea of deep cloning everything that gets exposed, and just write your classes with the logic contained within, and you'll have encapsulation well enough for the vast majority of purposes.
OOP concepts should always be taken with a very healthy dose of pragmatism.