Code Quality, Style and Best Practices

47.1 Style Conventions

4-space indentation, camelCase methods and variables, PascalCase classes, UPPER_SNAKE constants.

Omit semicolons and optional parentheses where readability improves (in DSL-like code). Keep parentheses in complex expressions.

Use def for local variables when the type is obvious, and explicit types for public APIs (method signatures, fields).

Prefer GStrings for interpolation and single quotes for plain strings.

47.2 Idiomatic Groovy

✅ Use GDK methods (collect, findAll, inject, groupBy) instead of manual loops where clearer.

✅ Use ?. and ?: for null handling. Use Groovy Truth for concise conditions (but be explicit when 0/empty is a valid value).

✅ Use properties instead of explicit getters and setters. Use named-argument constructors.

✅ Use AST transformations (@Canonical, @Immutable, @Builder, @Slf4j) to remove boilerplate.

✅ Use @CompileStatic for library code and hot paths. Use dynamic Groovy for scripts and DSLs.

✅ Use with/tap for object configuration. Use withReader/withWriter/withCloseable for resources.

✅ Use traits for reusable behavior. Use records for immutable data (Groovy 4).

✅ Write Spock specifications. Use power asserts.

❌ Don't overuse runtime metaprogramming in application code (hard to debug, breaks static compilation). Prefer extension modules.

❌ Don't use GStrings as map keys or compare GStrings to Strings with .equals() (== is fine).

❌ Don't ignore @CompileStatic errors by sprinkling @CompileDynamic everywhere.

❌ Don't rely on undeclared script binding variables in larger scripts. Use def or @Field.

❌ Avoid Eval.me / GroovyShell on user input.

47.3 Tooling

CodeNarc: static analysis (hundreds of rules: basic, braces, convention, design, imports, naming, unnecessary code, Groovyism). There's a Gradle plugin (codenarc).

groovy-lint / npm-groovy-lint: CodeNarc-based linter and formatter (also for Jenkinsfiles).

IntelliJ inspections, SpotBugs (bytecode-level), JaCoCo coverage, SonarQube Groovy plugin.

Documentation: groovydoc (Gradle groovydoc task) with Groovydoc comments /** ... */.