Saturday, 13 June 2020

Java Best Practices to write readable and maintainable code

From my understanding and experience following are the few best practices to write readable and maintainable code

Variables:

Methods:

Exceptions:


As shown in the above diagram never ever catch Throwable

We can use Throwable in a catch clause, but we should never do it! If we use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application

Also we should avoid using directly Exception  in the catch block. Try to handle specific exception
Ex:

try{
      readFile();
    }
catch(FileNotFoundException) { }

In catch block,
1) Do not print stacktrace ,  instead use any logging framework
    Ex : catch(.... ex){
                               log.error(ex);
                               }
2) Throw the exception using custom exception wherever appropriate

Class

The class should meet following important principle
1. Follow SRP - Single Responsibility Principle
2. Program to an Interface
3. Maintain Strong Encapsulation within Class
4. Maintain high Cohesion
5. Always try to have minimum Coupling
6 . Use Dependency Injection
7.  Principle of Proximity i.e. well organized methods

SOLID Principle
Single Responsibility Principle
Open Closed Principle'
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion

Comments

- Use JavaDoc format if necessary
- Always remove commented out code before pushing to version control system i.e svn or git
- Use comments if necessary, it should not compensate for buggy code. Prefer giving comments only for public methods wherever necessary


Tests(Junit/Mockito)

- Always verify one thing per test
- 1 assertion per test (Except-few cases where it is not applicable)
- No if branching in tests

Test should have basic template like as shown below

 Arrange
   - Setup and initialize the objects and the environment
  Act
    - Exercise the functionality under test
 Assert
    - Verify the result

Test Pattern
AAA - Arrange-Act-Assert
BDD - Given - When - Then

Other Points
- Install Static Code Checker like SonarLint 




=====================Reference=================================
Google Java Style Guide
https://google.github.io/styleguide/javaguide.html

Mr. Andrejs Doronins Java Readability & Maintainability Course