Video in progress
In an organization with many teams, how do you systematically prevent mistakes with equals/hashCode, null, mutable statics and the like without relying on code review?
Automate the rules: compiler warnings (-Xlint -Werror), Error Prone/NullAway, ArchUnit, SpotBugs, EqualsVerifier tests. Turn them on at the platform level (a shared build plugin), strict for new code and phased in with a baseline for old code.
📖 Answer
In code review, people like looking at design, naming and business logic. They don't like noticing that hashCode wasn't overridden, that BigDecimal was compared with equals, or an Optional.get(). Hand those to a machine.
The layers:
-
The compiler.
-Xlint:all -Werror(or at leastrawtypes,unchecked,fallthrough,deprecation). Cheap, fast, and every IDE shows it. -
Error Prone (at compile time):
EqualsHashCode,ReferenceEquality,MissingOverride,StringSplitter,FutureReturnValueIgnored,UnusedVariableand hundreds of others. NullAway is for null. -
ArchUnit: architecture rules as tests:
@ArchTest
static final ArchRule noMutableStatics =
fields().that().areStatic().and().areNotFinal()
.should().notBeDeclaredInClassesThat().resideInAPackage("..domain..")
.because("domen klasslarida global holat bo'lmasin");
Rules like ..controller.. must not call ..repository.. directly, and java.util.Date must not be used.
-
Test libraries:
EqualsVerifier.forClass(Money.class).verify()for every value object. -
SpotBugs/Sonar: bytecode analysis, broader but noisier; informational in CI.
The rollout strategy (where many initiatives die):
- Through the platform. A shared Gradle convention plugin or Maven parent, so each team doesn't configure its own.
- A baseline. For old code, the current list of warnings is frozen (ArchUnit's
FreezingArchRule; Error Prone has no ready-made baseline, so the check is turned on atWARNINGlevel in old modules andERRORlevel in new ones); only new violations fail the build. Otherwise there are 4,000 errors on day one and the rule gets switched off. - Automatic fixes: Error Prone patches, OpenRewrite recipes; when the cost of fixing is close to zero, resistance drops.
- Reducing noise. The "why" is documented for each rule; if there are many false positives, the rule is removed, not the people.
- Measuring. The size of the baseline should shrink every quarter; tying the causes of production incidents to these rules helps convince people.
Then comments like "there's no equals here" disappear from reviews, and the reviewer's time goes to design.
Sign up to mark studied questions and save your progress.