Interfaces and Casting in Object-Oriented Design

interfacesobject-oriented-designpatterns-and-practices

I recently started working with a shiny new version of a codebase that uses interfaces all over for… basically everything. I think all of our concrete classes implement interfaces.

The problem I've noticed is that the project doesn't appear to code to the interface! Items passed using interfaces are consistently casted to specific types. This feels like a bad idea but I can't seem to articulate clearly why this is wrong. It seems like using interfaces only to cast regularly is losing the benefits of both interfaces and a strongly-typed language in the first place.

To rephrase as a question: Is this a good practice? Why?

Edit: This is not a duplicate of What is the point of having every service class have an interface? as my question relates specifically to casting from an interface to a dozen or more concrete classes that implements that interface.

Best Answer

This is bad practice no matter you slice it.

If the code nominally expects an interface but then casts the parameter to a concrete type in order to use methods more specific than the interface, then it is effectively lying to itself. Presumably had to follow a well-intentioned guideline such as "All parameter types musty be interfaces" and followed its letter but not spirit, probably for lack of understanding.

If the values are cast and then used only via functionality of the interface anyway, that's even weirder. It looks as if someone doesn't understand the concept of interfaces at all and thinks they can only use (or only understand the use of) objects when they know their concrete class.

Both are red flags, although the second case is a bigger red flag.

Related Topic