封装良好实践

发布于 2024-10-13 21:52:18 字数 375 浏览 4 评论 0原文

可能的重复:
实践中的私有成员与公共成员(封装有多重要) ?)

最近我遇到了一种情况,我将一个类变量声明为公共变量,因为它将在另一个类中使用。最近有人告诉我,我应该将这些变量设为私有,并编写一个返回该变量值的公共方法。有人告诉我这是一个很好的做法。我搜索了我的 Java 书籍,但找不到任何对此的参考。我的问题是,将尽可能多的类变量声明为私有是否是一个好习惯?

Possible Duplicate:
Private vs. Public members in practice (how important is encapsulation?)

Recently I've been coming across a situation where I declare a class variable as public, because it will be used in another class. Someone told me recently that I should make such variables private and write a public method returning the value of the variable. I was told this was good practice. I searched through my Java book and couldnt find any reference to this. My question is, is it good practice to declare as many as possible class variables as private?

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

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

发布评论

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

评论(1

余生共白头 2024-10-20 21:52:18

是的。一般来说,所有变量都应该是私有的(不是受保护的,私有的),并且如果(并且仅当)您希望允许外部人员获取它们的值(并可能设置它们),则应该有方法。您使用的变量是实现细节,通常包含必须采用某种方式的数据。 Getters 和 Setters 允许你对数据负责,验证它,同步它等等,而不是让一些混蛋在其中存储随机的东西并可能使你的对象无法使用。

唯一的例外可能是那些唯一目的是存储数据的类,这样您就可以将其作为一个对象传送,有点像 C/C++ struct。但是,您做出的决定是,不,您不想以任何方式验证、同步、封装该数据......并且稍后改变主意会破坏二进制兼容性(意味着触及该类的任何代码都需要重新编译)。对于一个小型私人项目来说没什么大不了的;公共框架/API 中的重大问题。

Yes. Generally, all variables should be private (not protected, private), and there should be methods to get their values (and possibly set them) if (and only if) you want to allow that by outsiders. The variables you use are an implementation detail, and usually contain data that has to be a certain way. Getters and setters allow you to take responsibility for that data, validate it, synchronize it, etc, instead of letting some jackass store random stuff in it and potentially make your object unusable.

The sole exception might be classes whose only purpose is storage of data so you can ship it around as one object, kinda like a C/C++ struct. But then, you're making a decision that no, you don't want to validate, synchonize, encapsulate that data in any way...and changing your mind later breaks binary compatibility (meaning any code that touched that class will need to be recompiled). Not a big deal in a little private project; huge deal in a public framework/API.

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