How good is it to use additional constructors just for validation?

Currently I need to write SecondClassand decided to write using such a solution, because otherwise it would be impossible to verify.

@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 did not like my way of solving this issue and preferred the implementation SecondClassas follows:

@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 do not agree with this decision, because I believe that it Randomis a necessary part of this class, it will not be changed at runtime, and this setter is needed only for testing purposes, and therefore I prefer a solution with two constructors.

We also created such a constructor:

@Autowired(required = false)
public SecondClass(FirstClasss firstClass, Random random) {
    this.random = (random == null ? new Random() : random)
    ...
}

But in fact, more components have been added to the constructor, so it would be preferable if all of them were necessary.

, - ? ?

+4
3

spring . , . , , , , .

, , , ReflectionUtils.setField

+2

SecondClass , , unit-test , random.
API , .
API , .

random , SecondClass, SecondClass. random SecondClass.

+1

, . , , - , , . , random , , . , , ( ). , .

, : , null, ( ) .

So, if you need this constructor SecondClassfor verification, go ahead and add it. Because if the class is not checked, it is also not executable . Testing is the right way to ensure that a class can be useful.

+1
source

Source: https://habr.com/ru/post/1651082/


All Articles