Re: What is "evil" about casting?

From: Scott Ellsworth (scott_at_alodar.com)
Date: 09/30/04


Date: Wed, 29 Sep 2004 21:52:20 -0700

In article <20040929160644123+0200@news.text.chello.nl>,
 Jonck <jonck@vanderkogel.net> wrote:

> Hi all,
> Today I was reading through some discussions about the new functionality
> in Java 1.5 and there I read more than once that casting was considered
> "evil" and that generics would solve all this (or not, as others argued).

They cut out some expressiveness. Before 1.5, the Collections API used
only generic Objects. Programmers thus had no easy way to know what
they are going to get back out. They then must cast, and if they get it
wrong, or if an infrequently used code path puts something they do not
expect into the collection. they get a class cast exception.

> 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...

They work, but they require the developer to know the type of object he
or she is trying to get out of the Collection. As a developer, I would
rather state that the collection vends/accepts Actions, or Forms, or
whatever, than make the end user guess.

Scott



Relevant Pages

  • seeking advice on building jdk15
    ... I discovered I needed Java first. ... warning: non-varargs call of varargs method with inexact argument type ... cast to java.lang.Objectfor a non-varargs call and to suppress this ... http://mail.yahoo.com Java HotSpotClient VM warning: Can't detect initial thread stack location ...
    (freebsd-questions)
  • Re: InvalidCastException
    ... > possible to typecast for e.g: ... could say what the actual type was, like it does in Java. ... System.InvalidCastException: ...
    (microsoft.public.dotnet.framework.clr)
  • Re: What is "evil" about casting?
    ... But why would you cast if you didn't need to? ... > in Java 1.5 and there I read more than once that casting was considered ... > Thanks very much, Jonck ...
    (comp.lang.java.programmer)
  • Re: Static vs. Dynamic typing (big advantage or not)---WAS: c.programming: OOP and memory management
    ... In the first case static typing ... you need a cast. ... there's a lot of java code out there (some of mine ... and the java library and pragmatics encourages the novice to do so. ...
    (comp.programming)
  • Re: Differences between C++ and Java
    ... >> "In Java, garbage collection of unreferenced objects is automatic. ... >> provide third party libraries that work just as well, ... but that control can be overridden with a cast. ... To be fair many of the comments were nit picks, ...
    (comp.lang.java.programmer)