这绝对是主观的,但我想尽量避免它变成争论。我认为如果人们恰当地对待它,这将是一个有趣的问题。
这个问题的想法来自于我对“你最讨厌的语言的哪五件事?”问题的回答。我认为c#中的类在默认情况下应该是密封的——我不会把我的理由放在这个问题上,但我可能会写一个更完整的解释来回答这个问题。我对评论中的讨论热度感到惊讶(目前有25条评论)。
那么,你有什么有争议的观点?我宁愿避免那些基于相对较少的基础而导致相当宗教的事情(例如,大括号放置),但例如可能包括“单元测试实际上并没有多大帮助”或“公共字段确实是可以的”之类的事情。重要的是(至少对我来说)你的观点背后是有理由的。
请提出你的观点和理由——我鼓励人们投票给那些有充分论证和有趣的观点,不管你是否恰好同意这些观点。
最简单的方法就是最好的方法
程序员喜欢解决假定的或推断的需求,这些需求会增加解决方案的复杂性。
“我认为这段代码会成为性能瓶颈,因此我会添加所有这些额外的代码来缓解这个问题。”
“我假设用户会想要做某件事,因此我会添加这个非常酷的额外功能。”
“如果我能让我的代码解决这个不需要的场景,这将是一个使用我一直有兴趣尝试的新技术的好机会。”
实际上,满足需求的最简单的解决方案是最好的。如果出现新的需求或问题,这也为您在新的方向上采取解决方案提供了最大的灵活性。
程序员应该不惜一切代价避免通过继承隐藏方法。
In my experience, virtually every place I have ever seen inherited method hiding used it has caused problems. Method hiding results in objects behaving differently when accessed through a base type reference vs. a derived type reference - this is generally a Bad Thing. While many programmers are not formally aware of it, most intuitively expect that objects will adhere to the Liskov Substitution Principle. When objects violate this expectation, many of the assumptions inherent to object-oriented systems can begin to fray. The most egregious cases I've seen is when the hidden method alters the state of the object instance. In these cases, the behavior of the object can change in subtle ways that are difficult to debug and diagnose.
Ok, so there may be some infrequent cases where method hiding is actually useful and beneficial - like emulating return type covariance of methods in languages that don't support it. But the vast majority of time, when developers use method hiding it is either out of ignorance (or accident) or as a way to hack around some problem that probably deserves better design treatment. In general, the beneficial cases I've seen of method hiding (not to say there aren't others) is when a side-effect free method that returns some information is hidden by one that computes something more applicable to the calling context.
像c#这样的语言通过要求在隐藏基类方法的方法上使用new关键字进行了一些改进——至少有助于避免非自愿地使用方法隐藏。但我发现许多人仍然混淆了new和override的含义——特别是在简单的场景中,它们的行为看起来是相同的。如果像FxCop这样的工具实际上有内置的规则来识别方法隐藏的潜在不良使用,那就太好了。
顺便说一下,通过继承隐藏方法不应该与其他类型的隐藏(例如通过嵌套)相混淆,我认为嵌套是一种有效且有用的构造,潜在问题较少。