Getter/Setter 会导致代码更脆弱吗?

发布于 2024-09-27 20:21:58 字数 293 浏览 0 评论 0原文

关于受保护的问题引发了一场小争论。关于 getter/setter 的使用的成员变量。关于 getter/setter 是否邪恶已经存在很多问题,然而,由两个声誉比我高得多的独立人士提出的一个反对它们的特殊论点令我震惊。

一个人说 getters/setters 只使代码的脆弱性降低了 0.01%,另一个人说在需要的地方添加 10 行代码会使代码更加易碎。

这违背了我以前读过的、学到的、思考过的或经历过的大部分内容。还有其他人同意/不同意这些评论吗?

A small debate flared up in a question about protected member variables regarding the use of getters/setters. There are lots of questions already over whether getters/setters are evil, however one particular argument against them, which was posed by two separate individuals with much higher reputation than myself, struck me.

One said that getters/setters made the code only 0.01% less brittle, and the other stated that adding 10 lines of code where one would do makes the code more brittle.

This goes against most of what I had previously read, been taught, thought, or experienced. Does anyone else agree/disagree with those comments?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温折酒 2024-10-04 20:21:58

我知道这接近异端,但我讨厌 get/set 方法。讨厌他们。几乎从不写它们。

一般来说,一个类应该要么提供比直接简单地读取和修改内部状态变量更多的高级操作,要么它应该摆脱困境并像结构一样工作。

即使我要写一个,我也几乎不会在课堂上使用它。它们的重点是您可以在不影响客户端的情况下更改事物的内部表示。在类内部,是你关心的内部表示!如果您想使用类内部自己的接口对类进行大量操作,那么您可能会遇到第二个类正在努力摆脱困境。

I know it is close to herecy, but I hate get/set methods. Loathe them. Almost never write them.

Generally, a class should either provide much more high-level operations than directly and simply reading and modifying internal state variables, or it should get the hell out of the way and act like the struct it is.

Even if I were to write one, I would almost never use it inside the class. The whole point of them is that you can change the internal representation of thing without affecting a client. Inside the class, it is the internal representation you care about! If you are tempted to do a lot of operations on the class using its own interface inside the class, you probably have a second class in there fighting to get out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文