HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Having two abstract (static inner) classes within the interface they implement

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
abstracttheimplementhavingwithininterfacetwoclassesinnerthey

Problem

Is it wrong? Should I have these 2 classes in separate files?

public interface InternetDependentFlow {
    void onInternetIsAvailable();
    void onInternetIsNotAvailable();

    public static abstract class InternetIsAvailable implements InternetDependentFlow {
        @Override
        public final void onInternetIsNotAvailable() {
            // do nothing
        }
    }

    public static abstract class InternetIsNotAvailable implements InternetDependentFlow {
        @Override
        public final void onInternetIsAvailable() {
            // do nothing
        }
    }
}


Where I use this interface and the classes:

```
public class InternetDependentFlowTask extends AsyncTask {

private final Context context;
private InternetDependentFlow[] internetDependentFlows;

public static void run(Context context, InternetDependentFlow... internetDependentFlows) {
InternetDependentFlowTask internetDependentFlowTask = new InternetDependentFlowTask(context);
internetDependentFlowTask.execute(internetDependentFlows);
}

public InternetDependentFlowTask(Context context) {
this.context = context;
}

@Override
protected Boolean doInBackground(InternetDependentFlow... internetDependentFlows) {
this.internetDependentFlows = internetDependentFlows;
return NetworkUtils.isInternetAvailable(context);
}

@Override
protected void onPostExecute(Boolean internetIsAvailable) {
super.onPostExecute(internetIsAvailable);
InternetDependentFlowChooser flowChooser = (internetIsAvailable == Boolean.TRUE)
? INTERNET_IS_AVAILABLE_FLOW_CHOOSER : INTERNET_IS_NOT_AVAILABLE_FLOW_CHOOSER;
for (InternetDependentFlow internetDependentFlow : internetDependentFlows) {
if (internetDependentFlow != null) {
flowChooser.choose(internetDependentFlow);
}
}
}

private static interface InternetDependentFlowChooser {
vo

Solution

As a matter of principle,
an interface definition should not include implementation.
These abstract classes are by definition implementations,
even though they are mostly empty and seemingly harmless.
As such,
yes, you should move the inner abstract class definitions outside.

There are different kinds of "outside":

  • Outside of the class but in the same file



  • Outside of the class in other file(s)



If they are in the same file, they cannot be public.

If they are in different files, they can be public.

Either way, to achieve the cleanest separation of interface and implementations,
I recommend to move them to different file(s).

Context

StackExchange Code Review Q#69480, answer score: 7

Revisions (0)

No revisions yet.