Re: Why RTTI is considered as a bad design?
On Monday, August 6, 2012 9:43:24 PM UTC+3, Noah Roberts wrote:
On Wednesday, August 1, 2012 1:23:58 AM UTC-7, (unknown) wrote:
Stroustrup has written in his book TC++PL that the most common case of =
usage RTTI technique is with switch instruction, when one want to decide wh=
at code should be executed basing on what is a "real" type of a passed obje=
ct. There is given an example in which an object of shape class was passed=
to the function and different actions were executed depending on that whet=
her a shape is circle, square, triangle, etc. He has written that such cons=
truction is a sign that one should replace the switch-case sequence by virt=
ual functions.
See Liskov Substitution Principle: http://en.wikipedia.org/wiki/Liskov_su=
bstitution_principle
If your code looks like so:
if (type_1 * ptr = dynamic_cast<type_1*>(somePtr))
...
else if (type_2 * ptr = dynamic_cast<type_2*>(somePtr))
...
You're violating the principle. What this means is that all places that =
look like this will have to be searched for, found, and modified if you add=
a new type behind the abstraction. This can quite rapidly explode into a =
maintenance nightmare and cause bugs that are difficult and/or impossible t=
o find.
Usually i see dynamic_cast<>() more used for cross-casting rather than down=
-casting. I bring an example. A specific Door passed to SomeDoer::open(Door=
*) may have Lockable interface or not. To have all Doors Lockable by defaul=
t would deviate from sane design since most doors can not be locked. Succes=
s of unlocking may depend of availability of Keys or LockPicks or whatever =
for this SomeDoer so open() forwards these problems to SomeDoer::unlock(Lo=
ckable*):
bool SomeDoer::open( Door* door ) const
{
// we might need to unlock first on some cases
Lockable* lock = dynamic_cast<Lockable*>(door);
if ( lock != NULL && lock->isLocked() && !unlock( lock ) )
{
return false;
}
return door->open();
}
Can you tell how such a situation can be resolved as elegantly without RTTI=
(or some self-made substitution of RTTI)?