N
Noah Roberts
True, but the OP did not like that approach, and was asking for an
alternative. This alternative replaces dynamic_cast followed by a method
call with only the method call. But doing so violates some kind of an
utopian design goal, apparently, so we're told it's no good because of that.
See, because -- according to our learned mentors -- some lofty design
principle gets violated, we shouldn't use it. Never mind that the result is
cleaner, more readable code. We can't use it. It's not ideologically pure.
The problem I see with your mentality is that you stopped looking for
cleaner alternatives.
I've seen code like you suggest people do here and it is NOT cleaner nor
more readable. When it comes time to add some new class you have to
track down each and every part of the monolythic monstrosity you're
inheriting from and tell if it's got a reasonable default or will throw.
You might claim this to be a "junior developer" problem but in fact it
costs hours of time for anyone that has to deal with such ugliness.
Further, you have to check ALL client code that attempts to make calls
to the functions you have no reasonable definition for to make sure they
do the appropriate checking. They'd better be checking their types
before making calls (which sort of negates the entire point you're
saying this design has) and not making those calls when the type is
wrong. If they do not then you need to come up with some "reasonable"
definition when you don't have one or hope they're handling the
exception (which you claim in not necessary).
It's a horrible, horrible practice that may get the job done for you,
but when people have to maintain such garbage it costs hours and hours
in extra development time and debugging effort. I ton and a half of
copy/paste code would be better.
But, the really fascinating thing here is that you just stopped at
seeing one of two alternatives: dynamic_cast everywhere or monolythic
God objects. Point of fact is that there are many possible ways around
these problems. If you just pay attention to your principles instead of
tossing them out at the earliest inconvenience you just might find
youself coming up with intelligent and innovative solutions rather than
writing trash code.