当前位置:网站首页>什么是无副作用的函数方法?如何取名? - Mario
什么是无副作用的函数方法?如何取名? - Mario
2020-11-06 01:19:59 【解道jdon】
函数名称应描述函数所做的所有事情。换句话说,功能不应隐藏副作用。这符合“最小惊喜原则”。但是,有时候这并不容易。下面函数名词名副其实吗?
众说纷纭:
它会返回一个Cusomter,但是如果没有可用的Customer,它将创建一个没有参数的Customer。我将遵循GetCustomerOrDefault()的C#命名风格。
如果创建客户是完全封装的,并且没有外部代码会知道新客户和现有客户之间的区别,那么我认为这个名称很好。另一方面,如果没有封装,也许应该是两个功能。
坏名称不仅会降低可读性,而且通常是更深层质量问题的征兆。例如,如果找不到某个函数的好名称,则该函数的设计可能不好。您如何命名此功能?它的名称含糊不清,因为该函数没有内聚性。
取名TryGetCustomerOrInstantiate?
如果您需要副作用,我可以将其重命名为getCustomerOrDefault()之类的名称,以便消除副作用。如果不这样做,则对空客户抛出异常。您甚至可以同时使用这两种方法,具体取决于您的API需要多么精细。
它做了两件事:允许访问私人客户字段;如果缺少客户,则创建客户我建议避免这种编码方式!
banq:违反单一职责,做了两件事情;包含可变状态,带有副作用,无法让调用者调用getCustomer方法时确定返回一个Customer,不符号函数式编程原则。
版权声明
本文为[解道jdon]所创,转载请带上原文链接,感谢
https://www.jdon.com/55231
边栏推荐
- C++ 数字、string和char*的转换
- C++学习——centos7上部署C++开发环境
- C++学习——一步步学会写Makefile
- C++学习——临时对象的产生与优化
- C++学习——对象的引用的用法
- C++编程经验(6):使用C++风格的类型转换
- Won the CKA + CKS certificate with the highest gold content in kubernetes in 31 days!
- C + + number, string and char * conversion
- C + + Learning -- capacity() and resize() in C + +
- C + + Learning -- about code performance optimization
猜你喜欢
-
C + + programming experience (6): using C + + style type conversion
-
Latest party and government work report ppt - Park ppt
-
在线身份证号码提取生日工具
-
Online ID number extraction birthday tool
-
️野指针?悬空指针?️ 一文带你搞懂!
-
Field pointer? Dangling pointer? This article will help you understand!
-
HCNA Routing&Switching之GVRP
-
GVRP of hcna Routing & Switching
-
Seq2Seq实现闲聊机器人
-
【闲聊机器人】seq2seq模型的原理
随机推荐
- LeetCode 91. 解码方法
- Seq2seq implements chat robot
- [chat robot] principle of seq2seq model
- Leetcode 91. Decoding method
- HCNA Routing&Switching之GVRP
- GVRP of hcna Routing & Switching
- HDU7016 Random Walk 2
- [Code+#1]Yazid 的新生舞会
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- HDU7016 Random Walk 2
- [code + 1] Yazid's freshman ball
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- Qt Creator 自动补齐变慢的解决
- HALCON 20.11:如何处理标定助手品质问题
- HALCON 20.11:标定助手使用注意事项
- Solution of QT creator's automatic replenishment slowing down
- Halcon 20.11: how to deal with the quality problem of calibration assistant
- Halcon 20.11: precautions for use of calibration assistant
- “十大科学技术问题”揭晓!|青年科学家50²论坛
- "Top ten scientific and technological issues" announced| Young scientists 50 ² forum
- 求反转链表
- Reverse linked list
- js的数据类型
- JS data type
- 记一次文件读写遇到的bug
- Remember the bug encountered in reading and writing a file
- 单例模式
- Singleton mode
- 在这个 N 多编程语言争霸的世界,C++ 究竟还有没有未来?
- In this world of N programming languages, is there a future for C + +?
- es6模板字符
- js Promise
- js 数组方法 回顾
- ES6 template characters
- js Promise
- JS array method review
- 【Golang】️走进 Go 语言️ 第一课 Hello World
- [golang] go into go language lesson 1 Hello World