新关键字的副作用
Side effect of the new keyword
有人说 new
关键字有副作用是什么意思? SSE上有评论给了答案,但是我没看懂评论
Clearly the factory methods in the question call new, they have side
effects. However, that side effect is identical to just calling a
public constructor, so they are no more difficult to test than the
latter.
问题与使用静态方法构造具有私有构造函数的对象有关。使用 new
关键字有什么副作用?我应该如何创建我的对象?
Clearly the factory methods in the question call new
, they have side effects. However, that side effect is identical to just calling a public constructor, so they are no more difficult to test than the latter.
他是说副作用是创建了一个新的对象;但是在静态工厂方法中调用 new
的副作用与直接调用 new
没有什么不同。
"side effect",程序员通常指的是函数所具有的任何效果都没有完全包含在函数本身中。基本上,如果 "world" 由于调用函数而发生变化,它就会产生副作用。如果您可以根据需要多次调用该函数并且 "world" 永远不会改变,它就不会。
快速示例:System.out.println("Hello world!");
执行 IO,因此它有副作用。 Math.min(5, 10)
只是 returns 5
对任何东西都没有任何额外的影响,因此它没有副作用。
在您的示例中,您调用的函数除了用 new
构造一个新对象外似乎没有做太多事情。看看这个例子:
static Foo createFoo() {
return new Foo();
}
// ...
while (true) {
createFoo();
}
我们马上看到的明显副作用是内存分配。调用 createFoo()
将导致堆内存分配。可以说 Math.min(5, 10)
也会消耗堆栈上的内存,但是如果您自己没有明确分配 return 值,那么内存消耗是暂时的并且完全包含在函数的执行中,此时调用者是谁导致内存消耗。堆分配比函数调用长,直到它最终被垃圾收集器清理。
我想当你在 Java 中谈论 "no side effects" 时,我想这不是很明确,因为几乎所有事情都可能导致堆分配,通常可以考虑对象在你离开时已经消失删除他们的引用,让 GC 稍后清理它。
有人说 new
关键字有副作用是什么意思? SSE上有评论给了答案,但是我没看懂评论
Clearly the factory methods in the question call new, they have side effects. However, that side effect is identical to just calling a public constructor, so they are no more difficult to test than the latter.
问题与使用静态方法构造具有私有构造函数的对象有关。使用 new
关键字有什么副作用?我应该如何创建我的对象?
Clearly the factory methods in the question call
new
, they have side effects. However, that side effect is identical to just calling a public constructor, so they are no more difficult to test than the latter.
他是说副作用是创建了一个新的对象;但是在静态工厂方法中调用 new
的副作用与直接调用 new
没有什么不同。
"side effect",程序员通常指的是函数所具有的任何效果都没有完全包含在函数本身中。基本上,如果 "world" 由于调用函数而发生变化,它就会产生副作用。如果您可以根据需要多次调用该函数并且 "world" 永远不会改变,它就不会。
快速示例:System.out.println("Hello world!");
执行 IO,因此它有副作用。 Math.min(5, 10)
只是 returns 5
对任何东西都没有任何额外的影响,因此它没有副作用。
在您的示例中,您调用的函数除了用 new
构造一个新对象外似乎没有做太多事情。看看这个例子:
static Foo createFoo() {
return new Foo();
}
// ...
while (true) {
createFoo();
}
我们马上看到的明显副作用是内存分配。调用 createFoo()
将导致堆内存分配。可以说 Math.min(5, 10)
也会消耗堆栈上的内存,但是如果您自己没有明确分配 return 值,那么内存消耗是暂时的并且完全包含在函数的执行中,此时调用者是谁导致内存消耗。堆分配比函数调用长,直到它最终被垃圾收集器清理。
我想当你在 Java 中谈论 "no side effects" 时,我想这不是很明确,因为几乎所有事情都可能导致堆分配,通常可以考虑对象在你离开时已经消失删除他们的引用,让 GC 稍后清理它。