Item - 6 Avoid Creating Unnecessary Objects
This writing will discuss item 6 in Effective Java, recommended by Joshua Bloch.
The recommendation of the author in item 6 is simple. You should not avoid creating unnecessary objects.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Log {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Bad example
*
* @param message
*/
public void logMessageBadExample(String message) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = dateFormat.format(new Date());
System.out.println("---> Message received: " + timestamp + " - " + message);
}
/**
* Good Example
*
* @param message
*/
public void logMessageGoodExample(String message) {
String timestamp = dateFormat.format(new Date());
System.out.println("---> Message received: " + timestamp + " - " + message);
}
}
As you can see good and bad examples. Your API gets many client requests, and the system logs each request. If you use a terrible example method, you create SimpleDateFormat each time for nothing. But if you use a good example, you avoid creating unnecessary SimpleDateFormat objects. Therefore the system will save memory and performance.
Benefits of avoiding creating unnecessary objects.
It reduces memory usage, improving your code's performance and scalability.
It reduces garbage collection overhead, improving the responsiveness of your code.
You can use some technics to avoid creating unnecessary objects, such as static factory methods, primitive types, and reusable objects.
REFERENCES
Bloch, Joshua. Effective Java Programming Third Edition. [1]