在Java中将函数式接口声明为变量可能有哪些缺点?
我一直在尝试用一而在Java函数式编程,并发现我开始喜欢使用的@FunctionalInterface从功能java.util.function包,如功能,BiFunctions,UnaryOperators,谓语,BiPredicates等代替简单的私有方法我类。我知道他们的应用程序更推荐作为参数传递给另一个函数,这就是我通常倾向于使用它们的方式,但我现在只是发现它们立即并且以某种方式更好。
事实上,我现在倾向于将其中一些声明为变量,然后在需要时在我的类中使用。
我似乎没有找到任何使用这些而不是简单方法的指南或缺点。
那么:以这种方式使用它们有什么缺点吗?
- 一个例子:
为什么更喜欢:
private boolean foo(final int a, final int b){
return a < b;
}
代替:
private final BiPredicate<Integer,Integer> foo = (a,b) -> a < b;
我在最近的项目中如何使用它们的一个例子:
private final BiFunction<BoardPosition, Pair<Integer, Integer>, BoardPosition> sumBoardPosWithPair = (pos,
pair) -> new BoardPositionImpl(pos.getX() + pair.getX(), pos.getY() + pair.getY());
private final Function<Pair<Integer, Integer>, UnaryOperator<BoardPosition>> unaryCreator = (
axis) -> (p) -> this.sumBoardPosWithPair.apply(p, axis);
/**
* If you need to call the fromFunction method twice for specular directions use
* this TriFunction specularNoLimitDirection instead.
*/
private final TriFunction<Piece, Vectors, Board, Set<BoardPosition>> specularNoLimitDirection = (piece, axis,
board) -> Stream.concat(
this.fromFunction(this.unaryCreator.apply(axis.getAxis()), piece, board,
board.getColumns() + board.getRows()).stream(),
this.fromFunction(this.unaryCreator.apply(axis.getOpposite()), piece, board,
board.getColumns() + board.getRows()).stream())
.collect(Collectors.toSet());
protected final Set<BoardPosition> fromFunction(final UnaryOperator<BoardPosition> function, final Piece piece,
final Board board, final int limit) {
/*
* The "function.apply" at the seed of the Stream.Iterate is used to skip the
* first element, that's itself, in fact a piece can't have as a possible move
* it's original position.
*/
final List<BoardPosition> positions = Stream.iterate(function.apply(piece.getPiecePosition()), function)
.takeWhile(board::contains)
.takeWhile(x -> board.getPieceAtPosition(x).isEmpty()
|| !board.getPieceAtPosition(x).get().getPlayer().equals(piece.getPlayer()))
.limit(limit).collect(Collectors.toList());
final Optional<BoardPosition> pos = positions.stream().filter(i -> board.getPieceAtPosition(i).isPresent()
&& !board.getPieceAtPosition(i).get().getPlayer().equals(piece.getPlayer())).findFirst();
/*
* The sublist excludes the last n-th element of the high-endpoint, for this
* reason we need to add 1.
*/
return pos.isEmpty() ? new HashSet<>(positions)
: new HashSet<>(positions.subList(0, positions.indexOf(pos.get()) + SINGLE_INCREMENT));
}
回答
您应该做最易读和最可维护的事情。如果将这些函数放在具有描述性名称的变量中感觉像是解决问题的一种可读且可维护的方式,那很好。这样的编程没有错。
您可能还喜欢的中间立场是将逻辑放在普通的静态方法中:
private boolean foo(final int a, final int b){
return a < b;
}
然后在需要时使用方法引用来引用它:MyClass::foo。这在行为上等同于您定义的 lambda。
有很多方法可以编写此代码。每个人都对“正确”的方法有自己的看法,但实际上有很多“正确”的方法。(还有一些不太正确的方法。)