1

I want to enforce the use of the 'this' keyword using Spotless. For example: getTowerData().recordMap would be this.getTowerData().recordMap.

I'm running Spotless with Gradle with the current configuration:

spotless {
    java {
        importOrder('emu.grasscutter', '', 'java', 'javax', '\\#java', '\\#')
        googleJavaFormat('1.15.0')
        formatAnnotations()
        endWithNewline()
        indentWithTabs(2); indentWithSpaces(4)
        toggleOffOn()
    }
}

Currently, I've tried using:

custom('this', {
    // Force use of 'this.' keyword
    it.replaceAll('^\\s*(?!public|private|protected)(?!class|interface|enum|@interface)\\b(?!return)\\w+\\b', 'this.$0')
})

but this results in:

Step 'google-java-format' found problem in 'src\main\java\emu\grasscutter\auth\AuthenticationSystem.java':
null
java.lang.reflect.InvocationTargetException
Caused by: com.google.googlejavaformat.java.FormatterException: 1:2: error: class, interface, enum, or record expected
lolMagixD
  • 39
  • 1
  • 3
  • 2
    I see your point, but in my experience most Java programmer prefer to omit `this` when possible. You may be fighting against the main stream here. – markspace Apr 01 '23 at 19:18
  • I agree with what @markspace said, but for educational purposes, I am also interested to know how the technical solution to this (the political fight is another topic) – PatPanda Apr 03 '23 at 02:34
  • Do you want to do this only using `spotless` or are you open to using other plugins? Because the [checkstyle](https://docs.gradle.org/current/userguide/checkstyle_plugin.html) gradle plugin has the [RequireThis](https://checkstyle.sourceforge.io/config_coding.html#RequireThis) rule for this exact scenario – devatherock May 10 '23 at 21:50
  • While I'd love to do it with Spotless, checkstyle works fine as well! – lolMagixD May 12 '23 at 04:20

1 Answers1

0

In a comment by devatherock, the checkstyle plugin for Gradle was mentioned and solves this exact issue. While it isn't specifically Spotless, it's the best solution to this problem.

lolMagixD
  • 39
  • 1
  • 3