January 28, 2003
Easy error to miss

Spent some time today debugging an issue that turned out to be a very simple error which could be easily avoided.

Can you spot the bug in this code?

public class Buggy {

   private String value = null;
   
   public Buggy(String value) {
      value = value;
   }
  
   public String getValue() {
      String rval = value;
      return rval;
   }

}

When getValue() is called it returns a null object.. why?

value = value;

Should be:

this.value = value;

Easy to miss.. pain to debug.

Better yet.. Instead of using this.whatever just name the variables differently.. it makes for easier to read, less confusing code.


Posted January 28, 2003 02:20 PM in Java
TrackBack URL for this entry: http://www.unix-girl.com/mt/mt-tb.cgi/514
Comments
On January 28, 2003 06:13 PM garrett added:

just out of curiosity, why does getValue() use a temporary variable instead of just being 'return value;' ?

#
On January 28, 2003 06:42 PM kasia added:

Oh, it's just a habit I have.. it makes debugging easier at times. Kind of second nature for me to do it this way these days.

#
On January 29, 2003 01:18 PM Andre Restivo added:


public Buggy(String value) {
setValue(value);
}


This is how I like to avoid this kind of errors.

#
On January 29, 2003 01:21 PM kasia added:

.. but setValue() has to be a method as well and inside that method.. guess what happens :)

I used a constructor as an example becuase the code I ran into was structured like this.. but it's the same exact error you may see in a setValue method.

#
On January 30, 2003 03:28 AM Andre Restivo added:

I let all my getters and setters be autogenerated by Eclipse so I normally don't have any problems with those.

And Eclipse latest build(M4) already warns you of unconsequent code like assigning a variable to itself.

#
On March 4, 2003 06:33 AM Gwyn Evans added:

obMuse: If you post a comment to a month-old blog, does anyone see it? :-)

IntelliJ 'highlights' (actually, grey's) the "value = value", showing it's a NoOp (and also puts "Silly assignment" in the status bar!

Also shows fields as different from variables/paramaters in code formatting by default

#
On April 26, 2003 04:31 AM Eddy Young added:

Funny, in C# namespaces are funny. You do something like this:

class MyClass {
private String id;

public MyClass(String id) {
this.id = id;
}
}

and it will fail. Doh!

I love Java!

#
Trackbacks