jeudi 7 février 2019

Validation logic best practices and design patterns

I have a class that performs some sort of (potentially redundant) validation logic on some number of arguments in the functions it contains. To demonstrate, I have the following Controller and ValidationHelper classes:

class ValidationHelper {
    void validateA(int a, String b) { /*...*/ }

    void validateB(int c, double d, String e) { /*...*/ }

    void validateC(int f) { /*...*/ }
}

class Controller {
    private ValidationHelper helper;

    void foo(int a, String b, int f) {
        this.helper.validateA(a, b);
        this.helper.validateC(f);
        // .. Rest of foo
    }

    void bar(int a, String b, int c, double d, String e) {
        this.helper.validateA(a, b);
        this.helper.validateB(c, d, e);
        // .. Rest of bar
    }
}

I'm wondering if there is a way to improve this validation architecture so any addition in validation logic wouldn't be as intrusive as the current implementation, and have validation become much cleaner? If this isn't achievable, would you have any suggestions if all the functions had the exact same validation statements? (e.g. both foo() and bar() containing ONLY this.helper.validateA(a,b)):

class Controller {
    void foo(int a, String b, int f) {
        this.helper.validateA(a, b);
        // .. Rest of foo
    }

    void bar(int a, String b, int c, double d, String e) {
        this.helper.validateA(a, b);
        // .. Rest of bar
    }
}

Aucun commentaire:

Enregistrer un commentaire