BlackHatSamurai
BlackHatSamurai

Reputation: 23483

Advantage of Nested Interface Inside Class When Using Listeners

I'm confused on why you would want to use an interface nested within a class. I know that there are a couple posts that touch on this subject, but I'm more interested in how they are beneficial when using a listener.

I was reading about nested interfaces, and one post talked about it being an advantage when working with listeners. Unfortunately, they did not expand on the why. A current project I'm working on has a class that looks something like:

public class Manager extends BaseManager{

   public interface FollowedTopicListener extends BaseListener{
      void onLoadFollowedTopics(List<Tag> tags);
   }

       public interface FollowTopicsListener extends BaseListener {
        void onTopicsFollowed();
    }

    public interface UnFollowTopicsListener extends BaseListener {
        void onTopicsUnFollowed();
    }
    ...
}

I'm wondering what type of advantage this creates when referring to listeners. Also, why not just create a single listener. Something like:

public class Manager extends BaseManager{

    public interface FollowUnfollowTopicsListener extends BaseListener {
        void onLoadFollowedTopics();
        void onTopicsFollowed();
        void onTopicsUnFollowed();
    }
    ...
}

Why would I want to use this as opposed to a traditional interface?

Upvotes: 0

Views: 519

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

Being nested makes it very clear that they're closely related to Manager, and used to listen on events fired by the Manager. I would still prefer them as top-level interfaces, in the same package as the Manager class. Making them nested could also be a (bad) cure for many listeners having the same name but used in different contexts.

Making three different interfaces is helpful for two reasons:

  • it doesn't force you to provide dummy implementations of two methods when you're only interested in one kind of event
  • it makes the interface a functional interface, which can thus be implemented as a lambda expression or method reference

Upvotes: 3

Related Questions