Clean Code in Java: Principles and Examples for Beginners
Every developer starting their journey in Java sooner or later encounters a situation: the code works, but it's impossible to understand it a week later. This is the classic problem of "dirty" code. Clean Code is not just a trendy term, but a set of practices that make your program understandable, easy to maintain, and extensible. In this article, we will break down the main principles of Clean Code in Java for beginners with clear examples.
Why is clean code important?
In real-world development, code is read much more often than it is written. You will return to your old projects, work in a team, or pass code to colleagues. Poorly written code slows down development, increases the number of bugs, and is demotivating. Clean Code saves time and nerves. Let's break down the key principles.
1. Clear names: say what you do
Names of variables, methods, and classes should answer the question "what is this?" or "what does it do?". Don't skimp on characters — use meaningful names.
Bad example (unclear names):
int d; // elapsed time in daysList<String> lst = new ArrayList<>();public void prc() { ... }Good example (Clean Code):
int elapsedTimeInDays;List<String> customerNames = new ArrayList<>();public void processPayment() { ... }Tip: Avoid single-letter names (except for loop counters). The name should reveal intent. Instead of list, use activeUsers or orderIds.
2. Small functions: one task — one function
Functions should do only one thing and do it well. Long methods are hard to test and understand. Aim for a length of no more than 20–30 lines.
Bad example (function does everything):
public void processOrder(Order order) { // validation if (order.getTotal() <= 0) { throw new IllegalArgumentException("Invalid order"); } // save to database saveToDatabase(order); // send email sendEmail(order.getCustomerEmail(), "Order confirmed"); // update inventory updateInventory(order);}Good example (broken into small functions):
public void processOrder(Order order) { validateOrder(order); saveOrder(order); notifyCustomer(order); updateStock(order);}
private void validateOrder(Order order) { if (order.getTotal() <= 0) { throw new IllegalArgumentException("Invalid order total"); }}
private void notifyCustomer(Order order) { sendEmail(order.getCustomerEmail(), "Order confirmed");}Now each function has a clear responsibility. The code has become self-documenting.
3. Avoid duplication: the DRY principle
The DRY (Don't Repeat Yourself) principle states: every piece of knowledge must have a single, unambiguous representation within a system. If you copy code, you create maintenance problems.
Bad example (duplication):
public double calculateDiscountForRegularCustomer(double price) { return price * 0.9; // 10% discount}
public double calculateDiscountForVipCustomer(double price) { return price * 0.8; // 20% discount}Good example (generalization):
public double calculateDiscount(double price, CustomerType type) { double discountRate = getDiscountRate(type); return price * discountRate;}
private double getDiscountRate(CustomerType type) { switch (type) { case REGULAR: return 0.9; case VIP: return 0.8; default: return 1.0; }}Now changing the discount logic happens in one place.
4. Formatting and comments: visual cleanliness
Code should be neat