2 ms·
I've ended up doing something a bit like this in Java, but rather than using interfaces, i do it with a suite of lambdas: String perform(Supplier<String> s
by twic 9y ago
I've ended up doing something a bit like this in Java, but rather than using interfaces, i do it with a suite of lambdas:
String perform(Supplier<String> speaker) {
return speaker.get();
}
This is a poor example, but that's what's in the article. Better might a method which is going to do some message broadcasting or something. With interfaces:
interface Broadcaster<T> {
void send(T value);
void reset();
void close();
}
void pump(Source<T> source, Broadcaster<T> broadcaster) {
// this logic is nonsense but hopefully it makes the point
T value;
while ((value = source.poll()) != null) {
try {
broadcaster.send(value);
} catch (Exception e) {
broadcaster.reset();
}
}
broadcaster.close();
}
You might write:
void pump(Source<T> source, Consumer<T> send, Runnable reset, Runnable close) {
// still nonsense
T value;
while ((value = source.poll()) != null) {
try {
send.accept(value);
} catch (Exception e) {
reset.run();
}
}
close.run();
}
If you had an actual Broadcaster, this is simple to call:
pump(source, broadcaster::send, broadcaster::reset, broadcaster::close);
And if you don't have an actual Broadcaster, or if there is no such interface, it still simple to call, because you write references to whatever methods you do have. They could be on different objects. They could be lambdas. They could be no-op lambdas if you don't care about one of the events. In a unit test they could be:
List<String> sent = new ArrayList<>();
pump(source, sent::add, sent::clear, () -> sent.add("CLOSED"));
Etc.