-1

I have seen examples online about the Single Responsible principle.
They always use IoC/DI as an example.
They move the code from class A to class B and pass class B as reference.

See code below:

class B {}
class A {
  b;
  // reference used
  constructor(b) {
    this.b = b;
  }

  doStuff() {
    ...  
    this.b.doSomeOtherStuff();
  }
}

But the Single Responsible principle is about to increase the coherence.
Theoretically the code above would also follow the Single Reponsible principle without
passing down a reference to class B, right?

Like this:

class B {}
class A {
  // no reference
  constructor() {
    this.b = new B;
  }

  doStuff() {
    ...  
    this.b.doSomeOtherStuff();
  }
}
Znar
  • 193
  • 12

1 Answers1

0

In the book Clean Code by Robert C. Martin there is an example reagarding the SRP where he uses only composition.
So I would say yes, Singe Responsible Priciple is valid without IoC/DI.
In the example below hes directly creating an instance of the LinkedList.

public class Stack {
    private int topOfStack = 0;

    // creating a direct instance here
    List < Integer > elements = new LinkedList < Integer > ();

    public int size() {
        return topOfStack;
    }

    public void push(int element) {
        topOfStack++;
        elements.add(element);
    }

    public int pop() throws PoppedWhenEmpty {
        if (topOfStack == 0)
            throw new PoppedWhenEmpty();
        int element = elements.get(--topOfStack);
        elements.remove(topOfStack);
        return element;
    }
}
Znar
  • 193
  • 12