这绝对是主观的,但我想尽量避免它变成争论。我认为如果人们恰当地对待它,这将是一个有趣的问题。
这个问题的想法来自于我对“你最讨厌的语言的哪五件事?”问题的回答。我认为c#中的类在默认情况下应该是密封的——我不会把我的理由放在这个问题上,但我可能会写一个更完整的解释来回答这个问题。我对评论中的讨论热度感到惊讶(目前有25条评论)。
那么,你有什么有争议的观点?我宁愿避免那些基于相对较少的基础而导致相当宗教的事情(例如,大括号放置),但例如可能包括“单元测试实际上并没有多大帮助”或“公共字段确实是可以的”之类的事情。重要的是(至少对我来说)你的观点背后是有理由的。
请提出你的观点和理由——我鼓励人们投票给那些有充分论证和有趣的观点,不管你是否恰好同意这些观点。
默认情况下,所有变量/属性都应该是只读/final。
这个推理有点类似于Jon提出的类的封闭论证。程序中的一个实体应该有一个任务,而且只有一个任务。特别是,对于大多数变量和属性来说,改变值是绝对没有意义的。基本上有两个例外。
Loop variables. But then, I argue that the variable actually doesn't change value at all. Rather, it goes out of scope at the end of the loop and is re-instantiated in the next turn. Therefore, immutability would work nicely with loop variables and everyone who tries to change a loop variable's value by hand should go straight to hell.
Accumulators. For example, imagine the case of summing over the values in an array, or even a list/string that accumulates some information about something else.
Today, there are better means to accomplish the same goal. Functional languages have higher-order functions, Python has list comprehension and .NET has LINQ. In all these cases, there is no need for a mutable accumulator / result holder.
Consider the special case of string concatenation. In many environments (.NET, Java), strings are actually immutables. Why then allow an assignment to a string variable at all? Much better to use a builder class (i.e. a StringBuilder) all along.
我意识到,今天的大多数语言并没有默认我的愿望。在我看来,由于这个原因,所有这些语言都有根本性的缺陷。如果将它们更改为默认将所有变量视为只读,并且在初始化后不允许对它们进行任何赋值,那么它们的表达性、功能和易用性将不会受到任何损失。