Suppose the following class structure with a base class BC and 2 derived classes DC_A and DC_B; In addition, there is an XY class with the goo () method with a parameter of type BC and other methods
// base class public class BC { public virtual void foo(); } // derived class A public class DC_A : BC { public override void foo() {} } // derived class B public class DC_B : BC { public override void foo() {} } public class XY { public void goo(BC o) { // perfectly fine using polymorphism; no Ifs' no casting, OOP at its best ;-) o.foo(); // but what to do here? if ( (o as DC_A) != null ) { doX(o as DC_A); } else if ((o as DC_B) != null) { doY(o as DC_B); } } private void doX(DC_A o) {} private void doY(DC_B o) {} }
Does it go around value objects using polymorphism, bad practice? 'a visitor template is offered;
The problem of the If cascade and casting is moved (not excluded) to the abstract base class.
Are there any better solutions to avoid if completely?
For me there is no way (in this example) to move functionality from doX / doY to the DC_A / DC_B class
Your advice is greatly appreciated.
Edit: The basis of this question is a C # / WinForms application with a form for managing a "test rule" consisting of differenct subsections, such as TestSpec, with a set of measurement types, test limits, etc. (My classes DC_A, DC_B) from EntityBase (= BC above) The form sends an event to the controller that changed the entity; simplified PropertyChanged (EntityBase o) The controller calls the corresponding method in the model class (the goo method in the XY class above), which is now responsible for executing business logic that not only stores the changed entity verification limit, but also, for example, creating a new limit verification object verification, increase verification specification specifications, etc. Maybe this way the general approach to a method like PropertiesChanged (EntityBase o) should be changed to more detailed events from the form and the specific event handler in the controller and model class for processing "TestLimitChanged", etc.
But this special case led me to the more general or "philosophical" question of polymorphism in general :-)
source share