淘客熙熙

主题:【原创】乱侃软件工程师的素养 1 -- poorfat

共:💬71 🌺108 新:
全看分页树展 · 主题 跟帖
家园 【原创】素养 (5) 留下痕迹案例2

再强调一下:别忘了留下痕迹,从程序所有可能的执行路径都要记得留下踪迹。

我有一次测试这样一段程序。用正面测试(positive tests)都是好的。一用反例来测试,就碰到问题了。

请看这段程序:(以下用伪码表示)

bool Run(executableName, ParamList, &fullCommandLine, &error)

{

if ( ShellExecute("cmd /c " + executableName + " " +ParamList) )

{

fullCommandLine = "cmd /c " + executableName + " " +ParamList;

return true;

}

error = GetShellError();

return false;

}

void RunCommandWithLogging(executableName, ParamList)

{

...

var cmdline = "";

var errorlevel = 0;

if ( Run(executableName + " " +ParamList, cmdline, errorlevel) )

{

log("the command line=[" + cmdline+"] has succeeded. ");

}

else

{

log("the command line=[" + cmdline+"] has failed. Errorlevel="+errorlevel);

}

...

}

诸位看出问题来没有?每当我用一个错误的命令放入RunCommandWithLogging()函数,我就看到日志文件里有这样一行:

the command line=[] has failed. Errorlevel=blah

没错,就是一对空的方括号[]。问题就在这里。当命令行有错误的时候,日志文件里就没有记录那条错误的命令行,而只有一对空的方括号。

为什么会这样呢?应为当ShellExecute()失败的时候,变量fullCommandLine没有被赋值。就这么简单。因此,Run()函数应该订正如下:

bool Run(executableName, ParamList, &fullCommandLine, &error)

{

if ( ShellExecute("cmd /c " + executableName + " " +ParamList) )

{

fullCommandLine = "cmd /c " + executableName + " " +ParamList;

return true;

}

else

{

fullCommandLine = "cmd /c " + executableName + " " +ParamList;

error = GetShellError();

return false;

}

}

这个案例的教训就是,如果你要记录日志,别忘了所有的代码路径(code path)都要留下日志。

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河