Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use the private access modifier if it's redundant? [closed]

Given that these two examples are equivalent, which do you think is preferrable?

Without explicit modifier

public class MyClass {      string name = "james";      public string Name {         get { return name; }         set { name = value; }     }      void SomeMethod() { ... }  } 

With explicit modifier

public class MyClass {      private string name = "james";      public string Name {         get { return name; }         set { name = value; }     }      private void SomeMethod() { ... }  } 

I've always used the latter, but recently I've started adopting the former style. The private is redundant as that's the default accessor modifier, so doesn't it make sense to exclude it?

like image 704
jonnii Avatar asked Oct 31 '08 20:10

jonnii


People also ask

When should you use private access modifiers?

Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members.

What is the purpose of the private modifier?

The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Which of the following access modifier Cannot be applied to field of class?

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected.

Which of the following modifiers are not allowed in front of class?

Therefore the private access modifier is not allowed for classes.


1 Answers

I think explicity stating private helps in readability. It won't allow for a programmer to interpret its visibility differently.

like image 148
Nicholas Mancuso Avatar answered Sep 30 '22 18:09

Nicholas Mancuso