Assume:
- There is some module whose interface is
IA
. - There is some module
B
, that takes in a parameter an instance ofIA
, and whose behavior depends upon the type of thatIA
,
meaning (pseudo code, no specific language)
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
if(type(this.ia)==A1){
print("A1");
}
if(type(this.ia)==A2){
print("A2");
}
}
}
I realize I could add some public method foo
to ia
, and thus the code would simplify to
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
this.ia.foo();
}
}
My question is twofold:
-
What is the correct design to achieve this if I (for some reason) can't change
IA
, meaning, I can't addfoo()
? -
What is the correct (scalable) design if I am allowed to change
IA
but the same problem now repeats forA1
,A2
, and so on, meaning
the final desired behavior is
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
if(type(this.ia)==A1){
if(type(this.ia.iz)==Z1){
print("A1Z1");
print("unique treatment");
}
if(type(this.ia.iz)==Z2){
print("A1Z2");
print("special treatment");
}
}
if(type(this.ia)==A2){
if(type(this.ia.iz)==Z1){
print("Z1A2");
print("one of a kind treatment");
}
if(type(this.ia.iz)==Z2){
print("Z2A2");
print("Wow treatment");
}
}
}
}
and can repeat more times.
Please notice Z1 and Z1 are the same for A1 and A2!. And again, the same can go on, IZ
can contain IX
of several types, with unique behaviors
I wonder if case 2 is at all separate of modular, in the sense that, the behavior is unique for every type-combination, and no behavior can really be extracted to a more abstract level.
I still don't like the type checking, and wonder if there is something that can be done which looks better.
Aucun commentaire:
Enregistrer un commentaire