Access modifier best practice in C# vs Java

2019-02-21 21:17发布

I understand that the rule of thumb in OOD is to minimize access to all members of a given object as best as can be reasonably accomplished.

C# and Java both seem to implement the same set of access modifiers; however, something which has bewildered me for some time now is why Java classes seem to be mostly declared as public while C# classes seem mostly to be declared as default. Is there some subtlety to these languages which imposes these differences, or is it simply a matter of convention or what?

I find myself frequently going through my C# code (I habitually make most classes public, excepting inner classes, anonymous classes, and other classes of narrow scope and usefulness) in an attempt to please the compiler, however I wonder if I may be missing something important.

4条回答
Juvenile、少年°
2楼-- · 2019-02-21 22:07

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

查看更多
别忘想泡老子
3楼-- · 2019-02-21 22:12

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-21 22:18

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.

查看更多
聊天终结者
5楼-- · 2019-02-21 22:19

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

查看更多
登录 后发表回答