在某些(非常罕见)的情况下,存在以下风险:
重用不打算重用的变量(请参见示例1),
或使用一个变量代替另一个在语义上接近的变量(请参见示例2)。
范例1:
var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.
}
// ...
foreach (var flow in data.Flows)
{
// This shouldn't happen: given that ETL possibly altered the contents of `data`, it is
// not longer reliable to use `data.Flows`.
}
范例2:
var userSettingsFile = SettingsFiles.LoadForUser();
var appSettingsFile = SettingsFiles.LoadForApp();
if (someCondition)
{
userSettingsFile.Destroy();
}
userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe
// destroyed. It's `appSettingsFile` which should have
// been used instead.
通过引入范围可以减轻这种风险:
范例1:
// There is no `foreach`, `if` or anything like this before `{`.
{
var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
this.ETL.Process(data);
}
}
// ...
// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.
范例2:
{
var userSettingsFile = SettingsFiles.LoadForUser();
if (someCondition)
{
userSettingsFile.Destroy();
}
}
{
var appSettingsFile = SettingsFiles.LoadForApp();
// `userSettingsFile` is out of scope. There is no risk to use it instead of
// `appSettingsFile`.
}
看起来不对吗?您会避免使用这种语法吗?初学者很难理解吗?
7
您能否辩称每个独立的“作用域块”应该是其自己的方法或函数?
—
Dan Pichelman 2013年
我会说“经常”没有很好地实现(但可能不是“设计”问题)。有时是设计使然,这是不可避免的(例如,异常/资源范围界定)。
—
JustinC 2013年