I’m working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.
Right now In my code I’m forced to do something like this:
if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet.Feet feet = new Feet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet.Feet feet = new Feet(); feet.WashFeet(); }
This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically?
The namespace isn’t the problem – it’s simply that the 2 classes aren’t related, so there’s no inheritance chain that you can use for polymorphism.
You’ll need to look at something like duck typing, or an adapter pattern, or building your own proxy classes to get yourself to a common interface. For small numbers of implementations, I’ve gotten away with just building a single adapter class that delegates to whatever non-null instance it has:
For larger cases, you’d be better off with a separate PigFeetAdapter and HorseFeetAdapter that both implement IFeet, along with a FeetAdapterFactory to create them – but the concept is the same as I show above.