I want to keep a dependency decoupled, but at the same time, once it's passed to the constructor, I want to allow changes only through Whatever
(in the following example) because changing the dependency from the outside would invalidate the state of the Whatever
object that depends on it. So I keep a copy instead:
class Whatever{
private Dependency d;
public constructor(Dependency d){
this.d = d.clone();
}
// ...
}
However the dependency is huge so I've decided to avoid the copy; I've removed the clone()
and made clear through documentation that once the dependency is passed to this class, it must not be modified from the outside.
Question is: is there a way to avoid the copy and at the same time maintaining proper encapsulation? And with proper encapsulation I mean either immediately error on access attempts from the outside or avoiding the possibility of the access from the outside entirely.
My guess is that I cannot. Not using the Java/C#/etc's OOP interpretation.
So I also ask, are there languages that cover such a case? How do they work?
An option I could have is the following, assuming a language doing reference counting:
class Whatever{
private Dependency d;
public constructor(Dependency d){
this.d = d.isTheOnlyReference() ? d : d.clone();
}
// ...
}
new Whatever(new Dependency()); // no clone performed
Dependency d = new Dependency();
new Whatever(d); // clone performed, as Dependency has >= 1 references