Re: What is "evil" about casting?

From: Michael Borgwardt (brazil_at_brazils-animeland.de)
Date: 09/29/04


Date: Wed, 29 Sep 2004 16:31:59 +0200

Jonck wrote:
> Could someone give me a brief explenation as to what is wrong with
> casting and how generics in Java 1.5 will solve this? Personally I don't
> see what's wrong with casting, in all the books I've read on Java casts
> are used all the time...

The problem with casting is that it results in runtime exceptions.
These may occur only under very rare circumstances, so in the
worst case, a bug may stay undetected in all tests and then suddenly
manifest at the worst possible time in production and cost millions
of dollars.

Therefore, Java goes to great lengths to convert runtime exceptions
to compile-time exceptions wherever possible, partially via type checks.
An embarassing deviation from this philosophy was the Collections
framework, which required lots of casting and was impossible to use in
a typesafe way without writing lots of wrapper classes.

Generics makes Collections (and similar classes) typesafe *and* convenient
to use - you can declare a List that can contain only Strings, and
the compiler will protest if you try to put anything else into it.



Relevant Pages

  • Re: What is "evil" about casting?
    ... > in Java 1.5 and there I read more than once that casting was considered ... > Could someone give me a brief explenation as to what is wrong with ... the more robust Generics syntax. ...
    (comp.lang.java.programmer)
  • Re: Box and UnBoxing
    ... > I assume it's the same as in Java and then it's not similar to casting. ... > Boxing creates a new instance of a different class, ... Shayne Wissler ...
    (comp.object)
  • What is "evil" about casting?
    ... in Java 1.5 and there I read more than once that casting was considered ... "evil" and that generics would solve all this ...
    (comp.lang.java.programmer)
  • Re: Array Help!?!?!?...
    ... but I'm sure it can be done somehow, ... possibly by casting it to some generic type. ... Or perhaps that's the Java in ...
    (microsoft.public.word.vba.general)
  • Re: What is "evil" about casting?
    ... > in Java 1.5 and there I read more than once that casting was considered ... They then must cast, ... but they require the developer to know the type of object he ...
    (comp.lang.java.programmer)