T_T
T_T

Reputation: 437

Functions as Arguments: Strong Coupling?

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.

Upvotes: 0

Views: 229

Answers (2)

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49008

If you're replacing a simple value with a function argument, you're doing something seriously wrong. Functions should only be replacing something with tighter coupling, usually an application-specific Interface.

Upvotes: 2

Nazarii Bardiuk
Nazarii Bardiuk

Reputation: 4342

In your example I would recommend to follow principle of Single Responsibility

Gather together the things that change for the same reasons. Separate those things that change for different reasons.

So choosing in what way to couple A,B with C depends on why they are going to change.


Another principle that comes to mind from your example is Rule of least power

Given a choice of solutions, pick the least powerful solution capable of solving your problem

in your simplified example function C doesn't need a function as an argument. That function can be called in A,B side.

Upvotes: 3

Related Questions