1

In absence of this pattern, downcasting is needed in the derived classes. My question is does this pattern solve only the problem of downcasting? And why is downcasting bad compared to the alternative offered by Intelligent Childrean Design Pattern?

1

1 Answer 1

3

My question is does this pattern solve only the problem of downcasting?

Yes. It's a non-issue in dynamically-typed languages. It's specifically oriented around issues that arise in statically-typed languages with relationships that want to form between dual hierarchies, and specifically to avoid the need for a downcast.

And why is downcasting bad compared to the alternative offered by Intelligent Childrean Design Pattern?

There's lot of reasons why downcasting is kind of frowned upon. For a start, it kind of x-rays the type system (as is the general case with any form of explicit cast). Providing a virtual method in its place might seem like a loophole but it does establish a formal interface that's far less prone to be misused than an explicit, low-level cast reinterpreting bits and bytes. In a rare event, a downcast might be the right tool for the job, but it's a heavy-handed tool and when there's a safer alternative, it's typically better.

With dynamic_casts you get back some safety, but with the need for RTTI (which is sometimes not always a luxury available in some tight contexts). And it's still not working with the constrained kind of public interface available for a type, but rather "around" it (ex: there's no strong compile-time enforcement of what types are available as a legit target type to cast a source type). It throws exceptions for references and returns null for pointers which can be kind of trippy behavior.

With a virtual method, you can use that statically-typed language and compiler and make it work for you, spotting more human errors in the process. You can also add instrumentation and whatever you like to a virtual method, whereas you're kind of helpless with a cast.

Mostly it's just safer to make it an explicit part of an interface, and also a little more clear as to what legitimate behavior is provided by a data type (or more appropriately, interface). Some of this is "aesthetic", but there are some definite benefits to avoiding the downcast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.