Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing conditional chains of type checking

Tags:

c#

I stumbled across some code today that looked similar to:

  if (myObject is MyClass1) 
     myOtherObject = new MyOtherClass1(myObject);
  else if (myObject  is MyClass2) 
     myOtherObject = new MyOtherClass2(myObject);
  else if (myObject  is MyClass3)
     myOtherObject = new MyOtherClass3(myObject);
  else if (myObject  is MyClass4)
     myOtherObject = new MyOtherClass4(myObject);
  else if (myObject  is MyClass5)
     myOtherObject = new MyOtherClass5(myObject);
  else if (myObject  is MyClass6) 
     // ...

I find this somewhat difficult to maintain and would like to replace it with something less cumbersome. What are my options?

So far I've considered a table driven approach using a dictionary but I'm not sure if that's the best option.

// Not even sure this is valid syntax.
foreach (myClass in classes)
   if myObject is myClass
      new classes[myClass](myObject);

Any other ideas?

Update

Without going into to many details here is the basic structure of the classes:

MyBaseClass                              MyOtherBaseClass
  |                                        |
   -MyClass1                                -MyOtherClass1
  |                                        |
   -MyClass2                                -MyOtherClass2

MyBaseClass and its descendants are what I would consider persistent data transfer objects. They store their data in a class specific format.

The closest I can come to describing MyOtherBaseClass and its descendants would be unidirectional data mappers[PoEAA] but they mix a little business logic in as well.

The database only holds enough information to locate the objects and track their status.

like image 212
Kenneth Cochran Avatar asked Mar 04 '26 12:03

Kenneth Cochran


1 Answers

Could you consider having an abstract method generateOtherObject() in the base class for MyClass1, MyClass2, etc. which is overriden in each derived class to create a new object of the relevant type?

like image 179
Oliver Charlesworth Avatar answered Mar 06 '26 01:03

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!