3

I have several interfaces all with only a single method and they are all very similar. I know it works, but should I or should I not group them like this:

public class InterfaceGroup {
    public interface Type1 {
        public void method(int a);
    }
    public interface Type2 {
        public void method(String s);
    }
    public interface Type3 {
        public void method();
    }
}

And then reference them externally as InterfaceGroup.Type1.

rtheunissen
  • 7,347
  • 5
  • 34
  • 65

3 Answers3

6

Yes, it is sometimes helpful to have such a design. For example, it is the choice for Map.Entry in Java standard library.

The blemish on such a design, though, is that you define a type that doesn't play the role of a type, and it is actually never appropriate to implement it. If I found out that in a library I use such a type exists for no other reason than to reduce the number of source code files, I'd be at least slightly annoyed :-) On the other hand, when I'm writing code whose scope of visibility is just within the implementation, I use such tricks remorselessly.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • there is no grouping of multiple interfaces in Map, only one nested interface – lbalazscs May 29 '13 at 12:58
  • @lbalazscs I see this as close enough to establish an analogy. – Marko Topolnik May 29 '13 at 12:59
  • @lbalazscs My bad, I wrote too fast, I just checked and you're right. – Djon May 29 '13 at 13:03
  • I think the analogy is not strong. The `Map` interface is a real interface, not merely a container for other interfaces. `Map.Entry` is a type used by several of `Map`s methods, and it has little meaning outside the context of a `Map`. This is not the case in the OP's proposal. – Arend May 29 '13 at 16:01
  • @arend OP: "Is it at all acceptable to have nested public interfaces?" Me: yes, see for example Map.Entry – Marko Topolnik May 29 '13 at 16:53
  • @Marko You're right of course, having nested interfaces can make a lot of sense - but I have yet to see a good example where the outer type is not itself expected to be instantiated, which is what OP seems to be asking about. – Arend May 29 '13 at 17:11
  • @arend As you were writing your comment, I was expanding my answer with the same thought :-) – Marko Topolnik May 29 '13 at 17:17
0

I thought TimeUnit had that too but they are enumerations, I found this post that could maybe explain why it can be done.

Community
  • 1
  • 1
Djon
  • 2,230
  • 14
  • 19
0

There is no technical reason against this, but I'm not sure this makes for understandable code. Programmers will typically expect that an interface is there to be implemented, which is not the case in your proposition.

Note that the number of source files may be smaller this way, but the number of class files will be larger, as both InterfaceGroup and all its nested types will be compiled to a separate class file.

Arend
  • 2,363
  • 1
  • 18
  • 18