Java Best Practices


1. Use logging. Never use system.out.print().

For long-running programs, you’ll need to look at the log files to check that the program is functioning correctly.

2. For the scheduled task thread or any thread other than the main thread, catch the entire code block exception.

Generally, the main thread has global exception handling, but other threads do not.

3. No empty catch blocks.

An empty catch block won’t give you any information about what exception occurred. Probably the exception doesn’t matter, but it’s still an exceptional case.

4. Separate business and functional code.

Businesses are changing and functions are shared and reusable.

5. Divide your code by domain rather than by functionality or class type.

Usually, changes in your application are related to a specific domain, you should focus on business domains when building your structures, not functionality or class type.

6. Don’t create unnecessary variables, objects in a loop block.

Be careful when creating objects in a loop block. Create objects before a loop block if possible. Don’t create a lot of unnecessary objects in a loop block. For example, java.text.SimpleDateFormat, org.apache.poi.xssf.usermodel.XSSFCellStyle objects.

7. Don’t use Java internal code. All classes in com.sun.*, sun.*, or jdk.*are notionally internal, and should not be used directly in your code. All the classes you can use are in the Java API documentation, such as java.*, javax.*, and org.*.

Data Access

1. Never execute SQL statements in a for loop.

It takes a lot of time. You should find a way to do it in bulk.

Java Web and Spring Boot

1. Scheduling tasks should run when a specific profile is activated.

If the project is deployed on multiple servers, each server will execute scheduled tasks. Even if it activates different profiles on different servers.

2. API URLs use domain names rather than IP addresses.

If you use IP-based API URLs in many projects, you need to change many projects whenever the IP address changes.

3. Use Environment Variables in spring boot configuration files.

Don’t expose your confidential information in source code.