mercredi 29 août 2018

Implement interface in methods (the best practice)

I have some callback interace:

public interface FooCallback {
    boolean doSomething(Foo fooArg);
}

which is implemented as anonymouos block in methods in service layer:

public void methodA(Bar barArg) {
    // some bussiness logic like parsing Foo object from Bar for example

    FooCallback cb = new FooCallback() {
        @Override
        public boolean doSomething(Foo fooArg) {
            // some calculation with fooArg and barArg and return boolean value
        }
    }
    saveBar(barArg, cb);
}

saveBar is method which is also in that class and is using to save Bar object into database depends on result of doSomething method of FooCallback;

public void saveBar(barArg, cb) {
    // get Foo object from database

    if (cb.doSomething(fooFromDB)) {
        // save barArg into DB
    } else {
        // antother logic
    }
}

I have a lot of methods like methodA in my service class. Anonyme code block is also bad testable. Can you tell me what is the best practice with similar implementation? I figure out move content from doSomething to another method, but it means every method will be self methodCallback. What do you think? I am using java. Thank you in advice.

Aucun commentaire:

Enregistrer un commentaire