Programming to an interface...... what if I want to use a method from the concrete class not defined in the interface?

So if you're following the principle to it's full, non-waivering standard - you just wouldn't. You would have an interface IMap, an interface ITreeMap that extends it and a concrete implementation (perhaps ItsReallyATreeMap) - anything that requires the additional functions from ITreeMap will expect to be given one, and not a IMap.

But not everybody lives in a painful world of enterprise software. So depending on your situation you might have a couple of options:

A) You only use the minimum common functionality. This works, but is limiting. Generally, you're not really solving the problem so much as ignoring it.

B) You do nothing if it doesn't exist. You could implement it as a mock version, for example WindowsWindow "BringToFront" makes a window come to the front, but MacWindow literally does nothing (both then extend IWindow). The downside is you're asking for things to happen that just "don't" sometimes, but you're able to get the best functionality from each specific implementation available.

C) You specifically check which implementation you have. This is a little dodgy, in that it undoes the benefits gained from polymorphism in the first place (i.e if you needed a Foo cast as a Bar, but you really needed a Foo not a Bar - you should have just kept the Foo). Different languages have different dynamic cast features for this, but you could then make a decision based on the concrete type you have.

Generally though, if you're using an interface it's because you DON'T care about how it is implemented. You should ONLY use the functions of the interface and not worry about anything else. But as we know, reality doesn't always match the perfect text-book style principles and we're not always the person who wrote the first half of the code.

/r/learnprogramming Thread