Clean Code in Java: Principles and Practical Examples

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

Introduction: Why Clean Code is Not a Luxury, but a Necessity

\n

Every Java developer has encountered a situation where, opening an old project, they spend hours trying to understand what they themselves wrote just a couple of months ago. And what about someone else's code? Dirty code slows down development, increases the number of bugs, and demotivates the team. Robert Martin's book "Clean Code" has become a bible for programmers, but its principles often remain abstract. In this article, we will break down the key concepts of Clean Code in Java with real examples that you can apply today.

\n

Clean code is not about perfect syntax or following trends. It's about respect for your colleagues, for your future self, and ultimately, for the business. Readable code is easier to maintain, test, and refactor. Let's see how to turn Java code from "working" to "clean."

\n\n

1. Meaningful Names: Speak the Language of the Domain

\n

Rule: The name should answer the questions "why?", "what?", "how?"

\n

Poor naming is the main enemy of clean code. Variables like int a, String d, or List<Integer> list1 carry no information. A good name should reveal the programmer's intent.

\n\n
// Bad\nint d; // elapsed time in days\nList<Integer> lst;\n\n// Good\nint daysSinceCreation;\nList<Integer> customerIds;
\n\n

Avoid Disinformation

\n

Do not use accountList if it is not a List, but rather a Set or Map. Do not abbreviate the obvious: usrNm instead of userName.

\n\n

Class and Method Names

\n
    \n
  • Classes: nouns (Customer, OrderProcessor).
  • \n
  • Methods: verbs (calculateTotal(), saveToDatabase()).
  • \n
  • Boolean variables: predicates (isActive, hasPermission).
  • \n
\n\n
// Bad\npublic class Data {\n    public void proc() { ... }\n}\n\n// Good\npublic class InvoiceCalculator {\n    public BigDecimal calculateTotalAmount() { ... }\n}
\n\n

2. Functions: Short, Atomic, and Without Side Effects

\n

First Principle: A function should do only one thing

\n

The ideal function in Java is 4-20 lines. If a function does more than one action, it needs to be split. A classic sign: if you can extract another function with a meaningful name from a function — do it.

\n\n
// Bad: the function does three things\npublic void processOrder(Order order) {\n    if (order == null) throw new IllegalArgumentException();\n    // 1. Validation\n    if (order.getItems().isEmpty()) {\n        logger.warn("Empty order");\n        return;\n    }\n    // 2. Cost calculation\n    BigDecimal total = BigDecimal.ZERO;\n    for (Item item : order.getItems()) {\n        total = total.add(item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));\n    }\n    // 3. Sending email\n    emailService.sendConfirmation(order.getCustomerEmail(), total);\n}\n\n// Good: each function does one thing\npublic void processOrder(Order order) {\n    validateOrder(order);\n    BigDecimal total = calculateTotal(order);\n    sendConfirmationEmail(order, total);\n}\n\nprivate void validateOrder(Order order) {\n    if (order == null || order.getItems().isEmpty()) {\n        throw new IllegalArgumentException("Invalid order");\n    }\n}\n\nprivate BigDecimal calculateTotal(Order order) {\n    return order.getItems().stream()\n            .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))\n            .reduce(BigDecimal.ZERO, BigDecimal::add);\n}
\n\n

The Boy Scout Rule: Leave the Campground Cleaner Than You Found It

\n

Every time you edit a file, improve it: rename a bad variable, break up a long function. This prevents code entropy.

\n\n<

Blogs

Book Recommendations