Clean Coding with Classes: Embracing the Single Responsibility Principle

Introduction

Welcome to the very first lesson of the "Clean Coding with Classes" course! In our previous journey through "Clean Code Basics," we focused on the foundational practices essential for writing maintainable and efficient software. Now, we transition to learning about crafting clean, well-organized classes. This lesson will highlight the importance of the Single Responsibility Principle (SRP), which serves as a vital guideline for creating classes that are straightforward, understandable, and easy to work with.

Understanding the Single Responsibility Principle

The Single Responsibility Principle states that a class should have only one reason to change, meaning it should have only one job or responsibility. This principle contributes significantly to software design by ensuring each class has a single purpose. Adhering to the SRP results in cleaner, more modular, and more understandable code. The main benefits include enhanced readability, straightforward maintenance, and easier testing, making it a cornerstone of clean coding.

Identifying SRP Violations

Let's explore what happens when a class doesn't follow the Single Responsibility Principle by examining a practical code snippet. Consider the following Report class:

class Report {
    fun generateReport(): String {
        // Generate report logic
        return "Report"
    }

    fun print(reportContent: String) {
        // Print report logic
        println(reportContent)
    }

    fun saveToFile(reportContent: String, filePath: String) {
        // Save report logic
        println("Saving report to $filePath...")
    }

    fun sendByEmail(email: String, reportContent: String) {
        // Send email logic
        println("Sending email to $email")
    }
}

Here, the Report class handles report generation, printing, saving, and emailing, which are distinct responsibilities. This violation of the SRP results in increased complexity; changes in one area may unintentionally affect others, making maintenance more challenging.

Refactoring for SRP Compliance

To better align with the Single Responsibility Principle, we need to refactor the Report class into multiple classes, each handling a single responsibility. Let's examine a refactored version:

class Report {
    fun generate(): String {
        // Generate report logic
        return "Report"
    }
}

class ReportPrinter {
    fun print(reportContent: String) {
        // Print report logic
        println(reportContent)
    }
}

class ReportSaver {
    fun saveToFile(reportContent: String, filePath: String) {
        // Save report logic
        println("Saving report to $filePath...")
    }
}

class EmailSender {
    fun sendByEmail(email: String, reportContent: String) {
        // Send email logic
        println("Sending email to $email")
    }
}

In this refactoring, each class is responsible for only one task: Report generates the report, ReportPrinter handles printing, ReportSaver takes care of saving to a file, and EmailSender manages email sending. This division improves the modularity and testability of our code. Each class can now be understood, modified, and reused independently, reducing unintended side effects.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal