艾伦·霍鲁布 (Allen Holub) 写了以下内容,
You can't have a program without some coupling. Nonetheless, you can minimize coupling considerably by slavishly following OO (object-oriented) precepts (the most important is that the implementation of an object should be completely hidden from the objects that use it). For example, an object's instance variables (member fields that aren't constants), should always be private. Period. No exceptions. Ever. I mean it. (You can occasionally use protected methods effectively, but protected instance variables are an abomination.)
这听起来很合理,但他接着说,
You should never use get/set functions for the same reason—they're just overly complicated ways to make a field public (though access functions that return full-blown objects rather than a basic-type value are reasonable in situations where the returned object's class is a key abstraction in the design).
坦率地说,这对我来说听起来很疯狂。
我了解信息隐藏的原理,但是如果没有访问器和修改器,您根本无法使用 Java bean。我不知道在模型中没有访问器的情况下如何遵循 MVC 设计,因为模型不能负责渲染 View 。
但是,我是一名年轻的程序员,每天都会了解更多有关面向对象设计的知识。也许有更多经验的人可以权衡这个问题。
Allen Holub 的文章供引用
<小时/>相关问题:
最佳答案
Holub 告诉您,您通常应该避免更改对象的状态,而是诉诸集成方法(行为的执行)来实现此目的,我对此没有意见。正如 Corletk 指出的那样,长期认真地思考最高级别的抽象是明智的,而不仅仅是不假思索地使用 getter/setter 进行编程,这只会让您围绕封装进行最终运行。
但是,如果有人告诉你“永远不要”使用 setter 或“永远不要”访问原始类型,我就会遇到很多麻烦。事实上,在所有情况下保持这种纯度所需的努力可能并且最终会导致代码比使用适当实现的属性更加复杂。你只需要有足够的理智,知道自己何时为了短期利益而规避规则,而付出了长期痛苦的代价。
Holub 不相信你知道其中的区别。我认为了解差异才能使您成为专业人士。
关于language-agnostic - Allen Holub 写了 "You should never use get/set functions",他是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/996179/