A discussion of private methods in Java, and the two different methods there are for using them, and the ways they help create quality code in your project.
We all are using private methods in our classes. There are two different ways to use them – one is good and valid while the second one is a hint that something can be wrong with our design.
First of all, we should consider why we are using these private methods. The main reason is breaking our code on smaller problems. We want to create more readable code – from our complicated method, we can create two smaller and consistent private methods. So instead of doing all the work in one method, we break up our code:
Another reason is avoiding code duplication in our class. We separate our code not only to get it more readable but to reuse the same block of code more than once:
Above we have the first type of a private method – as I wrote in beginning this type is helpful. It prevents creating spaghetti code, helps to avoid duplication, and breaks our problem into smaller things. As you can see, all of these private methods use fields of the class in which they were implemented.
Now we can talk about private methods which are not using anything from a class. We declare them as static.
Private static method is a method inside of class, which is not connected with the state of the object it is in. This method for sure will not change the object itself because it is not using any of its fields.
We should decide to move our calculation logic into a separate method. In this situation, we do not need taxMinistry because we are only operating on two values passed by parameter – netPrice and tax. Because of that, we can mark our private methods as static. Of course, we do not have to put a static modifier if we don’t want to and the method will work as before. The compiler will not raise any problems and the application will not throw any exceptions if we do not make it static.
The main difference here is that static indicates that our class is probably doing more than it should. In our Bank class, we do two things: ask TaxMinistry for current taxes and calculate the gross price. Instead, we can create a separate class which will do this for us:
Here, the calculations are delegated to the PriceWithTax class, which is easier to read and maintain, simply because it is smaller. The behavior of this class is clear for the API/code reader. Unit tests are so much easier too.
In your IDE, you can turn on an info message that will tell us which method can be private or static. This information (and also an existing static modifier on a private method) will remind you, that you should think more about your class design. A new class will probably better fit into your codebase.