Best practices for dependency injection via constructor

后端 未结 1 1580
有刺的猬
有刺的猬 2021-01-31 22:54

Inversion of control is a value-proof technique which is used to modularize a system and decouple the components from each other.

Low coupling is always an advantage: it

相关标签:
1条回答
  • 2021-01-31 23:33

    Instance copyable class

    class object
    {
    public:
      object(dependency d) : dep_(d) {}
    
    private:
      dependency dep_;
    };
    

    Only works in case dependency class is completely stateless, i.e. doesn't have any members. Practically, this rarely happens because dependency class may store its own dependency.

    Raw pointer

    class object
    {
    public:
      object(dependency *d) : dep_(d)
      {
        if (d == nullptr)
          throw std::exception("null dependency");
      }
    
    private:
      dependency *dep_;
    };
    

    This works like true injection. We're required to check the passed pointer for nullptr value.

    object class does not own dependency class, thus it's the responsibility of calling code to make sure the object is destroyed before the dependency object.

    In real application, it's sometimes very difficult to validate.

    Reference

    #define DISALLOW_COPY_AND_ASSIGN(Class) \
      Class(const Class &) = delete;        \
      Class &operator=(const Class &) = delete
    
    class object
    {
    public:
      object(dependency &d) : dep_(d) {}
    
      DISALLOW_COPY_AND_ASSIGN(object);
    
    private:
      dependency &dep_;
    };
    

    The reference cannot be null, so it's a bit safer in this prospective.

    However this approach brings additional constraints to object class: it has to be non-copyable since a reference cannot be copied. You have to either manually override assignment operator and copy constructor to stop from copying or inherit it from something like boost::noncopyable.

    Like with raw pointer, the ownership constraint is in place. Calling code should provide the correct destruction order for both classes, otherwise the reference becomes invalid and application crashes with access violation.

    If the dependency is a const reference:

    class object
    {
    public:
      object(const dependency &d) : dep_(d) {}
    
    private:
      const dependency &dep_;
    };
    

    you should pay attention to the fact that the object class accepts references to temporary objects:

    dependency d;
    object o1(d);             // this is ok, but...
    
    object o2(dependency());  // ... this is BAD.
    

    Further details:

    • C++: non-temporary const reference
    • What are the advantages of boost::noncopyable for several approaches to prevent copying a class
    • Should I prefer pointers or references in member data?
    • Using reference as class members for dependencies

    Smart pointer

    class object
    {
    public:
      object(std::shared_ptr<dependency> d) : dep_(d)
      {
        if (!d)
          throw std::exception("null dependency");
      }
    
    private:
      std::shared_ptr<dependency> dep_;
    };
    

    Similar to raw pointer but the ownership is controlled by smart pointer mechanism.

    Still need to check for nullptr in the constructor body.

    The major advantage is the dependency object lifetime control: there is no need for the calling application to properly control the destruction order (but consider that you need to be very careful when designing your APIs with std::shared_ptr).

    Once the dependency class is no longer used it's automatically destroyed by shared_ptr destructor.

    There are cases when shared_ptr owned objects are not destroyed (so called cyclic references). However, with constructor injection, cyclic dependencies aren't possible due to the specific well-defined order of construction.

    This works of course if no other injection methods are used across the application.

    A smart pointer has a small overhead but it isn't a real problem in the majority of cases.

    Further details:

    • Disadvantages of shared_ptr
    • GotW #91: Smart Pointer Parameters
    0 讨论(0)
提交回复
热议问题