Best Practices for Java Developers

For being a good Java programmer, you have to follow some best practices while doing java programming. I am also doing follow them for better performance of application.

  1. Always follow most important coding standards

    • Naming variables, methods and classes should be in CamelCase.
    • Number of parameters should be less either need to break method into several methods.
    • Complexity of a method
    • Size of methods and classes
  2. Use Code Analyzer Tool to optimize your code

    Code Analyzer lets you know the unused local variables, unnecessary if and looping statements and lots more. There are many code analyzer tools available you can choose any of them. You can choose one of them.

  3. Use Lambda Expression if there is only one abstract method in interface

    Java 8 introduces Lambda Expression for making use of functional programming. Lambda Expression lets you to implement an abstract method with less code as compared to anonymous class in earlier version.

  4. Use Stream API for performing bulk data operations

    A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection.

  5. Don’t return null from a method rather return new object reference

    Sometimes you need to return collection object from your method like ArrayList or HashMap. Don’t return null in case you don’t have elements rather create an object and return its reference.

  6. Use Primitive Data Types instead of Wrapper Classes

    Use primitive data types instead of wrapper class for storing values. As wrapper class object leads more memory overhead.

  7. Use StringBuffer rather than the string concatenation operator (+)

    As you all know, String is immutable class means each time you doing any modification to String object a new String object is get created in heap memory. Use StringBuffer where modification required. Don’t ever using string concatenation in loop which leads a memory leak.

  8. Use short-circuit boolean operators(&&,||) instead of the normal boolean operators(&,|)

    The && and || operators “short-circuit”, meaning they don’t evaluate the right hand side if it isn’t necessary. The & and | operators, when used as logical operators, always evaluate both sides.

  9. Always release resource object

    Always release database connection,InputStream or any other resource object. Use try-with-resources which is added in Java 7. It automatically releases the resource object.

    Closing BufferedReader object after completing I/O operations

    try (BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")))
    {
    	String line;
    	 while ((line = br.readLine()) != null) {
    				System.out.println(line);
    	}
    } catch (IOException e) {
      e.printStackTrace();
    }
    

    Closing Connection object after completing database operations

    try (Connection con = DriverManager.getConnection(myConnectionURL,user,password);
             PreparedStatement ps = con.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                while(rs.next()) {
                    users.add(new User(rs.getInt("id"), rs.getString("name")));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    
  10. Always handle exceptions don’t ignore them

    As you know while an exception occurred the application abnormally stops the execution which bad programming practice. It is recommended to handle each exception so that the application doesn’t stop abnormally.

  11. Use static variables, if fields values are common among multiple objects

    Some variables value are common among objects then it should not be associated them with object. Like you have a schoolName field which is common among all students objects then this field should be static rather instance variable.

  12. Avoid Synchronization in single threaded environment

    Synchronized methods are slower than the non-synchronized one so make method synchronize only if there multiple threads access it. Don’t make whole method as synchronized rather use synchronize block for critical section.

  13. Choose right Collection Class

    As there are several collection class, according your requirement you need to choose best one. If you need fast traversal then choose ArrayList rather than LinkedList. Read More

  14.  Use PreparedStatement instead of Statement in JDBC

    PreparedStatement is used for executing parametric query. It provides prevention from SQL injection

  15. Use ConnectionPool while creating connection object in JDBC

    Creating a network connection to a database server is  relatively expensive. Likewise asking the server to prepare a SQL statement is relatively expensive. Using a connection/statement pool, you can reuse existing connections/prepared statements, avoiding the cost of initiating a connection, parsing SQL etc.

  16. Use Frameworks for building application

    There are lots frameworks available each of them solve a unique problem. You can choose one of them as your requirements. Learn most popular frameworks like Spring Boot,Hibernate,Struts 2.

  17. Do unit testing for your module

    Unit tests are written and executed by developers. Most of the time a testing framework like JUnit or TestNG is used. With unit tests you can verify your program behavior in different scenarios.

  18. Use open source logging library instead of System.out.println

    Logging helps you to keep track of your application flow and also get the information about the failure happened. Log4J and SLF4J are logging library available you can use one of them.

Leave a Reply