I wrote a piece of code at my job sometime ago. While writting the code I wrote few interfaces who would allow me to add more flexibility and at that time I was also trying to understand OOP concept more deeper. So in the interface I wrote I have a method signature similar to this :
void Add(ImyBase objToAdd)
And then I have few class implementing this interface. But what is bothering me is that I find myself doing this kind of thing pretty often in this Add
method
public void Add(ImyBase objToAdd)
{
if(!(objToAdd is ImyBaseDeviation))
throw new ArgumentException("blablabla");
//do stuff
}
At the time it was a smell to me but I didn't really bothered with it simply because I'm solo on this projet and this piece of code is only used within my compagny and there only 2 IT guys in there (me + some one else) and this is not near to change. Anyway I recently came back to that piece of code and from my previous reading (actually more than that but this one is pretty similar) it now actually really look bad to me and I'm trying to figure out the best way to improve this piece of code.
I don't like the code as it stand now because the interface allow more than the concrete type generally allow so basically the concret implementation doesn't respect the contract given by the interface.
I tough of a few solutions
First simply delete the Add
method from the interface since anyway calling Add
have a high chance to throw an exception. So to call Add
you need the concret type anyway. So here the object would still have a Add
method but with the accepted type as a parameter.
Secondly add a method who would look something like this in the interface
bool IsValidToAdd(ImyBase objToTest)
But that doesn't satisfy me.
So I'm seeking advise from more advance people like you to help me to figure out what would be the best way to implement this so it stay the cleanest possible.
Sorry I'm not a native anglophone so if my question need editing or grammar fixing please go ahead. Thank you
ImyBaseDeviation
instead of aImyBase
. Are there other implementations ofImyBase
that can't be converted to the derived class? Are there things on the derived interface that can be pulled up to the parent?ImyBase
generally implementImyBase
and some other interface(s)void Add(ImyBase)
method accept specificallyImyBaseDeviation
, or do they each accept different concrete types?