- Readable
- Clear
- Expressive
- Understandable
- Scannable
- Minimal diffs
- Easily edited
- Max 100 - 120 chars per line
- Prefer
final(except lambda args) - Prefer method references over lambdas
- Operators on next line
- Separate (logical) blocks with empty lines
- Empty line after "jumps" (loops,
return,break,continue) - "Chop" long expressions, arguments on separate lines
- Continued lines indented twice
- Mark methods without state as
static - Lambdas with a single arg do not use parentheses:
x => x + 1 - Prefer guard clauses over deep nesting
@Multiple(annotations = "")
@With(
several = "property",
values = {
"one",
"two",
"three"
})
publicclassMyClassextendsMyBaseimplementsImplementable {
publicstaticfinalStringCONSTANT_VALUE = "compile-time-constant";
privatestaticfinallongCLASS_ID = 1337L;
privatefinalMyDependencydependency;
publicMyClass(finalMyDependencydependency) {
this.dependency = Objects.requireNonNull(dependency);
finalMyCachemyCache = newMyExpiringCache(10, MINUTES);
finalMyOverlyLongNameoverlyLongInstance
= newMyOverlyLongName(myCache, "arguments");
finalMyThingWithTooManyArgs = newMyThingWithTooManyArgs(
myCache,
overlyLongInstance,
dependency,
"and",
"some",
"more",
"arguments");
}
publicstaticvoiddoSomethingWithManyParameters(
finalStringaction,
finalintiterations,
@AnnotatedfinalObjectpayload) {
if (payload == null) {
return;
}
if (iterations < 0) {
return;
}
for (inti = 0; i < iterations; ++i) {
call(action, payload);
}
callAnotherMethodWithManyParameters(
action,
iterations,
"foo",
"bar",
13,
37);
}
public <T> voidstreams(finalCollection<? extendsT> elements) {
finalList<T> list = elements.stream()
.filter(Objects::nonNull)
.map(x -> transform("mapping", x))
.collect(Collectors.toList());
dependency.send(list);
}
@Overridepublicbooleanequals(finalObjectother) {
returnthis == other
|| otherinstanceoffinalMyClassthat
&& Objects.equals(that.dependency, dependency);
}
@OverridepublicinthashCode() {
inthash = Objects.hashCode(dependency);
hash = 31 * hash + Objects.hashCode(/*another dependency*/);
returnresult;
}
privatestaticfinalclassNestedClassextendsAnotherBaseimplementsImplementable,
Nestable {
privateNestedClass() {
}
publicStringgetName() {
return"name";
}
publicintage() {
return42;
}
}
}Avoid reassigning default values:
// avoid:
List<String> names = List.of();
if (config) {
names = List.of(config.split(","));
}
// prefer:
final List<String> names;
if (config) {
names = List.of(config.split(","));
} else {
names = List.of();
}
// or:
final List<String> names = config
? List.of(config.split(","));
: List.of();
- Star-imports vs explicit imports
- Naming of getters: Java beans
getValue()vs record-stylevalue() finalwithinstanceofoperatorfinalwith try-with-resources