python - 理解Python中的命令-查询分离

标签 python

我正在学习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/

相关文章:

Python:从右到左压缩的最快方法是什么,没有内置的方法吗?

python - Python 模块 wx.GraphicsContext 中的函数 DrawEllipse 仅适用于 Windows,但不适用于 Linux

python - 如何访问应用程序 'File Description' ?

python - 使用 Firefox 的 Tensorboard 在 Google Colab 中出现错误 403

php - GET请求适用于python 'requests'库,但不适用于curl

python - 遍历 pandas 中的组以提取顶部

python - 是否可以阻止模块/全局类变量创建单元测试实例?

python - 如何检查是否使用预期对象调用方法

python - 过滤后选择 Pandas 中上一行的语法

python - 减少大字典使用的内存