Say... you're trying to write a networkCallback code in java:

public interface NetworkCallback {
    void onNetworkResult1(Object object);
    void onNetworkFailure(Object object);

you want to use it, but you sometimes have two network results:

public interface NetworkCallback2 implements NetworkCallback {
    void onNetworkResult2(Object object);

and sometimes, you might have three:

public interface NetworkCallback3 implements NetworkCallback2 {
    void onNetworkResult3(Object object);

Is this considered bad practice? What are the better alternatives?

  • 1
    When are onNetworkResultX methods called? If you call different methods for different result types, you can create a class hierarchy for callback method parameters. – Q Q Jan 27 '17 at 6:18
  • 1
    The most tidy solution would be to just call the one callback once for each result. You could pass a collection of results but you would not gain much performancewise. You might want to know how many results you got in one roundtrip though or you would need all to render the same web page anyway, in which case passing the results as one package may be the way to go. – Martin Maat Jan 27 '17 at 6:25
  • 5
    We need more details about how those interfaces would be implemented and used. Will all 3 be used at the same time, or is this some kind of evolution of the program? Is it necessary that all those interfaces be implemented by single class? – Euphoric Jan 27 '17 at 7:05
  • 1
    What will you do when you will have cases with 10 network results? – mgoeminne Jan 27 '17 at 8:35
  • 1
    Can you elaborate on why you cannot solve this by invoking the same callback multiple times? – edalorzo Jan 27 '17 at 13:44

Better alternatives come with these features:

  • Better names than NetworkCallback3 and onNetworkResult2. A name should make clear what belongs in the interface and what doesn't. I've no idea why onNetworkResult3 doesn't belong in NetworkCallback2. If you tell me it's the number I'll beat you with the magic number stick.

  • A polymorphic solution would reuse a onNetworkResult() method. Rather than using methods with different names you'd be using different objects that each had a method with the same name and signature, each with a different implementation. As well as the implementers of NetworkCallback, the passed object could be polymorphic as well.

  • Interface inheritance would be used to add truly new features. Not different flavors of old features.

The most critical mistake being made here is the author of this code is only looking at the problem structurally. If you're going to ignore semantics you might as well program in machine code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.