Cookie Consent by Free Privacy Policy Generator 📌 The SOLID Principles for Writing Scalable & Maintainable Code


✅ The SOLID Principles for Writing Scalable & Maintainable Code


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Introduction

Writing clean, maintainable, and scalable code is essential in the fast-evolving world of software development. The SOLID principles, devised by Robert C. Martin, provide a set of guidelines that help developers achieve this through better software design. Let's explore these principles with JavaScript-specific examples.

S: Single Responsibility Principle (SRP)

Definition: A class should have one, and only one, reason to change.

Explanation: SRP suggests that a class or module should have one responsibility and thus only one reason to change. This approach simplifies system modification and testing.

Example:
Consider a module that handles user data and generates user reports:

class UserHandler {
    constructor(user) {
        this.user = user;
    }

    saveUser() {
        console.log(`Saving user ${this.user.name}`);
        // logic to save user to a database
    }

    generateReport() {
        console.log(`Generating report for ${this.user.name}`);
        // logic to generate a user report
    }
}

This class violates SRP because it manages user data and also handles report generation. We can refactor it into two classes:

class UserStorage {
    constructor(user) {
        this.user = user;
    }

    saveUser() {
        console.log(`Saving user ${this.user.name}`);
        // logic to save user to a database
    }
}

class UserReport {
    constructor(user) {
        this.user = user;
    }

    generateReport() {
        console.log(`Generating report for ${this.user.name}`);
        // logic to generate a user report
    }
}

O: Open/Closed Principle (OCP)

Definition: Software entities should be open for extension, but closed for modification.

Explanation: This principle advocates that classes should be extendable without modifying the existing code, thus preventing changes in existing code and associated risks.

Example:
Imagine a basic payment class that needs to be extended to support different payment methods:

class Payment {
    process(amount) {
        console.log(`Processing ${amount} via Credit`);
    }
}

// Extending Payment for new payment method
class PaymentWithDebit extends Payment {
    process(amount) {
        console.log(`Processing ${amount} via Debit`);
    }
}

This setup allows new payment methods to be added without altering existing classes, complying with OCP.

L: Liskov Substitution Principle (LSP)

Definition: Subtypes must be substitutable for their base types.

Explanation: According to LSP, if a program uses a base class, the reference to the base class can be replaced with a derived class without affecting the program's functionality.

