Archive for September, 2008

Getting Around Dynamic Casting To Achieve Better Design And Performance

Using dynamic casts to determine an execution path in your code is not the best to write your logic.

I realized this fact while looking at Google’s style guide for C++

Do not use RTTI, except in unit-tests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type.

Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself.

If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system.

If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags.

That was an eye-opener to me. I didn’t know what double-dispatch is all about. Turns out that it’s the heart of the Visitor’s Pattern (although the example at dofactory.com is not ideal because they do not provide overloads for the visit() function and they cast all types to the base).

 

Double-Dispatch is the ability to dynamically select a method according to the run-time type of the caller (single dispatch) and the run-time type of the argument as well.

 

To close out, remember before you use dynamic casting in your code to think if there is a better way to achieve the same results using function overloads, virtual functions or double dispatch.