Tag Archives: Coding Practices

Top 5 Java Coding Practices

In this short post, we will discuss the top 5 Java coding practices. One reason I like to revisit best practices is to remind myself if I am following them or not. Another reason to verify if anything has changed with language. Even if I visit the best practices after a few years, it gives me a refreshing perspective to understand where I am and how I am improving or not. Everybody has their own way, but programming is a skill and over time, you can continue to improve it just like any other skill. So here we go with the top 5 Java best coding practices.

   1. Methods Naming Convention – 

The name of the method should reveal the intention of the method. Example calculateHeight but if you name your method height , it is just bad because that can be more of a variable name. A method should also do a single job. If it is doing more than one job, you can always refactor the code.

   2. Use a consistent style –

The syntax style you use while writing Java code should be consistent across any code you write.

   3.  Use logging –

There are a number of logging APIs available, but the most popular log4j is available as a blanket for logging APIs. While writing an enterprise application, it is of utmost importance to log. From a code review perspective, it is helpful to have logged in your code. Another advantage of logging is in production while resolving a lot of issues, logging is the only way to debug the code in a short amount of time.

    4.  Variable encapsulation –

Most variables when declared should be private . This ensures safety so that accidental usage of this variable does not change the state of it. Adding getter and setter for such variables is standard practice.

    5.   Use comments frequently –

As a programmer, your responsibility begins when you start coding and good code is easy to read with well-documented comments. If a new programmer or developer joins the team, he should be able to understand the code without much context. Also for this reason specifically, read and revisit open source code often.

Conclusion

In this post, I discussed top 5 Java coding practices. What are your favorite tips for Java? If you enjoyed this post, subscribe to my blog here.

References