I have a set of functions defined like this:
public void foo1(int a, int b){
if (a > b){
c++;
}
}
public void foo2(int a, int b){
if (a > b && b = 7){
c++;
}
}
public void foo3(int a, int b){
if (a >= b){
c++;
}
}
Which only differ in their conditions for a and b. Is there a way to contain these as one function, where I can set the condition as a variable? Or something similar?
EDIT: Please note this is a trivial example, I want to know if it’s possible to pass a condition to a function
For a general solution, you can define an interface:
Then define your function:
Then you can define various
Predicateobjects:and pass whichever one is appropriate to
foo().Alternatively, you can look at making use of the
Callableinterface usingBooleanas the type parameter. (It can’t take arguments, however, so it doesn’t exactly fit your pattern.)