Question about example in writing custom Java rules

I’m starting to look at writing a custom Java rule, so I’m looking at sonar-java/CUSTOM_RULES_101.md at master · SonarSource/sonar-java · GitHub . I haven’t gone very far through this, but I noticed something odd that I could use some clarification on, and perhaps it would be good to also clarify this in the document.

The doc specifically says this:

In folder `/src/test/files` , create a new empty file named `MyFirstCustomCheck.java` , and copy-paste the content of the following code snippet.

The content shown is this:

class MyClass {
}

Clearly, this is saying to define class “Myclass” inside “MyFirstCustomCheck.java”. There is nothing legally wrong with this. Java does allow for the source file name to not correspond to a class defined in that source file, but WHY is this example doing this? It’s odd to do this.

Hello @David_Karr ,
Thanks for pointing this out. While the naming is indeed not illegal Java-wise, the example could be renamed for better consistency.

As to why there might be inconsistencies between file names and classes, because the source file is placed outside of maven’s source directories, src/main/java and src/test/java, it enables you to test your check on a file that does not compile.
With this, you could test Java syntax that is not yet supported by the version you are running your custom rules with.
See this example with text blocks that can be parsed by the analyzer but cannot be compiled in Java 8 or 11.

Cheers,

Dorian