On 07-Oct-1999, Michael T. Richter <[EMAIL PROTECTED]> wrote:
> At 05:12 PM 10/7/99 , you wrote:
> > Sorry that I really can't explain well why I think that this concept
> > does not fit into Haskell. I must have heard that such "typecase"
> > is most often a bad design.
> 
> In most situations, type-casting is a symptom of bad design.  The only C++
> situation, for example, where some form of casting from a base class to a
> derived class isn't symptomatic of a bad design is the situation of the
> so-called "virtual constructor" -- building objects from a persistent
> store, say.  In most to all other situations, use of dynamic_cast or
> equivalent is just plain sucky design.

I have to say I disagree with that.

Firstly, the "virtual constructor" idiom, at least as this term is
commonly used, e.g. in the C++ FAQ list
<http://www.cerfnet.com/~mpcline/C++-FAQs-Lite/virtual-functions.html#[20.5]>,
does not involve any use of dynamic cast.  Nor should building objects
from a persistent store necessarily require any dynamic casts.

Secondly, there are many possible uses of `dynamic_cast' other than for
the "virtual constructor" idiom or for building objects from a
persistant store which would not constitute bad design in my book.
Among other things, `dynamic_cast' can be used to improve efficiency by
optionally taking advantage of operations which might not be present.
For example, you could use a `dynamic_cast' to check if some iostream
is a file, and if so, you can obtain the file descriptor and then try
using the OS's memory mapping facilities rather than reading it in byte
by byte.

Likewise `dynamic_cast' can also be used to improve properties other
than efficiency, for example user-friendliness.  Again the technique
involves taking advantages of certain operations, which might not be
present in all objects, in those cases where the operations _are_ present.
But the point is that this technique is not limited to improving
just efficiency.

Templates with traits classes are an alternative solution to the same
kind of problems.  That solution is becoming very popular in C++.
But it only works for homogenous collections or other situations where
the type is known at link time, and there are efficiency considerations
and modularity considerations that result from template code expansion
(templates in DLLs or shared libraries pose particular problems).
For heterogenous collections or other situations where the type will
only be known at runtime, if you want to apply these kinds of techniques,
then it is eminently reasonable to use `dynamic_cast'.

Note that `catch' in C++ involves the equivalent of `dynamic_cast'...
do you consider code using `catch' to be "just plain sucky design"?

-- 
Fergus Henderson <[EMAIL PROTECTED]>  |  "I have always known that the pursuit
WWW: <http://www.cs.mu.oz.au/~fjh>  |  of excellence is a lethal habit"
PGP: finger [EMAIL PROTECTED]        |     -- the last words of T. S. Garp.



Reply via email to