DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Adopt Developer Tools Through Internal Champions
  • Router4j: A Free Alternative to Google Maps for Route and Distance Calculation
  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Mastering Thread-Local Variables in Java: Explanation and Issues

Trending

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Scaling Microservices With Docker and Kubernetes on Production
  • How to Create a Successful API Ecosystem
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  1. DZone
  2. Coding
  3. Tools
  4. Writing Great Code: The Five Principles of Clean Code

Writing Great Code: The Five Principles of Clean Code

Explore clean code practices such as using meaningful names and focused functions, avoiding code duplication, and eliminating side effects.

By 
Sasidhar Sunkara user avatar
Sasidhar Sunkara
·
Oct. 14, 24 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

One of the finest ways to make the code easy to read, maintain, and improve can be done by writing clean code. Clean code helps to reduce errors, improves the code quality of the project, and makes other developers and future teams understand and work with the code. The well-organized code reduces mistakes and maintenance a lot easier.

Clean code graphic

1. Use Meaningful Names

Clean code should have meaningful names that describe the purpose of variables, functions, and classes. The name itself should convey what the code does. So, anyone who is reading it can understand its purpose without referring to any additional documentation.

Example

  • Bad naming:
Java
 
int d; // What does 'd' represent?


  • Good naming:
Java
 
int daysSinceLastUpdate; // Clear, self-explanatory name


  • Bad method name:
Java
 
public void process() {
    // What exactly is this method processing?
}


  • Good method name:
Java
 
public void processPayment() {
    // Now it's clear that this method processes a payment.
}


2. Write Small Functions

Functions should be small and focused on doing just one thing. A good rule of thumb is the Single Responsibility Principle (SRP) which is each function should have only one reason to change.

Example

  • Bad example (a large function doing multiple things):
Java
 
public void processOrder(Order order) {
    validateOrder(order);
    calculateShipping(order);
    processPayment(order);
    sendConfirmationEmail(order);
}


  • Good example (functions doing only one thing):
Java
 
public void processOrder(Order order) {
    validateOrder(order);
    processPayment(order);
    confirmOrder(order);
}

private void validateOrder(Order order) {
    // Validation logic
}

private void processPayment(Order order) {
    // Payment processing logic
}

private void confirmOrder(Order order) {
    // Send confirmation email
}


Each function now handles only one responsibility, making it easier to read, maintain, and test.

3. Avoid Duplication

Duplication is one of the biggest problems in messy code. Avoid copying and pasting code. Instead, look for common patterns and extract them into reusable methods or classes.

Example

  • Bad example (duplicated code):
Java
 
double getAreaOfRectangle(double width, double height) {
    return width * height;
}

double getAreaOfTriangle(double base, double height) {
    return (base * height) / 2;
}


  • Good example (eliminated duplication):
Java
 
double getArea(Shape shape) {
    return shape.area();
}

abstract class Shape {
    abstract double area();
}

class Rectangle extends Shape {
    double width, height;
    @Override
    double area() {
        return width * height;
    }
}

class Triangle extends Shape {
    double base, height;
    @Override
    double area() {
        return (base * height) / 2;
    }
}


Now, the logic for calculating the area is encapsulated in each shape class, eliminating the need for duplicating similar logic.

Java
 
public void updateOrderStatus(Order order) {
    if (order.isPaid()) {
        order.setStatus("shipped");
        sendEmailToCustomer(order);  // Side effect: sends an email when the status is changed
    }
}


4. Eliminate Side Effects

Functions should avoid change of state outside their scope which causes unintended side effects. When functions have side effects, they become harder to understand and can act in unpredictable behavior.

Example

  • Bad example (function with side effects):
Java
 
public void updateOrderStatus(Order order) {
    if (order.isPaid()) {
        order.setStatus("shipped");
        sendEmailToCustomer(order);  // Side effect: sends an email when the status is changed
    }
}


  • Good example (no side effects):
Java
 
public void updateOrderStatus(Order order) {
    if (order.isPaid()) {
        order.setStatus("shipped");
    }
}

public void sendOrderShippedEmail(Order order) {
    if (order.getStatus().equals("shipped")) {
        sendEmailToCustomer(order);
    }
}


In the above case, the function's main job is to update the status. Sending an email is another task that is handled in a separate method.

5. Keep Code Expressive

Keeping the code expressive includes structure, method names, and overall design which should be easy to understand to the reader what the code is doing. Comments are rarely used if the code is clear.

Example

  • Bad example (unclear code):
Java
 
if (employee.type == 1) {
    // Manager
    pay = employee.salary * 1.2;
} else if (employee.type == 2) {
    // Developer
    pay = employee.salary * 1.1;
} else if (employee.type == 3) {
    // Intern
    pay = employee.salary * 0.8;
}


  • Good example (expressive code):
Java
 
if (employee.isManager()) {
    pay = employee.calculateManagerPay();
} else if (employee.isDeveloper()) {
    pay = employee.calculateDeveloperPay();
} else if (employee.isIntern()) {
    pay = employee.calculateInternPay();
}


In the above good example, method names are made clear to express the intent. It makes user to read easier and understand the code without any comments.

Conclusion

Here are some of the key principles for writing clean code: use of meaningful names, use small functions, avoid repeating code, remove side effects, and write clear and expressive code. Following these practices makes the code easier to understand and fix.

dev Side effect (computer science) Data Types Coding best practices Tool

Opinions expressed by DZone contributors are their own.

Related

  • How to Adopt Developer Tools Through Internal Champions
  • Router4j: A Free Alternative to Google Maps for Route and Distance Calculation
  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Mastering Thread-Local Variables in Java: Explanation and Issues

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!