I like programming in a functional style. But it occurred to me that passing functions as arguments may sometimes create stronger coupling between components than would be created with non-function argument passing.
For instance, in the (contrived) example below: A, B, and C are coupled by the output type of C's function argument, by the type of C's int argument, and also by the arity and input type of C's function argument. If A wants to change its function to a BiFunction, B and C must both change.
public class Functional {
public void A() {
C(i -> String.valueOf(i + 2), 123);
}
public void B() {
C(i -> String.valueOf(i + 1), 123);
}
private String C(Function<Integer, String> f, int a) {
int len = String.valueOf(a).length();
return f.apply(len);
}
}
Contrast this with an example where A and B compute the result of the function up front, then pass the String result and the second int argument to C. Here A, B, and C are coupled only in two places – the two arguments to C. The function to compute the first argument is free to change.
Obviously passing functions has its place, but it seems that this kind of problem can compound and create rigid code when things get more complex. I'd love to hear any rules of thumb you use to decide when coupling in this way is ok vs. not.
C
offers a functionality and defines the prerequisites;A
doesn’t have to “want” anything here. 2) If there’s no requirement forC
to have a function as parameter type, it shouldn’t demand to get a function. If the offered functionality demands it, well, then it’s out of discussion. In your example, as contrived as it is, it is impossible for the callers to compute the result of the function up-front. But they could afterwards.