One often reads how it’s worth designing your code to avoid needing to make casts, and how finding yourself needing to cast might suggest that there is a better implementation available. I’m trying to achieve this holy grail of “cast-free code” in the implementation of a virtual world engine, where many objects have a wide variety of interfaces, acting as mediators and data (and sometimes as both) of many different forms. As one answer in a similar question mentions (Linkage), the aim is to always have a reference/pointer of the correct type at the required location rather than trying to dig one out from a large range of candidate objects.
My latest stab at managing this large issue involves registration of objects with their mediators which has some nice advantages in terms granularity of control (you can runtime configure many to many mappings between mediators and their targets).
There are some problems as well… The biggest I’m looking at at the moment is the de-registration of targets from mediators. In order to keep track of who’s using what without having to poll every possible mediator the program needs to store yet more data on what links have been created. On the one hand it would be possible for mediators to disconnect themselves simply by checking if their targets are expired (i’m using smart pointers and weak pointers for everything so this is not difficult), however this simply handles the expiry of objects and does not establish a framework for meaningful reconfiguration of behaviour.
When looked at from far away, it’s just another case of software boiling down to the trade-off between time and memory. Store more data to do less computation.
I want to ask what your thoughts are about structuring programs to avoid dynamic casts, and if you could share any strategies / patterns that are effective in these situations.
This is a fundamentally flawed proposition.
dynamic_castexists for a reason. Trying to aim for cast-less code is just naive- casts serve a purpose. Sure, it might be the best thing to reduce them wherever you can, but that’s very different from trying to ban them. Code withoutdynamic_castisn’t some kind of holy grail- either it doesn’t need it, in which case it’s just code, or it does need it, in which case it’s suboptimal code.However, to stay a little more on-topic, I personally find that just by not spreading inheritance around like it’s the Plague and I’m trying to cause the Apocalypse, then the need for casting is limited- templates are a miracle here.