这绝对是主观的,但我想尽量避免它变成争论。我认为如果人们恰当地对待它,这将是一个有趣的问题。
这个问题的想法来自于我对“你最讨厌的语言的哪五件事?”问题的回答。我认为c#中的类在默认情况下应该是密封的——我不会把我的理由放在这个问题上,但我可能会写一个更完整的解释来回答这个问题。我对评论中的讨论热度感到惊讶(目前有25条评论)。
那么,你有什么有争议的观点?我宁愿避免那些基于相对较少的基础而导致相当宗教的事情(例如,大括号放置),但例如可能包括“单元测试实际上并没有多大帮助”或“公共字段确实是可以的”之类的事情。重要的是(至少对我来说)你的观点背后是有理由的。
请提出你的观点和理由——我鼓励人们投票给那些有充分论证和有趣的观点,不管你是否恰好同意这些观点。
To Be A Good Programmer really requires working in multiple aspects of the field: Application development, Systems (Kernel) work, User Interface Design, Database, and so on. There are certain approaches common to all, and certain approaches that are specific to one aspect of the job. You need to learn how to program Java like a Java coder, not like a C++ coder and vice versa. User Interface design is really hard, and uses a different part of your brain than coding, but implementing that UI in code is yet another skill as well. It is not just that there is no "one" approach to coding, but there is not just one type of coding.
对象不应该处于无效状态
不幸的是,许多ORM框架要求所有实体类都使用零参数构造函数,使用setter填充成员变量。在这些情况下,很难知道为了构造一个有效的对象必须调用哪些setter。
MyClass c = new MyClass(); // Object in invalid state. Doesn't have an ID.
c.setId(12345); // Now object is valid.
在我看来,一个对象不可能发现自己处于无效状态,类的API应该在每次方法调用后主动强制它的类不变量。
构造函数和突变方法应该原子地将对象从一种有效状态转换为另一种有效状态。这个好多了:
MyClass c = new MyClass(12345); // Object starts out valid. Stays valid.
作为一些库的使用者,在尝试使用一个对象之前跟踪是否调用了所有正确的setter是一件非常痛苦的事情,因为文档通常没有提供关于类契约的线索。