Automation QA Testing Course Content

Best Practices and Examples in Java

 

Use clear and meaningful variable names

One of the most important principles of clean code is to use clear and meaningful variable names. This makes it easy for other developers to understand what your code is doing and reduces the likelihood of bugs. For example, instead of using a variable named “d” to represent the distance, use a variable named “distance”.

// Bad
int d = getDistance();

// Good
int distance = getDistance();

Use appropriate data types

Another important principle of clean code is to use appropriate data types. This ensures that your code will work correctly and reduces the likelihood of bugs. For example, instead of using a string to represent an age, use an integer.

// Bad
String age = "25";

// Good
int age = 25;

Keep methods short and focused

Clean code is also about keeping methods short and focused. A method should only do one thing and should be easy to understand. This makes it easier to test and maintain your code. For example, instead of putting all the code for processing an order in one method, break it up into smaller methods for validation, calculation, and saving.

// Bad
public void processOrder(Order order) {
// lots of code
}

// Good
public void processOrder(Order order) {
validateOrder(order);
calculateTotal(order);
saveOrder(order);
}

Write clear and meaningful comments

Another important principle of clean code is to write clear and meaningful comments. Comments should explain why the code is doing something, not how it is doing it. This makes it easier for other developers to understand your code.

// Bad
// increments count
count++;

// Good
// Increment the count by 1
count++;

Use whitespace and indentation to improve readability

Clean code is also about making it easy to read. Use whitespace and indentation to improve the readability of your code. This makes it easier for other developers to understand what your code is doing.

// Bad
if(a==b){c=d;}

// Good
if (a == b) {
c = d;
}

Use exception handling in a proper way

Clean code is also about handling exceptions in a proper way. You should catch only the exceptions that you can handle, and handle them in a specific way. Avoid catch-all exception handlers.

// Bad
try {
// some code
} catch (Exception e) {
// handle exception
}

// Good
try {
// some code
} catch (IllegalArgumentException e) {
// handle specific exception
} catch (Exception e) {
// handle general exception
}

Use encapsulation to hide implementation details

Encapsulation is a technique that helps to hide the implementation details of a class and make it more flexible and extensible. By using encapsulation, you can change the implementation of a class without affecting the rest of the code.

// Bad
public class BankAccount {
public double balance;
// other methods
}

// Good
public class BankAccount {
private double balance;
// other methods
}

Use inheritance and polymorphism to write reusable code

Inheritance and polymorphism are powerful features of object-oriented programming that allow you to write reusable code. By using inheritance, you can create a base class that contains common code and then create subclasses that inherit that code. By using polymorphism, you can write code that works with objects of different classes in a generic way.

// Bad
public class Square {
// code specific to squares
}

public class Circle {
// code specific to circles
}

// Good
public class Shape {
// common code for all shapes
}

public class Square extends Shape {
// code specific to squares
}

public class Circle extends Shape {
// code specific to circles
}

Use design patterns to solve common problems

Design patterns are solutions to common programming problems that have been proven to work. By using design patterns, you can write code that is easy to understand and maintain. For example, the strategy pattern is a design pattern that allows you to write code that is flexible and easy to extend.

// Bad
public class OrderProcessor {
public void processOrder(Order order) {
// lots of code
}
}

// Good
public class OrderProcessor {
public void processOrder(Order order) {
OrderStrategy strategy = new OrderStrategy(order);
strategy.process();
}
}

Use unit tests to ensure code works as expected

Clean code is also about testing. By writing unit tests, you can ensure that your code works as expected and that it is easy to maintain. Unit tests are automated tests that test individual units of code.

public class BankAccountTest {
@Test
public void testDeposit() {
BankAccount account = new BankAccount();
account.deposit(100);
assertEquals(100, account.getBalance());
}
}

Use code review, pair programming, and mentoring to improve the code quality

Clean code is also about collaboration. By using code review, pair programming, and mentoring, you can improve the quality of your code and make it easier to understand and maintain.

Use good naming convention and make use of code formatter

Naming is an important aspect of clean code, it should be self-describing, consistent and reflective of the code’s purpose. Also, using code formatter like checkstyle, sonarqube can help to maintain the standard of the code.

Use logging and monitoring tools

In order to identify and troubleshoot the issues in the code, it is important to use logging and monitoring tools like log4j, slf4j, etc.


readFile from resource folder

 

package com.qa.opencart.factory;

import java.io.File;

import java.net.URISyntaxException;

import java.net.URL;


public class ReadFile {

/*

    The resource URL is not working in the JAR

    If we try to access a file that is inside a JAR,

    It throws NoSuchFileException (linux), InvalidPathException (Windows)


    Resource URL Sample: file:java-io.jar!/json/file1.json

 */

private String getFileFromResource(String fileName) throws URISyntaxException{


    ClassLoader classLoader = getClass().getClassLoader();

    URL resource = classLoader.getResource(fileName);

    if (resource == null) {

        throw new IllegalArgumentException("file not found! " + fileName);

    } else {


        // failed if files have whitespaces or special characters

        //return new File(resource.getFile());


        return new File(resource.toURI()).getAbsolutePath();

    }


}

public static void main(String[] args) throws URISyntaxException {

// TODO Auto-generated method stub

String str =new ReadFile().getFileFromResource("log4j2.xml");


System.out.println(str);

}


}


Java Code Editor