vendredi 30 décembre 2016

How to avoid passing a context down a bunch of method calls?

suppose I have a problem that, intuitively, is best solved using recursion.

I'm also trying to use dependency injection to make code testeable:

class Foo {

    Bar bar;

    Foo(Bar bar) {
        this.bar = bar;
    }

    ResultType doFoo() {
        ...stuff...
        bar.doBar();
    }

}

class Bar {

    Baz baz;

    Bar(Baz baz) {
        this.baz = baz;
    }

    ResultType doBar() {
        ...stuff...
        baz.doBaz();
    }
}

class Baz {

    Foo foo;

    Baz(Foo foo) {
        this.foo;
    }

    ResultType doBaz() {
        if (foo is needed) {
            foo.doFoo(smaller problem)
        } else {
            ...stuf...
        }
    }
}

Now, if Baz wan't dependant on Foo, you could just do something like:

Foo foo = new Foo(new Bar(new Baz()));

Baz can take any Foo, so it is no problem if it just gets the one at the top, thus forming a loop. (The JVM can take care of loops IIRC). Only Baz can determine if it needs Foo.

What is the cleanest way to get a Foo into Baz in a way that is testeable?

Is adding a Foo parameter to doBaz() my only option? (Implying that Foo needs to pass "this" to doBar, which then passes it to doBaz, etc... or is there a better way?)

Aucun commentaire:

Enregistrer un commentaire