OOT是一个迷你系列,旨在编写可维护的面向对象代码而无需费劲。
Arguments Arguments Arguments
- 冗长的函数参数列表对于调用代码要使用来说是乏味的。 这也使得以错误的顺序传递参数变得非常容易,而几乎没有类型安全性,并且会降低代码的可读性。除非您每次调用函数签名都加倍,否则它们很难阅读也很难理解。
“每个人都会感到困惑和困惑,在阅读代码时会中断流程,从而使您难以接受。”鲍勃·马丁叔叔
- 参数使测试功能变得更加困难。 编写所有测试用例以确保所有各种参数组合都能正常工作是很困难的。
因此,我们不应该鲁ck地使用它们作为便利,我们应该施加大量的约束,并将每个论点都视为一种责任。
Structure
最好的函数具有尽可能少的参数。 理想情况下。 niladic > monadic > dyadic > triadic > polyadic The same guidelines apply for constructors.
Always Be Refactoring
- Argument Objects: If you pass three or more arguments in your functions, then stop and think. If three or more variables are so cohesive that they can be passed together into a function, why aren’t they an object? https://www.refactoring.com/catalog/introduceParameterObject.html
- Overloading: One reason to overload functions is so that a client can call the appropriate version of the function for supplying just the necessary parameters.
- Builder Pattern: Sometimes function overloading goes out of hand and leads to a situation called a Telescoping Constructor anti-pattern. To avoid this, in the Second Edition of Effective Java, Josh Bloch introduces use of the builder pattern for dealing with constructors that require too many parameters.
- Mutable State: Not Recommended Perhaps the best known and most widely scorned approach in all of software development for using state to reduce parameter methods is the use of global, instance variables. Although not the best solution, but may be appropriate in some cases. Use with caution especially in highly concurrent programs.
“任何全球数据在被证明无辜之前总是有罪的。”马丁•福勒(Martin Fowler)
Death By Booleans
在大多数情况下,将布尔值传递给函数时,都是在向世界大声宣布您编写的函数可以完成两件事。 一件事是真实情况,另一件事是错误情况。 相反,您应该编写了两个函数,每种情况一个。
A boolean hanging out in the argument list can be a huge source of error and confusion. What does it mean if it’s true? What does it mean if it’s false? If the name of the function and the argument fail to make this perfectly clear, then every time you use this function, you need to dive into the implementation details to understand the right value to be passed. Passing in two booleans is even worse. A function that takes two booleans does four things!
Try guessing the booleans, their order and the behaviour:
Makes you squint, doesn’t it? Avoid guesses and double-takes by using the Builder Pattern:
The Null Defense
通过空值到一个函数或编写一个期望的函数空值传递几乎和传递布尔值一样糟糕。 实际上,情况甚至更糟,因为根本不明显只有两种可能的状态。
当然,非空情况下有行为,空情况下有行为。 更好的方法是创建两个函数,一个函数采用非null参数,而另一个函数根本不采用该参数。 不要将null用作伪布尔值。
听甘道夫。 空参数不得通过。
坦白说,防御性编程很糟糕。 用空检查和错误检查乱丢代码太可怕了。 我们不想认为我们的队友会毫不留情地将null纳入我们的职能范围。 这也意味着我们不信任阻止我们传递该null的单元测试。
这不适用于公共API,因为我们不知道谁会传递什么。 如果您的语言支持@NotNull批注或类似的概念,使用它来标记您的公共功能,并且可能因抛出诸如IllegalArgumentException。
我希望这可以帮助您避免编写容易出错的代码,因为它对我有所帮助。 您对此有何看法? 这篇文章的灵感来自Bob叔叔和他的书Clean Code。
Originally posted on Hackernoon
Check out the next trick here.
from: https://dev.to//voidmaindev/object-oriented-tricks-3-death-by-arguments