Reputation: 11277
When I write some API I try to avoid introducing new interfaces, and often this makes me want to use the guava interface "Function". For example rather than doing:
// a new interface
interface URILookup {
public URI lookup(Object o);
}
public class Some {
public Some(URILookup u){//...}
}
I replace URILookup
with Function<Object,URI>
and document the use in the constructor for Some
.
I feel that this could lead later to unreadable code, as I could make everything a Function.. What criteria are you applying to find a balance between such "general" interfaces vs introducing a new type?
Upvotes: 2
Views: 182
Reputation: 127761
I'm using a very simple rule for this.
When you write code which should perform some generic action (for example, Guava's Iterables.transform()
applies some function to elements of an iterable; it does not care at all what exactly this function does or should do), you use generic interfaces, like Function<F, T>
.
When you write code which has any idea of what "function" passed to it should do (like in your example - Some
class expects that its constructor argument should somehow get a URI from an object), it would be more natural to create a distinct interface for it.
This can be reformulated more formally. If you need to use concrete instantiation of a generic type, i.e. not Function<F, T>
for arbitrary F
and T
(like Iterables.transform()
), then you'd better create separate interface like your URILookup
instead of using Function<Object, URI>
. Otherwise you should stick with generic interfaces.
Of course, there are exceptions in boundary cases, for example, when the code is generic in spirit but not really generic in implementation sense (e.g. something like Function<T, Integer>
) or when you need compatibility with 3rd-party API. Then your decision will depend on concrete details of the case.
BTW, this is true (in my opinion) for Java, but it is not quite true for other JVM languages like Scala, which have function type built-in. If the language supports functions natively, you should by all means embrace this support.
Upvotes: 4