我有一个关于范围和封装的一般性问题。采取两种情况:
场景一:
// a global application level constant
public static const IS_DEMO_MODE:Boolean = false;
... // somewhere deep in the codebase
private function _myFunction():void
{
if (IS_DEMO_MODE == true) {
// If Demo Mode do not allow this function to complete
return;
}
else {
// Function behaves normally
// Code ...
}
}
场景二:
// a global application level constant
public static const IS_DEMO_MODE:Boolean = false;
... // somewhere deep in the codebase
// call the function and pass in the constant
_myFunction(IS_DEMO_MODE);
private function _myFunction(isDemoMode:Boolean):void
{
if (isDemoMode == true) {
// If Demo Mode do not allow this function to complete
return;
}
else {
// Function behaves normally
// Code ...
}
}
从功能上讲,这两个代码片段做同样的事情。我试图了解编码风格的细微之处以及为什么一种方式可能优于另一种方式?从封装的角度来看,方案 2 似乎更好。但是场景 1 更加万无一失,因为条件中的布尔值仅来自一个地方,即全局常量。您不必担心在正确接收参数时可能会传入错误值的函数调用。但是场景 2 似乎值得,因为您删除了常量的依赖关系并且可以让函数表现得更加动态。对此有什么想法吗?我还有其他权衡吗?
同样的概念和问题也适用于对象和类。但是为了简化代码示例,我只是根据函数来展示示例。