Menu

Java 5 rules: Unnecessary casts/Iterators

2006-08-04
2012-10-07
  • dexter riley

    dexter riley - 2006-08-04

    Hello! I was wondering if anyone has been writing rules to take advantage of the new Java 5 types and loop syntaxes? For example, I would like a rule to test for unnecessary casts when using typed collections:
    List<Double> list = new ArrayList<Double>();
    ...
    Double d = (Double) list.get(0); //The cast is unnecessary on this typed array.

    Similarly, I'd like to find Iterators that are only used to iterate through a collection, so I can replace them with the simpler Java 5 syntax:

    List<Double> list = new ArrayList<Double>();
    double sum;
    ...
    Iterator<Double> iter = list.iterator();
    while (iter.hasNext()){
    Double d = iter.next();
    sum += d;
    }

    //could be replaced with:
    for (Double d: list)
    sum += d;

    I've downloaded the Eclipse PMD plugin, and will try my hand at making rules, but if anyone has made these rules already, it would be a big time saver for me.
    Thanks for all your help!
    -Ed

     
    • Allan Caplan

      Allan Caplan - 2006-08-25

      After toying with this rule I found it's too simplistic.

      It doesn't see the difference between (Double)list.get and (List)list.clone() (for example)

      I think I'll have to expand it a bit to map classes to method names. Does that make sense?

       
    • Tom Copeland

      Tom Copeland - 2006-08-24

      Hi Ed -

      Hm, nope, we don't have those rules yet, although they certainly do sound useful. We do have some rules in the "migrating" rulesets, e.g.:

      http://pmd.sourceforge.net/rules/migrating.html

      But it'd be great to have more rules specifically for JDK 1.5!

      Yours,

      Tom
      Using PMD? Get the book - http://pmdapplied.com/

       
    • Allan Caplan

      Allan Caplan - 2006-08-24

      Dexter

      I'd started a rule like this - but since we have 0 Java 5 code at work, 0 Java 5 code in PMD I've been procrastinating in checking the code in.

      I just checked the rule in as net.sourceforge.pmd.rules.migration.UnnecessaryCast. It's not in any ruleset or anything, if you want, give it a go and let me know how it fares.

      I'll try and test it a bit more the next few days and see if I can't fully commit it to cvs by the weekend.

       

Log in to post a comment.