正如我一直理解的那样,对程序状态(或与 IO 相关的任何事情)的任何更改都是副作用。更改是发生在全局变量中还是发生在调用该方法的对象的私有(private)字段中都没有关系。因此,所有不返回任何内容的方法要么什么都不做,要么有副作用。我的困惑来自我们大学的一位讲师(他仍然是学生,因此还不是无所不知的;))告诉我二传手没有副作用。
最佳答案
你的导师搞错了。对于没有将整篇文章粘贴到此处的 SO 编辑表示歉意,这就是 Wikipedia 必须说的:
http://en.wikipedia.org/wiki/Side_effect_(computer_science)
金钱报价#1:
In computer science, a function or expression is said to have a side effect if, in addition to producing a value, it also modifies some state or has an observable interaction with calling functions or the outside world.
金钱报价#2:
In the presence of side effects, a program's behavior depends on past history; that is, the order of evaluation matters.
非 NOP setter 始终满足该标准。
关于language-agnostic - 一个方法究竟什么时候有副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/810289/