Currently I needed to write SecondClass
and decided to write using this kind of solution because otherwise it wouldn't be testable.
@Component
public class FirstClass {
public void doStuff() {
System.out.println("First Class stuff!");
}
}
@Component
public class SecondClass {
private final Random random;
private final FirstClass firstClass;
@Autowired
public SecondClass(FirstClass firstClass) {
this(new Random(), firstClass);
}
public SecondClass(Random random, FirstClass firstClass) {
this.random = random;
this.firstClass = firstClass;
}
public void doOtherStuff() {
firstClass.doStuff();
System.out.println("Second Class stuff " + random.nextInt(10));
}
}
My colleagues didn't liked my way of solving it and preferred implementation of SecondClass
like this:
@Component
public class SecondClass {
private Random random;
private final FirstClass firstClass;
@Autowired
public SecondClass(FirstClass firstClass) {
this.random = new Random();
this.firstClass = firstClass;
}
public void doOtherStuff() {
firstClass.doStuff();
System.out.println("Second Class stuff " + random.nextInt(10));
}
public void setRandom(Random random) {
this.random = random;
}
}
I disagree with this kind of solution because I think that Random
is the necessary part of this class, it wont be changed in the run time and that setter is only necessary for testing purposes and that's why I prefer solution with two constructors.
We also came up with this kind of constructor:
@Autowired(required = false)
public SecondClass(FirstClasss firstClass, Random random) {
this.random = (random == null ? new Random() : random)
...
}
But there is actually more components injected in the constructor so it would be preferable if all of them would have been required.
I'm interested if anybody here had this kind of experience before? What do you think about this case and if there is any better way of solving this problem?