0

I have a field name which is similar to static constant

public static final String MAIL = "mail";
private String mail;

I'm getting sonar warning:

`Methods and field names should not be the same or differ only by capitalization (squid:S1845)`

Although field is instance and constant isn't a method and also static

Is it false positive sonar warning, a corner case I should suppress or is there a real issue in my code and I need to move constant outside class (or inner class)?

I found other false positive for this warning, but it was fixed, Builder pattern:

S1845 should not raise issue on builders and methods returning the field with same name

Ori Marko
  • 56,308
  • 23
  • 131
  • 233

1 Answers1

0

It wouldn't cause an issue when building your source code, so from that perspective you could suppress it, but it might generate confusion to the developer/reviewer, so it would be best to fix it (especially when working with autocomplete, although the field is private in this case...) . Maybe use a different naming pattern for local variables. Different scope would also fix this.

I found also this link where they try to describe this, although they focus mostly on methods, and the 'Compliant Solution' is in tune with the links you've shared regarding the BuilderPattern: https://rules.sonarsource.com/java/tag/confusing/RSPEC-1845

Nicolae Natea
  • 1,185
  • 9
  • 14
  • I want similar attributes, as in example mail, how should I fix it? add suffix/prefix? it seems redundant – Ori Marko Mar 30 '20 at 12:22
  • BTW in link it state same visibility *exactly the same name and visibility.* which isn't the case here – Ori Marko Mar 30 '20 at 12:25
  • Normally in c++ I would use an underscore as a suffix, or prefix the private member with m_, but as this is java, that might not be the way to go. In this case, I'd implement a separate 'enum' for the attribute names, so that in the end the scope differs, and I'd trow an error if an unimplemented attribute is requested – Nicolae Natea Mar 30 '20 at 12:33