Java – Void method refactoring with multiple checks

Void method refactoring with multiple checks… here is a solution to the problem.

Void method refactoring with multiple checks

I have this method :

public void validate(param1, pararm2, param3 ...) {
    if(check1)
        add error
        return
    if check2
        add error
        return
    getDbObject
        check3
        exception
            return

There is another use case, in addition to the above checks, if check1 and check2 pass, then the db object should be returned after check3.
What should be the best practice to implement it?

Should I write a new method that does the same check and returns the db object after check3, or add more parameters and simplify the existing method?

The best practice I’ve read is to have up to 5 parameters, so if we add more parameters, eventually the first method call will have 8-9 parameters
If we reduce the number of arguments, then each call requires more checks (if statements), which also violates the basic principles of OOP.
So is there an alternative?

Solution

I would override to use an exception, deliberately returning null doesn’t help the caller, it might look like this:

public DbObjectType validate(param1, param2, ...) throws Check1FailedException, Check2FailedException, Check3FailedException {

check1();
    check2();
    check3();

return getDbObject();
}

private check1() throws Check1FailedException() {
    DoCheck and throw Exception if failed
}

private check2() throws Check2FailedException() {
    DoCheck and throw Exception if failed
}

private check3() throws Check3FailedException() {
    DoCheck and throw Exception if failed
}

Related Problems and Solutions