Pregunta

In the company I work for, I keep seeing IManager interfaces being converted into their real types and lots of "instanceof / TypeOf" if statement checks.

For example:

IManager manager // passed to method as a parameter

if (manager.GetType() == typeof(CustomerManager)) {
    customerManager = (CustomerManager) manager;
    customers = customerManager.GetCustomers();
    groupId = customerManager.GetCustomerGroupID(); 
    // etc...
}

I've been reading Liskov Substitution Principle and it states that "Subtypes must be substitutable for their base type". This seems to violate this.

The sub-types have their own very specific functions and I'm not sure on how to solve this. This is a problem I see happen a lot when I myself am developing. I find it hard to avoid and I think I need to change how I treat interfaces.

Does anyone have any SE advice to avoiding common problems like this?

¿Fue útil?

Solución

If you're passing interfaces around to places that can't get their work done with only the functions in the interfaces, then you shouldn't be using those interfaces in the first place.

Often such code is the result of people slavishly following the principle "Code to interfaces, not to implementations", without understanding the even more important principle "If you use instanceof, refactoring to use interfaces is pointless".

An interface is useful if multiple concrete classes are interchangable for some particular purpose. If they aren't, well, there's no shame in that. Perhaps you can group your functionality in a different way so that some things can be abstracted away. But mandating the use of interfaces in situations where they don't work is a red flag; it means that someone understands important principles only half-way.

Licenciado bajo: CC-BY-SA con atribución
scroll top