Empty interface to combine multiple interfaces
Posted
by
user1109519
on Programmers
See other posts from Programmers
or by user1109519
Published on 2013-10-16T11:30:19Z
Indexed on
2013/10/17
16:23 UTC
Read the original article
Hit count: 281
java
|object-oriented
Suppose you have two interfaces:
interface Readable {
public void read();
}
interface Writable {
public void write();
}
In some cases the implementing objects can only support one of these but in a lot of cases the implementations will support both interfaces. The people who use the interfaces will have to do something like:
// can't write to it without explicit casting
Readable myObject = new MyObject();
// can't read from it without explicit casting
Writable myObject = new MyObject();
// tight coupling to actual implementation
MyObject myObject = new MyObject();
None of these options is terribly convenient, even more so when considering that you want this as a method parameter.
One solution would be to declare a wrapping interface:
interface TheWholeShabam extends Readable, Writable {}
But this has one specific problem: all implementations that support both Readable and Writable have to implement TheWholeShabam if they want to be compatible with people using the interface. Even though it offers nothing apart from the guaranteed presence of both interfaces.
Is there a clean solution to this problem or should I go for the wrapper interface?
UPDATE
It is in fact often necessary to have an object that is both readable and writable so simply seperating the concerns in the arguments is not always a clean solution.
UPDATE2
(extracted as answer so it's easier to comment on)
UPDATE3
Please beware that the primary usecase for this is not streams (although they too must be supported). Streams make a very specific distinction between input and output and there is a clear separation of responsibilities. Rather, think of something like a bytebuffer where you need one object you can write to and read from, one object that has a very specific state attached to it. These objects exist because they are very useful for some things like asynchronous I/O, encodings,...
© Programmers or respective owner