Home » Java » java – Should I use dependency injection in a Helper class?-Exceptionshub

java – Should I use dependency injection in a Helper class?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a package with various classes and a helper class which has various methods (being used by various other classes in the same package), but one method uses a package ‘A’ and I am currently injecting it using constructor.

But it being a helper class I think it shouldn’t have a constructor and all the methods should be static so that other classes can call these methods as say

Helper.method1();

So should I move the method dependent on package ‘A’ back to all the classes using it to avoid using dependency injection or should I keep it as it is.

class Helper{

private final A a;

@Inject
Helper(final A a){
        this.a = a;
}

}

How to&Answers:

Move the methods to A and inject A instead of Helper

You’re already injecting Helper in some places. And its only dependency is A. Since it’s a helper, it’s kind of known that you need to use A, so refactor the Helper class to move the specific method to A and replace the Helper dependencies to A ones:

Before

A.java

class A {
  void doSomethingSmall() {
    // 
  }
}

Helper.java

class Helper {
  @Inject A a;
  void doSomethingBig() {
    a.doSomethingSmall();
  }
}

Usage.java

class Usage {
  @Inject Helper helper;
  void doSomethingBigger() {
    helper.doSomethingBig();
  }
}

After

A.java

class A {
  void doSomethingSmall() {
    // 
  }
  void doSomethingBig() {
    a.doSomethingSmall();
  }
}

Usage.java

class Usage {
  @Inject A a;
  void doSomethingBigger() {
    a.doSomethingBig();
  }
}

Which is neater? Before or after? Which is the simpler?