几年前,曾经有过一场比赛,看谁能编写出最模糊的 C 代码,其中一些结果非常难以理解。 C是这样的。你真的可以用预处理器搞砸事情。
然而,许多 C# 的新特性提供了一个绝佳的机会来混淆代码。我想知道是否有人对在代码的简洁和清晰之间找到正确的平衡有意见。让我举一个例子进行讨论,将项目填充到 ListView 中的任务. (是的,我知道您可以通过数据绑定(bind)来做到这一点,但请跟我来。)
该控件是两列要填充的数组
struct Person
{
public string name;
public string address;
};
一种,清晰而简单的方法是这样的:
private void Fill(Person[] people)
{
foreach(Person person in people)
{
string[] columns = new string[2];
columns[0] = person.name;
columns[1] = person.address;
ListViewItem item = new ListViewItem(columns);
listView1.items.Add(item);
}
}
清晰易懂。
我也可以这样写:
private void Fill(Person[] people)
{
foreach(Person person in people)
{
string[] columns = new string[] { person.name, person.address };
ListViewItem item = new ListViewItem(columns);
listView1.items.Add(item);
}
}
甚至:
private void Fill(Person[] people)
{
foreach(var person in people) // Note use implicit typing here
{
listView1.items.Add(new ListViewItem(
new string[] { person.name, person.address }));
}
}
最后,我也可以这样写:
private void Fill(Person[] people)
{
Array.ForEach(people, item =>
listView1.items.Add(new ListViewItem(
new string[] { person.name, person.address}));
}
每个人都或多或少地使用了该语言的各种新特性。您如何在简洁和清晰之间找到平衡?我们应该每年举办一次混淆 C# 比赛吗?
请您参考如下方法:
你知道什么难吗?编写其他人可以阅读和维护的代码。任何白痴都可以编写可编译且无法维护的代码。
总是 支持可维护性:这就是您找到平衡的方式。
编辑:
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
- Martin Fowler, Refactoring: Improving the Design of Existing Code
感谢 roygbiv查找上述报价。向福勒道歉,因为他谋杀了他的报价;我知道我以前读过它,我只是不记得在哪里。




