本文介绍了设计一种返回值或更改某些数据但不能同时返回两者的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我隐约记得前段时间读到,方法/函数应该返回一个值而不修改状态,或者应该处理一些改变状态但不返回数据的数据。

I vaguely remember reading somewhere a while ago that either a method/function should return a value without modifying the state or should process some data changing a state but not returning data. It is beyond simple getters and setters.

我无法弄清楚我在哪里读到的书,基本原理以及这是否是合理的原则。确定测试可能更简单,但是还有其他原因吗?有没有相关的设计原则或模式?

I cannot figure where I read that, the rationale and if this was a sound principle. It may be simpler to test for sure but is there any other reason? Is there is there a related design principle or pattern? Any clue or link appreciated.

感谢
Olivier

ThanksOlivier

推荐答案

该原理称为命令-查询分隔

来自:

它声明每个方法都应该是执行动作的 command ,或 query ,它们将数据返回给调用者,但不能同时返回给调用者。换句话说,提出问题不应更改答案。更正式地讲,方法仅在引用透明且因此没有副作用的情况下才应返回值。

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. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.

就我个人而言,我认为该原理非常有用。它基于一个普遍的观察结果:当我们看到一个函数返回一些数据时,我们倾向于认为它不会改变任何数据状态。换句话说,该功能没有任何副作用。相反,具有副作用的功能被认为是危险的。因此应该有明确的指示(返回 void 类型)。您会看到,C#具有 Properties 的概念,您可以在其中使用赋值符号来更改属性的状态,该赋值符号比setter方法更有效。

Personally, I think this principle is very helpful. It is based on a common observation that: when we see a function that returns some data, we tend to think that it does not change any state of data. In other words, that function does not have any side-effect. In constrast, functions with side-effects are considered "risky" and therefore should have a clear indication (returning void type). You see, C# has the concept of Properties where you change state of a property by using the assignment symbol which is a stronger indication than setter methods.

总结,CQS原则有助于管理代码,因为管理状态更改在编程中的重要性。

To conclude, the CQS principle helps our code to be easier to read and reason since managing how state changes is crucial in programming.

您可以在Wikipedia文章中找到更多有用的链接,并且和。

You can find more useful links in the wikipedia article, and this and this.

这篇关于设计一种返回值或更改某些数据但不能同时返回两者的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 19:16