What is the best practice of creating function objects
(a stateless object that exports a single method which works on other objects ) in Java ?

- 26,489
- 43
- 149
- 227
-
1You could get some inspiration by looking at the `Comparator` interface: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html. This is an open-ended question. – Christophe Roussy Feb 25 '13 at 13:30
-
2possible duplicate of [What's the nearest substitute for a function pointer in Java?](http://stackoverflow.com/questions/122407/whats-the-nearest-substitute-for-a-function-pointer-in-java) – Raedwald Feb 25 '13 at 13:32
4 Answers
It's instructive to look at the forthcoming Java 8 functional interfaces
The Java 8 class library has a new package, java.util.functions, which contains several new functional interfaces. Many of these can be used with the Collections API.
If you follow the patterns exhibited here, you'll have a functional interface (an interface supporting one method) and an implementation with no members. Your function object shouldn't call any methods on the method arguments that could change their state (i.e. exhibit side-effects). Unfortunately you can't enforce that - you have to rely on convention for this.

- 268,207
- 37
- 334
- 440
-
-
I believe languages enforcing immutability could enforce this. Perhaps also C++ and its strong const semantics, although I'd prefer not to be quoted on this! – Brian Agnew Feb 25 '13 at 13:44
Java is an Object Oriented programming language, so use the Strategy design pattern.

- 46,613
- 43
- 151
- 237
-
1Whilst strategies work here, there's no need for a strategy object to implement only one method, as a functional object would require – Brian Agnew Feb 25 '13 at 13:43
Java8 should have lambdas to ease the creation of functional interface implementations. Before Java8 you may look at what the guava library offers: Functional Explained
Here is an excerpt of the documentation:
Guava provides two basic "functional" interfaces: Function, which has the single method B apply(A input). Instances of Function are generally expected to be referentially transparent -- no side effects -- and to be consistent with equals, that is, a.equals(b) implies that function.apply(a).equals(function.apply(b)). Predicate, which has the single method boolean apply(T input). Instances of Predicate are generally expected to be side-effect-free and consistent with equals.

- 12,614
- 4
- 38
- 46
Ok after commenting, here is an answer: There is no easy/convenient way to pass a function.
Most of the time you will declare an inner class which implements a interface like for example, the Comparator
:
http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
The fact that functions cannot be passed as parameters gave rise to a lot of so called design patterns, where you pass around objects classes/interfaces which declare having those functions.
As mentioned by others life will get a little easier with Java 8.

- 16,299
- 4
- 85
- 85