Polymorphism – Is Down-Casting Always Bad?

designpolymorphism

At my company, we have many different "services" that work in parallel and send messages to each other using a common messaging system. All message objects are derived from a common generic object we defined for messaging. When any service receives a message, the first thing it must do is downcast the object to the derived type so that it can extract the data needed.

I have read all over the internet that you should not have to downcast a base object pointer to a derived object pointer and that having to do this is often a sign of bad design. I agree with this sentiment for most cases. And I can imagine different designs for the generic message object that wouldn't necessitate down-casting. But I don't see any big reason to handle this situation differently.

So my overall question is: Is down-casting always a bad thing? Are there situations in which down-casting is necessary or acceptable?

Best Answer

Downcasting a pointer vs making a generic payload into a specific object are two different things.

The common messaging system API should have a set of functions for returning the exact object you want so that you aren't constantly downcast in your application code (which is more error-prone).

You're basically talking about passing around objects using XML or JSON or some other data interchange format. Talking about downcasting is unnecessary because it should already be handled by the common messaging system API since you know exactly what sorts of objects are being passed around.

I'm assuming the system API looks like this:

GeneralObject* getObject(Message *message);

It should look like this:

GeneralObject* _getObject(Message *message); // the _ is just to indicate this is a private function that shouldn't be used outside of this module

// these raise exceptions if the object doesn't exist or return null or whatever
Person* getPerson(Message *message);
Place* getPlace(Message *message);

Never in your code will you use the generic function that returns the base class, you'll always use the code that returns the derived classes and let the API handle or raise errors if it can't downcast.

Downcasting in this case is basically failing to parse or de-serialize an object.

Google's protobuf library has an example of what I'm talking about