我正在学习list的方法(pop和remove的区别)
并注意 Command–query separation
It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, Asking a question should not change the answer.[1] More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.
我无法解释“提出问题不应改变答案”,
我读了ppt
维基百科链接,其中以 channel 内部和外部的“光”标志为例。
它没有说明问题和答案之间的关系。
在我看来,应该是“回答问题不应该改变问题”
说得有道理
In theoretical terms, this establishes a measure of sanity, whereby one can reason about a program's state without simultaneously modifying that state.
我的扣除合理吗?
最佳答案
下面的类遵循 CQS 原则。它的每个方法要么是一个查询,要么是一个命令。方法 get
提供有关状态的信息,并且不允许产生任何副作用。 set
方法有副作用,因此返回 None
。
class IntValue:
def __init__(self, x):
self.x = int(x)
def get(self):
return self.x
def set(self, x):
self.x = int(x)
特别是,以下内容始终为真。
v = IntValue(1)
v.get() == v.get() # Always True
您永远不会通过 get
方法询问值并同时更改它。在这里,CQS 原则确保您可以连续多次询问该值,并且仍然得到相同的答案。
这很重要,因为程序中许多不希望有的复杂性都是由副作用引起的。
现在考虑一个封装列表的类似类。
class ListValue:
def __init__(self, x):
self.x = list(x)
def get(self):
return self.x
def set(self, x):
self.x = list(x)
上述的问题是提出问题可能会导致答案发生变化。
v = ListValue([1, 2, 3])
lst = v.get() # [1, 2, 3]
lst.append(4)
v.get() # [1, 2, 3, 4]
在开发大型软件时,这通常是难以跟踪的错误的来源。通过确保您无法从 ListValue
访问状态,而只能访问该状态的 View ,可以避免这些问题。
class ListValue:
def __init__(self, x):
self.x = list(x)
def get(self):
return deepcopy(self.x) # Here we return a copy of the list
def set(self, x):
self.x = list(x)
关于python - 理解Python中的命令-查询分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743954/