不小心发现自己编写的一些垃圾代码,删前留念。可以作为面试题使用。
有时候一个程序员会或者不会什么具体的技术差别不大,因为看看书几分钟就能学会;但编写垃圾代码一旦养成习惯,不是一天两天能改好的。
1. 这段代码等同于?
return vc.RequestContext.HttpContext.Request.Params["view"] != null
? vc.RequestContext.HttpContext.Request.Params["view"]
: null;
2001年曾经有个MM写过这样的代码(基本上一个字不差),后来被发现后,她自己也笑了:
switch (n)
{
case 1: return 1;
case 2: return 2;
case 3: return 3;
case 4: return 4;
case 5: return 5;
case 6: return 6;
default: return n;
}
如果能安装一个静态代码检查工具如Resharper,多数情况都会被发现出来。
作为编程者而言,无论经验多少,都经常会不小心写出垃圾代码。有个心法是:任何时候看到两处以上代码、两行以上代码、两个以上长变量……外观很相似时,都要提高警惕,几乎比有方法解决。
2. 如何写成一行代码?
if (String.IsNullOrEmpty(originalPage))
{
AnaylizeUrl(isInHomeArea, page.Request.RawUrl);
}
else
{
AnaylizeUrl(isInHomeArea, HttpUtility.UrlDecode(originalPage));
}
3. 这些代码实际上不存在,但差点被写出来,请看哪里可以优化?
名字很长,可能不太容易看懂,但不用看懂就能发现有问题的地方。
if (team.MethodologyValueOf(Methodology.TeamManagementTypeName) == Methodology.TeamManagementTypeKanban)
{
@RenderPage("MyItems/_MyItemsKanban.cshtml", myItemsViewModel, team, userName)
}
else if (team.MethodologyValueOf(Methodology.TeamManagementTypeName) == Methodology.TeamManagementTypeScrum)
{
@RenderPage("MyItems/_MyItemsScrum.cshtml", myItemsViewModel, team, userName)
}
else if (....)
{
...
}
Mehthodology在此定义:
public static string TeamManagementTypeName = "TeamManagementType";
public static string TeamManagementTypeKanban = "Kanban";
public static string TeamManagementTypeScrum = "Scrum";
提示:修改后那些if-else-if代码只有一行,无论日后是否增加新的分支,都无需改动。