DEV Community

araf
araf

Posted on

10 Coding Practices Every Senior Java Developer Should Know (with Real-World Examples)

If you're writing Java in production, these best practices are non-negotiable. Whether you're mentoring juniors or scaling systems, these habits define senior-level engineering.


1. βœ… Name Things Clearly

Bad:

public void d(User u) { ... }
Enter fullscreen mode Exit fullscreen mode

Good:

public void deleteUser(User user) { ... }
Enter fullscreen mode Exit fullscreen mode

Clear names reduce bugs and make code easier to debug and maintain.


2. 🧱 Apply SOLID Principles

Example – Open/Closed Principle (OCP)

Instead of:

if (shape instanceof Circle) { ... }
Enter fullscreen mode Exit fullscreen mode

Use:

interface Shape {
    double area();
}
Enter fullscreen mode Exit fullscreen mode

Add new shapes without modifying existing logic. That’s real extensibility.


3. 🚫 Avoid null – Use Optional

Optional<User> user = userRepo.findById(id);
user.ifPresent(u -> sendEmail(u.getEmail()));
Enter fullscreen mode Exit fullscreen mode

Encourages defensive coding and avoids NullPointerException.


4. 🧼 Keep Business Logic Out of Controllers

Anti-pattern:

@GetMapping("/register")
public void register(@RequestParam String name) {
    if (name.length() > 10) ...
}
Enter fullscreen mode Exit fullscreen mode

Best Practice:
Move validation and logic into service classes. Keep controllers thin.


5. πŸ”„ Prefer Composition Over Inheritance

Instead of:

class PremiumUser extends User { ... }
Enter fullscreen mode Exit fullscreen mode

Use:

class PremiumUser {
    private User user;
    private LoyaltyProgram loyaltyProgram;
}
Enter fullscreen mode Exit fullscreen mode

Composition = more flexibility, fewer surprises.


6. πŸ”’ Secure at Method Level

Use annotations like:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { ... }
Enter fullscreen mode Exit fullscreen mode

Never rely only on frontend enforcement or URL security.


7. πŸ” Log Intelligently

Avoid:

System.out.println("Order placed");
Enter fullscreen mode Exit fullscreen mode

Do:

log.info("Order placed for orderId={}, userId={}", orderId, userId);
Enter fullscreen mode Exit fullscreen mode

Structured logging helps with observability and tracing.


8. πŸ§ͺ Write Focused Tests

Bad:

@Test void testAll() { ... }
Enter fullscreen mode Exit fullscreen mode

Good:
Write one assert per test scenario. Use JUnit 5, Mockito, and Testcontainers where applicable.


9. 🧹 Validate Early, Validate Always

Use Bean Validation:

public class PaymentRequest {
    @NotNull
    private String accountId;

    @Min(1)
    private BigDecimal amount;
}
Enter fullscreen mode Exit fullscreen mode

Combine with @Validated in service or controller layers.


10. πŸ›‘ Don't Optimize Before It's Needed

Don’t:

buildHyperCustomCacheThatNoOneAskedFor()
Enter fullscreen mode Exit fullscreen mode

Do:
Profile first. Optimize second. Trust JFR, VisualVM, or YourKit.


Top comments (0)