Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access modifier best practice in C# vs Java

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.

like image 524
Brian Sweeney Avatar asked Feb 04 '23 09:02

Brian Sweeney


2 Answers

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

like image 137
Gren Avatar answered Feb 06 '23 16:02

Gren


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.

like image 22
Powerlord Avatar answered Feb 06 '23 16:02

Powerlord