作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个函数接受一个 checkGlossary
bool 参数以及一个可选的 glossary
数组。
他们的状态直接联系在一起。
如果 bool 为 FALSE,则从不需要词汇表,相反,如果 bool 为 TRUE,则始终需要词汇表。
对我来说,这似乎可以很容易地简化为:
// Current
function doSomething($param1, $param2, $checkGlossary=FALSE, $glossary=NULL){
// blah blah blah
if($checkGlossary)
array_search($glossary[$param2]);
// etc etc etc
}
...到:
// Proposed
function doSomething($param1, $param2, $glossary=FALSE){
// blah blah blah
if($glossary)
array_search($glossary[$param2]);
// etc etc etc
}
我唯一的犹豫是 $glossary
的类型(bool 或 array)是不可预测的。
只要我不违反某些最佳实践准则,我就不会感到困扰。
想法?
最佳答案
使用 PHP 调用的 mixed
数据类型的函数参数总是一个坏主意。它需要函数中的额外代码来检查参数的类型,显然它会变得非常困惑。
在您的特殊情况下,最简单的解决方案可能是使用数组长度作为是否使用词汇表代码的指示符。您需要一种方法来声明不应使用词汇表数组。所以您应该问问自己:什么时候使用词汇表毫无意义?当然是空的时候。因此,我建议您去掉该标志并将 array()
定义为其他参数的默认值:
function doSomething($param1, $param2, $glossary=array()) {
if (count($array) > 0) {
// do your glossary code here
}
// all the other stuff goes here
}
对我来说,这在语义上似乎是正确的并且工作得很好。
我不知道您到底在那里构建什么,但另一种解决方案是将其全部放入一个类中并将词汇表作为实例变量。如果您可以在多个函数调用中使用词汇表。它大致看起来像这样:
public class SomeAccurateClassName {
private $glossary = array();
function setGlossary(array $glossary) {
$this->glossary = $glossary;
}
function doSomething($param1, $param2) {
if (count($array) > 0) {
// do your glossary code here
}
// all the other stuff goes here
}
}
考虑到您基本上有一个状态(使用词汇表或不使用词汇表),将它封装在一个类中可能是个好主意。
关于PHP 最佳实践 : Should a given parameter always have a consistent type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15259844/
我是一名优秀的程序员,十分优秀!