Monday, October 21, 2013

Checkstyle Check to detect System.out.println usage in java code

Examples of usage in code:
1.
import static java.lang.System.out;
...
out.println("hello!")

2.
System.out.println("hello");




Requirement:
- Analyse import for short name usage "import static java.lang.System.out;"

Possiblle name for Check: ForbidQualifierUsage

Options:
forbiddenFullQualifierNames : String List-  qualifier that we will search for (Example:"System.err.println")
ignoredClasses : Regex -  ignores (Example:"com.mycompany.console.Main")

Bad sides:
1) we can not distinguish methods by parameters so any user method with same name and without package usage will be false-positive if not all methods are investigated to detects overlap of static import in local declaration .

import static java.lang.System.setIn;


public static void setIn(InputStream in) {
    // just a method with similar signature that is compiled
    // if you comment out that method System.setIn will be used (tested in Intelij Idea)
}

public static void main(String... args) {
    setIn(null); // it is local if local method is defined
}

2) Any overloaded methods(same name but different parameters) will be false-positives or known limitations :) :

   System.out.println("hi", "hi")

https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5.3

It is permissible for one single-static-import declaration to import several fields or types with the same name, or several methods with the same name and signature. 
So JDK is OK with multiple imports by single static import, so overloaded identifiers are ok.


Resolution:
So it is not complete solution, kind of same level of false positives as RegExp search on code approach.
Could we close eyes on that false-positives?
do you have other ideas and proposal?
https://github.com/checkstyle/checkstyle/issues?q=is%3Aopen+is%3Aissue
Or discussion mail-list - https://groups.google.com/forum/#!forum/checkstyle-devel

No comments:

Post a Comment