Writing code is easy. Reading it 6 months later… less so 😅 Here’s a recap of core Java code conventions around declarations that make your codebase easier to maintain and review.
🔸 TL;DR
- ▪️ One declaration per line, no mixed types, no “var + method” combos.
- ▪️ Declare at block start, except for loop indices.
- ▪️ Avoid shadowing variables from outer scopes.
- ▪️ Initialize where you declare when possible.
- ▪️ Consistent class formatting: braces placement, no space before (, blank lines between methods.
🔸 ONE DECLARATION PER LINE
▪️ Prefer one variable per line so you can comment each clearly:
int level; // indentation levelint size; // size of table
▪️ Avoid grouping in one line:
int level, size; // 👎 harder to comment/scan
▪️ Never mix variables and methods on the same line:
long dbaddr, getDbaddr(); // ❌ WRONG
▪️ Don’t mix different types on the same line (including arrays):
int foo, fooarray[]; // ❌ WRONG
▪️ Spacing is flexible:
- int level; (one space) ✅
- or aligned with tabs for nicer columns ✅
🔸 PLACE DECLARATIONS AT THE START OF BLOCKS
▪️ Put declarations at the beginning of a block (anything between { and }):
void myMethod() { int int1; // method block start
if (condition) {
int int2; // "if" block start
...
}
}
▪️ Don’t delay declarations until first use inside the block – it makes code harder to read and move around.
▪️ Exception: for loop indices can be declared directly in the loop header:
for (int i = 0; i < maxLoops; i++) { ...
}
▪️ Avoid hiding variables declared in outer scopes (no shadowing):
int count;
void func() {
if (condition) {
int count; // ❌ AVOID: hides outer 'count'
}
}
🔸 INITIALIZE WHERE YOU DECLARE 💡
▪️ Try to initialize local variables at the point of declaration:
int retries = 3;String status = "PENDING";
▪️ Only skip initialization when the value depends on a prior computation and must be set later.
🔸 CLASS & INTERFACE DECLARATION STYLE
When writing classes and interfaces, keep formatting consistent:
▪️ No space between method name and (:
int sum(int a, int b) { ... } // ✅
▪️ Opening brace { stays on the same line as the declaration:
class Sample extends Object { int ivar1;
int ivar2;
Sample(int i, int j) {
ivar1 = i;
ivar2 = j;
}
▪️ Closing brace }
- On its own line, aligned with the start of the declaration:
...} // aligned with 'class Sample...'
▪️ For empty methods, {} can be placed directly after the signature:
int emptyMethod() {}
▪️ Separate methods with a blank line for readability:
int doSomething() { ...
}
int doSomethingElse() {
...
}
🔸 TAKEAWAYS 🚀
- ▪️ Clean declarations = clean diffs, easier reviews, fewer bugs.
- ▪️ These rules look strict, but they scale incredibly well on large teams and codebases.
- ▪️ Even in modern Java, boring consistency wins over clever shortcuts.
How close is your current codebase to these conventions? 🤔
#Java #Java21 #CleanCode #CodeStyle #CodingStandards #JavaDeveloper #Backend #SoftwareEngineering
Go further with Java certification:
Java👇
Spring👇
SpringBook👇