当我遇到以下代码时, 我正在重构一个简单的脚本文件解析器的一些旧代码:
StringReader reader = new StringReader(scriptTextToProcess);
StringBuilder scope = new StringBuilder();
string line = reader.ReadLine();
while (line != null)
{
switch (line[0])
{
case '$':
// Process the entire "line" as a variable,
// i.e. add it to a collection of KeyValuePair.
AddToVariables(line);
break;
case '!':
// Depending of what comes after the '!' character,
// process the entire "scope" and/or the command in "line".
if (line == "!execute")
ExecuteScope(scope);
else if (line.StartsWith("!custom_command"))
RunCustomCommand(line, scope);
else if (line == "!single_line_directive")
ProcessDirective(line);
scope = new StringBuilder();
break;
default:
// No processing directive, i.e. add the "line"
// to the current scope.
scope.Append(line);
break;
}
line = reader.ReadLine();
}
这个简单的脚本处理器在我看来是通过应用“开放封闭原则”进行重构的一个很好的候选者。以 a 开头的行$
可能永远不会有不同的处理方式。但是,如果!
需要添加以 a 开头的新指令怎么办?还是需要新的处理标识符(例如新的 switch-case)?
问题是,我无法弄清楚如何在不破坏 OCP 的情况下轻松正确地添加更多指令和处理器。!
使用scope
和/或 的-caseline
使它有点棘手,就像default
-case 一样。
有什么建议么?