3

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?

lawonga
  • 139

1 Answers1

1

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.

candied_orange
  • 119,268