Access modifier best practice in C# vs Java

僤鯓⒐⒋嵵緔 提交于 2019-12-01 16:54:58

I think you answered your question. As per Joshua Bloch, "The rule of thumb is simple, make each class or member as inaccessible as possible." Effective Java

Java's scoping is slightly different than C#'s scoping.

This is talked about briefly in C# From a Java Developer's Perspective's The Same, But Different: Access Modifiers. This document is slightly dated now, but is still mostly relevant.

That list has two mistakes:

  1. C#'s internal is equivalent to Java's default scope (which is its own scope).
  2. C#'s internal protected is equivalent to Java's protected.

Additionally, the above document doesn't mention what the default access modifiers are for classes, only for methods and properties/variables.

For reference, the default scope for classes in c# is internal. Java's is its usual default scope, as described earlier.

The only things that I make public are static/final variables, which are generally constants. Everything else is private, and access is done through getXXX() and setXXX() methods, when appropriate. The setXXX() methods also perform any validation against the data. If I have to make something protected, I will, but I usually avoid it.

Less "client" (other code) knows about inner-workings of your classes, he will benefit more ... Simple rule of abstraction, and a fundamental pillar of OOP. The right answer is already given above:

"The rule of thumb is simple, make each class or member as inaccessible as possible." ~ Joshua Bloch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!