What is the best practice of exporting function objects in Java?

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

+6
source share
4 answers

It is instructive to look at the upcoming functional interfaces of Java 8

The Java 8 class library has a new package, java.util.functions, which contains several new functional interfaces. Many of them can be used with the collection APIs.

If you follow the patterns presented here, you will have a functional interface (an interface that supports one method) and an implementation without participants. A function object should not call any methods in the method arguments that could change their state (i.e., exhibit side effects). Unfortunately, you cannot provide this - you must rely on an agreement to do this.

+5
source

Java is an object-oriented programming language, so use a strategy development template.

+3
source

Java8 should have lambdas to facilitate the creation of functional interface implementations. Before Java8, you can see what the guava library offers: Functional Explanation

Here is an excerpt from the documentation:

Guava provides two main "functional" interfaces: A function that uses one method B (input A). It is usually assumed that function instances are referentially transparent - without side effects - and must be consistent with equal, i.e. a.equals (b) implies that function.apply (a) .equals (function.apply (b)). A predicate that has a single boolean apply (T input) method. Predicate instances are expected to be free of side effects and consistent with equals.

+2
source

Well after the comments, here is the answer: There is no simple and convenient way to pass a function.

In most cases, you declare an inner class that implements the interface, for example, Comparator : http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

The fact that functions cannot be passed as parameters has caused a lot of so-called design patterns, where you go through object classes / interfaces that declare the presence of these functions.

As others have mentioned, life will be a little easier with Java 8.

0
source

All Articles