JinchaKku
JinchaKku

Reputation: 1

SONAR Violation IllegalType, why it is important to fix it?

I have noticed in SONAR that I have a violation that is called IllegalType in my java Code. I looked for this and in Checkstyle explain about it this :

Checks that particular class are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.

Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of a convenience base class implementations of interfaces and as such are not types themselves.

But I don't understand really why is this a problem in my code. If anyone can explain me better maybe with an example it could be great!. Thanks at all.

Upvotes: 0

Views: 875

Answers (2)

Manuelarte
Manuelarte

Reputation: 1810

What Aaron Digulla said in his comments is a good practice for sure. However I also found this IllegalType issue with my own Abstract Classes (instead of interfaces) which don't seem to me to be pretty clear. I understand the benefits of using intefaces insteaf of classes, and I also understand that abstract classes are partially classes (so much more a class than a interface) but I don't see the benefits of this rule, as I can find cases where I can return a concrete class (no abstract) which is a superclass of what I'm actually returning.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328760

Not all violations that Sonar finds are for everyone. The check IllegalType (docs) tries to make sure you don't use classes that most developers deem "broken" in some way like Vector (use ArrayList instead).

Other classes shouldn't be used as a return type. Always return List instead of ArrayList, Set instead of HashSet, Map instead of HashMap - that way, consumers of your code don't know any unnecessary details about your implementation. If you find you need to replace HashMap with TreeMap (or vice versa) in a method, that will be much more simple if you don't have to change all the places as well where this method was called.

Generally, the check isn't a problem as such (your code works) but fixing those will make your code easier to maintain in the future.

Upvotes: 0

Related Questions