Example:
Suppose we have a rectangle class and a square class:

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    setWidth(width) {
        this.width = width;
    }

    setHeight(height) {
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class Square extends Rectangle {
    setWidth(width) {
        super.setWidth(width);
        super.setHeight(width);
    }

    setHeight(height) {
        super.setWidth(height);
        super.setHeight(height);
    }
}

In this scenario, Square should not inherit from Rectangle as it changes the behavior of setWidth and setHeight methods, violating LSP. Each should have its own class if their behaviors differ significantly.

I: Interface Segregation Principle (ISP)

Definition: No client should be forced to depend on methods it does not use.

Explanation: ISP advocates for creating specific interfaces rather than general-purpose interfaces, so that implementing classes only need to be concerned with methods that are pertinent to them.

Example:
Consider an interface with too many responsibilities:

class Worker {
    work() {
        console.log('Working on tasks');
    }

    eat() {
        console.log('Lunch break');
    }

    train() {
        console.log('Training in progress');
    }
}

class Robot extends Worker {
    train() {
        // Irrelevant method for a robot
        throw new Error('Not applicable');
    }
}

A better approach is to break down the Worker interface:

class Workable {
    work() {
        console.log('Working on tasks');
    }
}

class Eatable {
    eat() {
        console.log('Lunch break');
    }
}

class Trainable {
    train() {
        console.log('Training in progress');
    }
}

class HumanWorker extends Workable, Eatable, Trainable {}
class RobotWorker extends Workable

 {}

D: Dependency Inversion Principle (DIP)

Definition: High-level modules should not depend on low-level modules. Both should depend on abstractions.

Explanation: DIP suggests that high-level and low-level modules should interact through interfaces (abstractions), reducing the dependencies on concrete implementations.

Example:
Here's a basic example with tight coupling:

class ContentDatabase {
    store(content) {
        console.log(`Storing content: ${content}`);
        // Database storage logic
    }
}

class ContentService {
    constructor() {
        this.db = new ContentDatabase();
    }

    addContent(content) {
        this.db.store(content);
    }
}

Refactored with dependency inversion:

class Database {
    store(content) {
        throw new Error('Method store() must be implemented');
    }
}

class ContentDatabase extends Database {
    store(content) {
        console.log(`Storing content: ${content}`);
        // Database storage logic
    }
}

class ContentService {
    constructor(database) {
        this.db = database;
    }

    addContent(content) {
        this.db.store(content);
    }
}

This setup allows ContentService to be more flexible and easier to test, as it can work with any database that adheres to the Database interface.

Conclusion

Applying the SOLID principles in JavaScript projects can significantly enhance the maintainability, scalability, and robustness of your code. By ensuring that each component of your software adheres to these principles, you establish a strong foundation for a sustainable project.

...

✅ The SOLID Principles for Writing Scalable & Maintainable Code


📈 79.35 Punkte

✅ Crafting Maintainable and Scalable Software: Applying SOLID Principles


📈 62.22 Punkte

✅ Mastering SOLID Principles in C# Building Robust and Maintainable Software


📈 48.19 Punkte

✅ Why SOLID Design Matters: Avoid Code Smells and Write Maintainable Code


📈 41.74 Punkte

✅ SOLID Principles / Open - closed principles -


📈 39.78 Punkte

✅ SOLID Principles Aren't Principles


📈 39.78 Punkte

✅ SOLID Principles: They're Rock-Solid for Good Reason!


📈 38.85 Punkte

✅ Writing maintainable js code


📈 36.97 Punkte

✅ 5 Best Practices for Coding: Tips for Writing Clean, Efficient, and Maintainable Code


📈 36.97 Punkte

✅ Best Practices for Writing Clean and Maintainable Code


📈 36.97 Punkte

✅ TypeScript Best Practices: Writing Clean and Maintainable Code


📈 36.97 Punkte

✅ Tips and Strategies for Writing Clean and Maintainable JSX Code


📈 36.97 Punkte

✅ A Guide To Writing Clean and Maintainable Code.


📈 36.97 Punkte

✅ The Art of Writing Clean Code: Craft Clear and Maintainable Software


📈 36.97 Punkte

✅ Best Practices for Writing Clean and Maintainable Html, Css, and JavaScript Code


📈 36.97 Punkte

✅ Scalable and Maintainable React Project Structure Every Developer Should Use.


📈 36.01 Punkte

✅ How to Develop Scalable and Maintainable JavaScript Apps using ES6 Design Patterns


📈 36.01 Punkte

✅ Object-Oriented Design: The Key to Scalable and Maintainable Software


📈 36.01 Punkte

✅ Top 10 Best Practices in HTML to Build Maintainable and Scalable Websites


📈 36.01 Punkte

✅ Leveraging Vue 3's Composition API for Scalable and Maintainable Codebases


📈 36.01 Punkte

✅ Practical Go: Real World Advice For Writing Maintainable Go Programs


📈 33.41 Punkte

✅ Best Practices for Writing Clean and Maintainable HTML


📈 33.41 Punkte

✅ Mastering Code Quality: Applying SOLID Principles in a Library Checkout System


📈 29.76 Punkte

✅ What are the SOLID Principles in Java? Explained With Code Examples


📈 29.76 Punkte

✅ Enhancing Code Quality: How ChatGPT Can Help You Follow Best Practices and Maintainable Code 🚀


📈 29.1 Punkte

✅ Data Protection Principles: The 7 Principles of GDPR Explained


📈 27.14 Punkte

✅ Data Protection Principles: The 7 Principles of GDPR Explained


📈 27.14 Punkte

✅ How do programming principles equate to life's principles?


📈 27.14 Punkte

✅ I Used to be a 💩 Coder 💻 Until I Discovered SOLID Principles 🌟


📈 26.21 Punkte

✅ SOLID Design Principles in Software Development


📈 26.21 Punkte

✅ SOLID PRINCIPLES


📈 26.21 Punkte

✅ Solid Principles in Python


📈 26.21 Punkte

✅ SOLID PRINCIPLES


📈 26.21 Punkte

✅ SOLID Principles: Explained with Golang Examples


📈 26.21 Punkte











matomo

Datei nicht gefunden!