Constructor-choke variable encapsulation.
I have been chewing over the idea of using constructors which take a single complex object roughly equivalent to a "transfer object" as a means to achieve a sort of flexible encapsulation, and I was wondering whether people would think it is a good idea.
Example.
publicclass Bomb{
privateint clicks;// the number of times the button has to be pushed to get an effect
privateboolean dud;// whether the bomb is a dud or not
public Bomb(int clicks){
this.clicks = clicks;
this.dud =new Random().nextBoolean();
}
publicvoid pushButton(){
clicks = clicks - 1;
if (clicks > 0){
System.out.println("Click.");
}
elseif (dud){
System.out.println("Ffffuuut.");
}
else{
System.out.println("BOOOM!!!!");
}
}
}
The bomb has a button that is pressed using pushButton(). Once the button has been pressed the predetermined number of times, the bomb either blows up or goes "ffffffuuut!!" (turns out to be a dud). Yes, this is a stupid example.
Notice that all the values are encapsulated totally - no getters and no setters. Now say that we decide we want to get to them... sometimes... but not most of the time. For example, we might want to be able to persist the bomb but would prefer not to open it up to do so.
The constructor-choke variable encapsulation idea goes like this.
publicclass BombData{// The equivalent of a DTO
publicint clicks;
publicboolean dud;
}
publicclass Bomb{
private BombData data;
public Bomb(BombData data){
this.data = data;
}
publicvoid pushButton(){
data.clicks = data.clicks - 1;
if (data.clicks > 0){
System.out.println("Click.");
}
elseif (dud){
System.out.println("Ffffuuut.");
}
else{
System.out.println("BOOOM!!!!");
}
}
}
Considered as an instantiated object, the Bomb is no less encapsulated than it was before. There are no methods for accessing or mutating its members. However, the code responsible for instantiating the Bomb can keep a reference to the BombData hanging around for persistence purposes or whatever.
Basically the idea is that the object has a variable level of encapsulation determined by the code which instantiates it. The instantiating code serves a sort of access control role in this purpose, as it can pass references to the BombData to other classes or not, as it pleases.
In our example, in which we want to persist the Bomb, the class responsible for instantiating bombs could be a DAO (which returns actual business object Bombs and NOT BombData transfer objects). All new Bombs must be instantiated using the DAO, which just keeps track of which BombData objects go to which Bombs for when data manipulation requests are made.
Cool idea? Or am I a crackpot? Or is this the so-and-so pattern that I would already have known about if I had read such-and-such a book?
Drake

