What is the point of interfaces if you still have to cast to the interface to use it?

Interfaces are good to having to avoid having access to the things that you should not have access to. Maybe you should take a look at Factory Pattern, and you will get the picture. But I’ll give you a small example.

You have a project that contains multiple types of land vehicles (truck, motorcycles, cars… etc). And all of them implement IVehicle which contains method accelerate.

You are in movement component, and you have pawn reference. You don’t know which one it is, and want to accelerate it. Then you just cast pawn to IVehicle and use method accelerate.
Before you say, but I can create base pawn that is vehicle, and they can al inherit from it, I will explain why is that bad. Vehicles can open door, lower windows… etc. Why would Movement component care about that?

So the goal is, do not give someone reference to the whole pawn, some components don’t need whole pawn, but just part of it, and this is why interfaces are good.

In C++, you can just use Cast<IMyInterface> to check if some object implements that interface, and then call needed method.

Yes, you still have to cast, but you only get the part that you need, and avoid having more than you need. It helps a lot with big projects when it comes to maintainance. This is why Interfaces should be segregated which is I in S.O.L.I.D. :slight_smile:
This, combined with CLEAN architecture is a win win situation.

4 Likes