5

Eclipse has a java compiler setting called "field declaration hides another field or variable" that can be set to warning/error.

How important is this warning in your opinion?

What is a good standard way to handle this problem?

Code example of where this happens:

public class Test {
   private String caption = null;

   public Test(String caption) { // here
     this.caption = caption;
   }
}

I've seen solutions where the field is renamed, i.e "fCaption", but that would cause the automatic getters/setters that can be genereated to have odd names (getfCaption()). Not unreadable, but ugly...

Edit: Oh yea, there is the possibility to rename the method signature Test(String caption_) or something similar, but that would end up in the javadoc looking weird.

jmj
  • 237,923
  • 42
  • 401
  • 438
Fredrik
  • 10,626
  • 6
  • 45
  • 81

3 Answers3

11

This is a very useful option in my opinion and should be enabled to show a compiler warning. There is an option (in my version at least Eclipse 3.5.2, Java EE feature 1.2.2) to further enable/disable it within constructors and getters/setters to prevent false positives.

eclipse compiler settings

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • Agreed, name shadowing can cause subtle errors, especially if you aren't using the this keyword to prefix any class variables. However, it does seem silly for constructors and setters/getters – Martijn Verburg Nov 08 '10 at 11:08
  • However: Not doing name shadowing can cause subtle errors too. Just the other way round, like having a method access a field rather than its parameter, if people apply conventions that a parameters have a _p suffix, but then forget this in their implementation. – zedoo Sep 04 '13 at 13:57
1

I'd say that you just disable this warning - it seems no use in your convention. And no wonder it is ignored by default.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Its a setting that is disabled by default in eclipse. In preferences, Java - compiler - errors/warnings, under "name shadowing and conflicts" – Fredrik Nov 08 '10 at 10:23
1

I keep these set to "Error". If a class and its parent both have a field of the same name I don't want to lose any of my time trying to figure out why I seem to be assigning a value to the field yet it never seems to change!

Evvo
  • 481
  • 5
  • 8