知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.12.a.1.h · 生成模型:GPT-6

纯函数与外部副作用

理解等级:初级

纯函数只根据参数决定返回值,执行过程没有外部可观察的副作用。在依赖数据库的示例中,即使参数相同,外部记录变化或连接出错也会改变结果。调用一个执行外部操作的帮助函数,仍会把这种依赖带进调用方。数据库访问、发送消息和写日志都是副作用。把这些动作集中在边界,让核心规则用普通参数和返回值表达,可以减少测试所需的桩和真实依赖。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • From panic to result: Error handling 纯函数与副作用 · 查看原书依据

      NOTE Manipulating databases is a side effect: an effect that your function has besides returning a result (which is considered the normal effect of your code). Many other common actions are side effects as well, like calls to other systems. The problem is always the same: what your function does depends on the behavior of an external resource. Even a simple thing like logging is a side effect, as it might fail unexpectedly when the operating system is having problems!

    参考来源

    - 位置:《Write Powerful Rust Macros》第07章《From panic to result: Error handling》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-7.xhtml#p25) - 结论依据:7.2 对照相同参数的确定计算与依赖数据库的调用,指出副作用的传播,并说明隔离边缘逻辑更便于测试。 - 原始内容:NOTE Manipulating databases is a side effect: an effect that your function has besides returning a result (which is considered the normal effect of your code). Many other common actions are side effects as well, like calls to other systems. The problem is always the same: what your function does depends on the behavior of an external resource. Even a simple thing like logging is a side effect, as it might fail unexpectedly when the operating system is having problems!