OO inheritance question
Consider the following 2 methods:
class A{
void Method1(){
if(!something) return;
DoX();
DoY();
DoZ();
}
class B{
void Method2(){
if(!something) return;
DoX();
DoY();
DoP();
}
}
obviously a superclass could be written to avoid dry principle:
class Super{
virtual void Method(){
if(!something) return; //problem...
DoX();
DoY();
}
}
class A:Super{
override void Method(){
inherited Method();
DoZ();
}
}
class B:Super{
override void Method(){
inherited Method();
DoP();
}
}
The problem is the !something check where it would run out in the first example whereas in the second, it will run out of the super class's method, but do either DoZ() or DoP() in the derived class;
My question: What is the best way to solve this kind of problem? The one that comes to my hand is making开发者_如何转开发 the super class's method a function that returns bool
virtual bool Method(){ if(!something) return false;}
override bool Method(){ if(!inherited Method()) return;}
is this the best workaround?
How about:
class Super {
void Method() {
if (!something) return;
DoX();
DoY();
DoThingy();
}
abstract void DoThingy();
}
class A : Super {
override DoThingy() {
DoZ();
}
}
class B : Super {
override DoThingy() {
DoP();
}
}
Why not declaring another virtual method for DoP or Doz, you can wrap them if you want to keep them public with their respective names.
Like superclass :
virtual void wrapping(){};
Then each child :
void wrapping() { DoP(); }
void wrapping() { DoZ(); }
Don't know if I've been clear.
Another option: Keep the checks in the derived methods. Maybe a derived class might need a slightly different condition?
class Super{
virtual void Method(){
DoX();
DoY();
}
}
class A:Super{
override void Method(){
if(!something) return;
inherited Method();
DoZ();
}
}
class B:Super{
override void Method(){
if(!something) return;
inherited Method();
DoP();
}
}
精彩评论