Clean Code in Java: Principles and Examples for Practitioners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Clean Code in Java: Principles and Practical Examples



Every Java developer sooner or later faces the problem of "dirty" code. Hard-to-read methods, meaningless variable names, magic numbers, and giant classes all slow down development, increase the number of bugs, and demotivate the team. Robert Martin's book "Clean Code" has become a bible for those who want to write quality software. In this article, we will break down the key principles of clean code in Java and show how to apply them in practice with concrete examples.



1. Naming Variables, Methods, and Classes



A proper name is half the battle. The name should reveal the programmer's intent. If you need to read the method body to understand what it does, the name was poorly chosen.



Bad example:

int d; // elapsed time in daysList<Integer> lst = new ArrayList<>();public void proc(int a, int b) {    // ...}


Good example:

int elapsedTimeInDays;List<Integer> customerIds = new ArrayList<>();public void calculateTotalPrice(double basePrice, double discount) {    // ...}


Naming rules:

  • Classes and interfaces — nouns (Customer, OrderProcessor, PaymentService).
  • Methods — verbs or verb phrases (saveCustomer, findById, isActive).
  • Variables — meaningful nouns reflecting the essence of the data (userName, totalAmount).
  • Avoid abbreviations — write fullName instead of fn, otherwise in a month you won't remember what fn means.


2. Small Methods and the Single Responsibility Principle



A method should do only one thing and do it well. If a method contains more than 10-15 lines of code or has multiple levels of nesting, it's a signal for refactoring.



Bad example (method does too much):

public void processOrder(Order order) {    // 1. Validation    if (order.getItems().isEmpty()) throw new IllegalArgumentException("Order is empty");    // 2. Discount calculation    double discount = 0;    if (order.getCustomer().isPremium()) discount = 0.1;    // 3. Total price calculation    double total = 0;    for (Item item : order.getItems()) {        total += item.getPrice() * item.getQuantity();    }    total = total * (1 - discount);    // 4. Save to DB    orderRepository.save(order);    // 5. Send email    emailService.sendConfirmation(order.getCustomer().getEmail());}


Good example (split into small methods):

public void processOrder(Order order) {    validateOrder(order);    double discount = calculateDiscount(order.getCustomer());    double totalPrice = calculateTotalPrice(order, discount);    order.setTotalPrice(totalPrice);    orderRepository.save(order);    sendConfirmationEmail(order.getCustomer());}

private void validateOrder(Order order) { if (order.getItems().isEmpty()) { throw new IllegalArgumentException("Order cannot be empty"); }}

private double calculateDiscount(Customer customer) { return customer.isPremium() ? 0.1 : 0.0;}

private double calculateTotalPrice(Order order, double discount) { double subtotal = order.getItems().stream() .mapToDouble(item -> item.getPrice() * item.getQuantity()) .sum(); return subtotal * (1 - discount);}

private void sendConfirmationEmail(Customer customer) { emailService.sendConfirmation(customer.getEmail());}


3. Avoid Code Duplication (DRY — Don't Repeat Yourself)



Duplication is the root of many evils. When logic is repeated in multiple places, any change requires fixes

Blogs

Book Recommendations