0
public interface DataAdapter {

    int solve(int a, int b, int c)
}

Now i have multiple classes which implements this interface something like :

public class DataAdapterImplA implements DataAdapter {

    int solve(int a, int b, int c) {

        return ...
    }
}

public class DataAdapterImplB implements DataAdapter {

    int solve(int a, int b, int c) {

        return ...
    }
}

and similarly multiple others ...

Now i am adding one more implementing class but with one less parameter in the existing method signature ..something like below :

public class DataAdapterImplF implements DataAdapter {

    int solve(int a, int b) {

        return ...
    }
}

So , question here is how to go about this :

  1. Should i override the existing solve(int, int, int) method only & in my method body i can ignore this and won't use it at all ?

  2. should i create a default method solve(int, int) in the interface & override that in my new implementation class ?

or any other better & clean solution ?

  • There's no generic answer to this. If it's a method only applicable to `DataAdapterImplF` then that's where it should live. If the `DataAdapter`s live in a list and you need to be able call it regardless of implementation then it should be in the interface, with the caveat that calling in on non-`DAIF`s will always be non-sensical--you could implement a default no-op, but this leads to cognitive overhead because it may not be obvious it's a no-op for everything except the `F`s. – Dave Newton May 17 '23 at 15:01
  • My doubt is that how come the `DataAdapterImplF` is not declared abstract? If the arguments are your problem then you can better encapsulate them into a class and use its reference as the method argument. Inside each implementation you can decide which and all attributes to be used. – Arun Sudhakaran May 17 '23 at 16:12

1 Answers1

0

So I think the problem lays in the question you have asked. Interfaces are a very explicit contract, and in your case the contract is:

"You give me three integers and I can calculate you some solution which will also be an integer."

Thus, it does not make sense to ask how one would adapt some operation that only takes two integers to this interface. Those are just different things. What you could do is redefine your contract and say:

"You give me two integers a, b and a third optional integer c, and I can calculate you some solution which will also be an integer."

This contract would then look like this:

public interface DataAdapter {

    int solve(int a, int b, Optional<Integer> c)
}
yezper
  • 693
  • 3
  • 12
  • [Why should Java 8's Optional not be used in arguments](https://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments) – jaco0646 May 18 '23 at 21:29