Menu

Parameter name != field name

2002-07-18
2012-10-07
  • Tom Copeland

    Tom Copeland - 2002-07-18

    I had a field:

    private Bar mybar;

    and a mutator method:

    public void setBar(Bar myBar) {
    this.mybar = mybar;
    }

    See the problem?  No compile error, no runtime error... but calling set(aBar) never sets the field value!  It was even worse because I had a constructor that accepted a Bar and set it correctly.

    This heinousness took me a couple hours to track down and was incredibly frustrating.  In retrospect, a good unit test would have caught this, but that was before I had met JUnit.

    A rule which would help catch this sort of thing is the "UnusedFormalParameter" rule which we've already discussed here:

    http://sourceforge.net/forum/forum.php?thread_id=699778&forum_id=188194

    I'll add it as a feature request.

    Tom

     
    • Nobody/Anonymous

      ouch! Took me a while to spot that.

      After renaming variables en mass, I've sometimes been left with things like
      myBar = myBar
      in the setter method, which always seems to throw NullPointerExceptions far enough away to be confusing...

      (but I imagine PMD already covers these ;-)

       
    • Tom Copeland

      Tom Copeland - 2002-09-03

      PMD actually doesn't catch this yet... more interesting things keep coming up. 

      Now that I look at it, the UnusedFormalParameter thing doesn't catch this problem.  Bummer.

      Man, that was frustrating though.  Blah.

      Tom

       
    • Scott Oster

      Scott Oster - 2003-03-28

      Eclipse catches that.

       

Log in to post a comment.