Java code Tips

(1) In logger statements use Format specifiers instead of string concatenation. 

logger.info("Completed populating RAW data from the file " + fileId + " ,Took " + (System.currentTimeMillis() - dataEntryTime) + " ms."));

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created.

logger.info(String.format("Completed populating RAW data from the file %s ,Took %d ms.", fileId, (System.currentTimeMillis() - dataEntryTime)));
Prefer the following log statement
logger.info( "Completed populating RAW data from the file {} ,Took {} ms.
",fileId, (System.currentTimeMillis() - dataEntryTime));
{} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not.

(2) Try-with-resources should be used

Java 7 introduced the try-with-resources statement, which guarantees that the resource in question will be closed. Since the new syntax is closer to bullet-proof, it should be preferred over the older try/catch/finally version.
This rule checks that close-able resources are opened in a try-with-resources statement.


(3) "java.nio.Files#delete" should be preferred

When java.io.File#delete fails, this boolean method simply returns false with no indication of the cause. On the other hand, when java.nio.file.Files#delete fails, this void method returns one of a series of exception types to better indicate the cause of the failure. And since more information is generally better in a debugging situation, java.nio.file.Files#delete is the preferred option.
if (null != tempFile) {
	tempFile.delete();	
}
instead use the following
try {
	if (null != tempFile) {
		Files.delete(tempFile.toPath());
	}
} catch (Exception ex) {
	logger.error("Error", ex);
}

(4) Null checks

for an object foo, the following is the best way to check for null

if(foo != null && foo.bar()) {
   someStuff();
}
Java 7 introduced the new Objects API
Objects.isNull(obj) //returns true if the object is null

Objects.nonNull(obj) //returns true if object is not-null

if(Objects.nonNull(foo) && foo.something())
Here are some good documentations
https://www.baeldung.com/java-avoid-null-check
https://stackoverflow.com/questions/17302256/best-way-to-check-for-null-values-in-java/40777583#:~:text=In%20Java%208%2C%20the%20best,not%2Dnull%20if(Objects.


(5) Package name naming convention

This is the convention  ^[a-z_]+(\.[a-z_][a-z0-9_]*)*$: so no Upper case.


(6) Avoid instantiating objects in a loop

ogger.info("Start Time : {} and End Time : {} for {}", new Date(1565601480000L).toInstant(), new Date(1565601480000L).toInstant(), "check");
Instead use 

logger.info("Start Time : {} and End Time : {} for {}", Instant.ofEpochMilli(1565601480000L), Instant.ofEpochMilli(1565601480000L), "check");

(7) Use Varangs when possible

The following method call 
combineData(Employee e1, Employee e2, Employee e3);

The method can be written using varangs as shown below.
private void combineData (Employee... emp) {

        // Here is how you access the individual objects
Employee e1 = emp[0];
Employee e2 = emp[1];
Employee e3 = emp[2];


(8) Uncheck or raw use of ArrayList

return new ArrayList(new TreeMap<Long, ProcessedDataInfo.ProcessedDataRow>(combinedDataMap).values());

instead use the following

return new ArrayList<>(new TreeMap<Long, ProcessedDataInfo.ProcessedDataRow>(combinedDataMap).values());


(9) Utility classes should not have a public constructor

Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.

So the following Utility class

public class Constants {

    public static final Long ONE_HOUR = 1000*60*60L;
    public static final Long TWENTY_MINUTES = 20*60*1000L;
    public static final Long THIRTY_MINUTES = 30*60*1000L;
}

should be like this

private Constants () {
throw new IllegalStateException("Utility class");
}

(10) Source code lines
NCSS (Non commented source code lines) should not exceed 1500 per PMD tool. 

(11) Whenever you write a method always consider The Law of Demeter
Its about loose coupling
  1. Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  2. Each unit should only talk to its friends; don't talk to strangers.
  3. Only talk to your immediate friends.
 


No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days