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.
TrackBack URL for this entry: http://www.unix-girl.com/mt/mt-tb.cgi/514
just out of curiosity, why does getValue() use a temporary variable instead of just being 'return value;' ?
#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.
#.. 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.
#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.
#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
#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!
#