我想验证命令行参数并在出现错误时输出错误消息。我的问题是,如果命令行参数的数量增加(目前,我只有3),那么我的代码将变成意大利面代码。我怎样才能减少给定代码的圈复杂度?如何减少这些if else语句的圈复杂度
var isCmdLineWrong = false;
var Arg1 = "Undefined";
var Arg2 = "Undefined";
var Arg3 = "Undefined";
var commandArguments = Environment.GetCommandLineArgs();
if (commandArguments.Contains("-r") && arguments[commandArguments.IndexOf("-r") + 1].StartsWith("-") == false)
Arg1 = commandArguments[commandArguments.IndexOf("-r") + 1];
else
{
isCmdLineWrong = true;
}
if (commandArguments.Contains("-n") && commandArguments[commandArguments.IndexOf("-n") + 1].StartsWith("-") == false)
Arg2 = commandArguments[commandArguments.IndexOf("-n") + 1];
else
{
isCmdLineWrong = true;
}
if (commandArguments.Contains("-p") && commandArguments[commandArguments.IndexOf("-p") + 1].StartsWith("-") == false)
Arg3 = commandArguments[commandArguments.IndexOf("-p") + 1];
else
{
isCmdLineWrong = true;
}
if (isCmdLineWrong) Console.WriteLine("Parameters structure is inconsistent");
正是我在想什么,但为什么你把它全部**静态**? – Maarten
@Maarten:我们对应用程序只有*一个*命令行,所以我们不需要'CommandLine'类的许多实例(像'Application','Environment'和类似的类) –
@DmitryBychenko:这是正确的,但这也会让你的班级更难测试或替换。我可以提出这些简单的改变:** 1。**使类和它的成员非静态** 2。**用'commandLine'字符串参数来扩充ctor,而不是'Environment.GetCommandLineArgs( )',最后** 3。**添加一个静态的'Instance'属性或字段,该属性或字段返回/被初始化为绑定到实际命令行的实例:'public static CommandLine Instance = new CommandLine(Environment.GetCommandLineArgs())'。 – stakx