mercredi 20 avril 2016

Interface method with interface parameters

I have two classes, Foo and Bar, and an Algorithm class that uses both.

class Foo {
    void method(Bar bar) {
        bar.otherMethod();
        ...
    }
}

class Bar {
    void method() {
        ...
    }

    void otherMethod() {
        ...
    }
}

class Algorithm {
    void run(Foo foo, Bar bar) {
        foo.method(bar);
        bar.method();
        ...
    }
}

The algorithm part (run method) is generic, and I want to be able to reuse it in other projects, involving classes analogue to Foo and Bar, which I know will each have the methods named method. However, I do not want to put the Bar.otherMethod at interface level (because it is not a generic functionality).

For this reason, I defined two interfaces:

interface IFoo {
    void method(IBar bar);
}

and

interface IBar {
    void method();
}

and changed the signature of Algorithm.run() into void run(IFoo foo, IBar bar), in order to use these interfaces.

The problem is that now, in the Foo class I have to make a cast in order to use specific aspects from the Bar class.

class Foo implements IFoo {
    void method(IBar bar) {
        (Bar)bar.otherMethod();
        ...
    }
}

In general, this cast is an indicator of bad design. Is there indeed a problem? What would be a better approach for my intention of having a generic Algorithm.run() method?

Aucun commentaire:

Enregistrer un commentaire