Regarding java:S6212 : Local-Variable Type Inference (var) should be used

Hi team,

Could you please explain your reasoning behind java:S6212 and why this is now considered a codesmell?

The jira ticket and the descriptions are vague

I do not believe that this is a code smell and it is more a matter of preference. In my case, I prefer and will continue to use the type explicitly

From the style guide : Local Variable Type Inference: Style Guidelines

Using var for declarations can improve code by reducing clutter, thereby letting more important information stand out. On the other hand, applying var indiscriminately can make things worse. Used properly, var can help improve good code, making it shorter and clearer without compromising understandability.

It seems that this continues to be controversial. I wonder why you decided to take a drastic stand that this is a codesmell. Also, it seems that a good variable name needs to accompany the usage of var, otherwise, it will be more confusing that the alternative. For example, see :

        String category = relationshipJson.getJsonObject(JSON_KEY_ACCOUNT)
        var category = relationshipJson.getJsonObject(JSON_KEY_ACCOUNT)

Which one do you think that is more clear from this code? In my opinion, the one with the type is but sonar considers this a codemell and recommends it to be replaced with var

At the same time, it is true that sometimes it could help :

  B2B2CNetwork b2b2cNetwork = new B2B2CNetwork();
  var b2b2cNetwork = new B2B2CNetwork();

But again, it is very controversial and depends on the context. Adding this as a blanket codesmell is bad in my opinion

Hello @sonaruser1231

Thanks for the feedback, this is a legitimate concern.
I invite you to have a look at this topic:

Hope it clarifies the situation.

Thank you @Quentin

The thread you’re referring to is locked so I cannot add anything else.

It is strange that there you mentioned that is disabled by default because I experienced this in version 8.9.6 (build 50800) using “Sonar way”

The rule is removed from Sonar Way in version 7.1 of the Java analyzer, included in SonarQube version >= 9. In version 8.9.6 the rule is still in the default quality profile.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.