Check the class of objects
janderson
askme at me.com
Sat Jun 7 19:22:21 PDT 2008
janderson wrote:
> mael wrote:
>> Actually, this wouldn't be the right solution,
>> because the doSomething action is specific to a particular algorithm,
>> and there will be tens of such algorithms, and I don't want to clutter
>> the main class with parts of algorithms adapted to each class...
>>
>
> http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism
> http://c2.com/cgi/wiki?SwitchStatementsSmell
>
> The following is an excerpt from Scott Meyers’ new book,
> Effective C++, Third Edition: 55 Specific Ways to Improve
> Your Programs and Designs.
>
> "Effective C++, Third Edition Item 27 7
> One thing you definitely want to avoid is designs that involve cascading
> dynamic_casts, i.e., anything that looks like this:
> class Window { ... };
> ... // derived classes are defined here
> typedef std::vector<std::tr1::shared_ptr<Window> > VPW;
> VPW winPtrs;
> ...
> for (VPW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter)
> {
> if (SpecialWindow1 *psw1 =
> dynamic_cast<SpecialWindow1*>(iter->get())) { ... }
> else if (SpecialWindow2 *psw2 =
> dynamic_cast<SpecialWindow2*>(iter->get())) { ... }
> else if (SpecialWindow3 *psw3 =
> dynamic_cast<SpecialWindow3*>(iter->get())) { ... }
> ...
> }
> Such C++ generates code that’s big and slow, plus it’s brittle, because
> every time the Window class hierarchy changes, all such code has to
> be examined to see if it needs to be updated. (For example, if a new
> derived class gets added, a new conditional branch probably needs to
> be added to the above cascade.) Code that looks like this should
> almost always be replaced with"
Sorry part of that got cut off. It says something like "replaced with
virtual functions".
>
>
> I think that only becomes appropriate if you use a template or operator
> overloads to generate this so its generic, less brittle and without evil
> down casting.
>
> -Joel
More information about the Digitalmars-d-learn
mailing list