受保护/私有 - 为什么要麻烦呢?
在用 Java 编写程序的过程中,我抽象出了一些库,我可以看到它们在未来项目中可能的用途。
为什么我要为这些方法中的任何一个设置受限访问(私有/受保护)?
看来这只会让我以后的生活变得更加复杂。 如果我对所有内容都使用 public,我将永远不需要担心是否可以从其他类中调用某些内容。 在我的任何代码中,我从未见过使用除 public 之外的任何内容对我来说有意义的情况。
在所有事情上都使用“公共”是错误的吗? 我会被爪哇诸神击倒吗?
DUPE: Private vs. Public members in practice (how important is encapsulation?)
In the course of writing a program in Java, I have abstracted out some libraries that I can see a possible use for in future projects.
Why should I bother with setting restricted access (private/protected) on any of these methods?
It seems like this will just make my life more complicated in the future. If I use public on everything, I will never need to worry about whether I can call something from some other class. I have never seen a case in any of my code yet where it made any sense for me to use anything except public.
Is it so wrong to use 'public' on everything? Am I going to be struck down by the Java gods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,在所有事情上都使用 public 是错误的。 这意味着您完全不知道“此成员是公共 API 的一部分;您应该能够从外部世界使用它,并且它不应该更改”和“此成员是一个实现”之间的区别如果我以后想更改它,我可以这样做,因为我知道外界不会调用它。”
在我看来,API 和实现之间的明确划分对于灵活性和清晰度非常重要。
Yes, it's wrong to use public on everything. It means you have absolutely no concept of the difference between "this member is part of a public API; you're expected to be able to use it from the outside world, and it shouldn't change" and "this member is an implementation detail. If I want to change it later, I can do so because I know nothing from the outside world will be calling it."
Having a clear split between API and implementation is important for flexibility and clarity IMO.