gpt4 book ai didi

java - 在 Java 中通过 Lambda 修改本地对象状态的设计选择错误?

转载 作者:行者123 更新时间:2023-12-01 18:52:56 24 4
gpt4 key购买 nike

假设我有这个

Class1 instance = new Class1(); //this is "effectively final"
int [] arr = new int[]{1, 2, 3, 4, 5}; //array of ints

// modify "instance" with a lambda
Arrays.stream(arr).forEach(x -> instance.modifyInstanceStateWithNum(x));

此代码将起作用,因为 instance 实际上是最终的。然而,我想知道,这是否是一个错误的代码使用和一个糟糕的设计,因为根据我的理解,Lambda 通常是有效的?

替代方案是:

for(int num : arr){
instance.modifyInstanceStateWithNum(num);
}

这做了同样的事情,但它“感觉更正确。”

最佳答案

Streams in java are generally terser. In its strict sense they are supposed to encourage lesser mutability and thus not changing states of your object. However, otherwise both sequential streams and a for loop does the same thing. ref. TDD java

它有一些人们通常不会谈论的缺点。 for 循环在堆内存使用和 CPU 使用方面都是轻量级的。如果优先考虑更好的 cpu 速度和堆,通常不建议使用流。

作为自己编程的新手,我仍然更喜欢使用声明式编程风格,而无需明显显示控制流,事实上,它“有效”

In practise you are definitely allowed to modify the state of the instance but not technically the source of the stream. You aren't allowed to modify the data source during the execution of the stream function javase8.stream

所以基本上作为一个例子:这很好:基于您的代码:

Arrays.stream(arr).forEach(x -> instance.modifyInstanceStateWithNum(x));

但这样的事情不是:

List<Pojo> pojos; //some pojo
pojos.stream().forEach(pojo-> pojos.remove(pojo)); //THIS ISN'T RIGHT

总结一下你的疑问,这取决于你正在做的事情是否正确以及你觉得代码应该如何,并且更多地关注代码的可读性,效率,对于数千行代码我老实说更喜欢 lambda functions只要“它有效”并且任何人都可以轻松理解我尝试做的事情,就可以通过通用的 for 循环。

这也与面向 FP 的编程相一致,并且随着编程语言的发展,这一点似乎受到了尊重。

关于java - 在 Java 中通过 Lambda 修改本地对象状态的设计选择错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59701555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com