次のコードに出くわしたとき 、単純なスクリプト ファイル パーサーの古いコードをリファクタリングしていました。
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 で始まる新しいディレクティブ!
を追加する必要がある場合はどうでしょうか? または、新しい処理識別子 (新しいスイッチケースなど) が必要ですか?
問題は、OCP を壊さずにディレクティブとプロセッサを簡単かつ正確に追加する方法を理解できなかったことです。!
-case を使用してscope
and/or を使用すると、 -caseline
と同様に少しトリッキーになりdefault
ます。
助言がありますか?