« back

Access Modifiers

04 Mar 2013

Here are some tips about making decisions about access.

When you create variables and methods, it is necessary to declare their scope; to determine what else has access to them. This again ties into encapsulation and what should be exposed to the outside world. As I discussed in my post What? Good Test Coverage Does Not Always Mean 1 to 1?, leaving certain variables or methods hidden from the outside world is desirable. Let's explore this topic by taking a look at the java access modifiers that provide options for choosing the level of exposure we give to our code at a variable and method level.

Public - This is like an all access pass. This means that you can access the variable or method from any class, subclass, package...anywhere. This can often times leave your code exposed and vulnerable when you do not want it to be. When making something public, you can ask yourself if this is the point where the exposure needs to be? If you were to change the access modifier, would you still be able to reach the variable or method and use it in the scope of your original intent? Could you move the responsibility access off of this method or variable to help you achieve a more SOLID design?

1 public MyClass classInstance;  <-- Public field access modifier.
2 
3 public void myMethod() {  <-- Public method access modifier.
4     do some stuff 
5 }

Private - This means that the field or method will only be accessible through it's own class. This is a good level of access for utility code and details to keep hidden. I think the same questions from above can be asked in regards to this modifier. Encapsulation baby.

1 private MyClass classInstance;  <-- Private field access modifier.
2 
3 private void myMethod() {  <-- Private method access modifier.
4     do some stuff 
5 }

Protected - This is like a members only club. "Are you part of my package or a subclass of my class? Then we're cool, I can help you and you can talk to me. If not, forget about it."

1 protected MyClass classInstance;  <-- Protected field access modifier.
2 
3 protected void myMethod() {  <-- Protected method access modifier.
4     do some stuff 
5 }

Default - if you do not declare an access modifier, one will be provided for you. By default, no modifier will allow access within your package, but nowhere else. Sometimes this will be referred to as a package access modifier.

1 MyClass classInstance;  <-- Default field access modifier.
2 
3 void myMethod() {  <-- Default method access modifier.
4     do some stuff 
5 }

A class will always have access to it's own members. You control what happens beyond that and working this way helps prevent errors from misuse. As a guideline, you want to always use the most restrictive access modifier that you can. If you are not going to use private, ask yourself the reason why not and make sure that it is justified.

comments powered by Disqus