Sobes.tech
Junior — Middle

Can you explain the essence of the dependency inversion principle in software development?

sobes.tech AI

Answer from AI

The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that:

  • High-level modules should not depend on low-level modules directly.
  • Both should depend on abstractions (e.g., interfaces).
  • Abstractions should not depend on details, but details should depend on abstractions.

This helps reduce coupling, increase flexibility, and facilitate testing.

Example in C++:

class IWriter {
public:
    virtual void write(const std::string& message) = 0;
    virtual ~IWriter() = default;
};

class ConsoleWriter : public IWriter {
public:
    void write(const std::string& message) override {
        std::cout << message << std::endl;
    }
};

class Logger {
    IWriter& writer;
public:
    Logger(IWriter& w) : writer(w) {}
    void log(const std::string& msg) {
        writer.write(msg);
    }
};

// Usage:
ConsoleWriter cw;
Logger logger(cw);
logger.log("Dependency inversion example");

Here, the Logger class depends not on a specific implementation of ConsoleWriter but on the abstraction IWriter, which allows easy changing of the writing implementation without modifying the Logger.