13 Essential Java Coding Practices to Boost Performance and Cleanliness

This article presents a comprehensive guide to writing more standardized Java code, covering topics such as avoiding "1=1" in MyBatis, iterating Map entrySet, pre‑sizing collections, using StringBuilder, preferring Set for contains checks, proper static initialization, removing unused variables, shielding utility constructors, eliminating redundant exception handling, using String.valueOf, avoiding BigDecimal(double), returning empty collections instead of null, safe equals usage, immutable enum fields, and correctly escaping regex in String.split, each illustrated with clear code examples.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
13 Essential Java Coding Practices to Boost Performance and Cleanliness

1. MyBatis should not use "where 1=1" for multiple conditions

Adding "where 1=1" makes the database unable to use indexes, leading to full table scans and potential SQL injection risks.

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
  select count(*) from t_rule_BookInfo t where 1=1
  <if test="title !=null and title !='' "> AND title = #{title} </if>
  <if test="author !=null and author !='' "> AND author = #{author} </if>
</select>
<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
  select count(*) from t_rule_BookInfo t
  <where>
    <if test="title !=null and title !='' "> title = #{title} </if>
    <if test="author !=null and author !='' "> AND author = #{author} </if>
  </where>
</select>

For UPDATE statements, use <set> instead of "1=1".

2. Iterate entrySet() to get Map keys and values

When both key and value are needed, entrySet() is more efficient than iterating keySet() and calling get() for each key.

// Anti‑pattern: iterate keySet and call get
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()) {
    String value = map.get(key);
}
// Correct: iterate entrySet
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

3. Use Collection.isEmpty() to check emptiness

Using isEmpty() improves readability and guarantees O(1) time, while size() may be O(n) for some collections.

LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()) {
    System.out.println("collection is empty.");
}
// Or using CollectionUtils.isEmpty(collection)

4. Specify collection size during initialization

Pre‑allocating capacity reduces the number of costly resize operations (typically O(n)).

// Anti‑pattern: default capacity
List<Integer> list = new ArrayList<>();
for (int i : arr) {
    list.add(i);
}
// Correct: set initial capacity
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
    list.add(i);
}

5. Use StringBuilder for string concatenation inside loops

Compilers cannot optimise concatenation inside loops, so StringBuilder should be used to avoid excessive temporary objects.

// Anti‑pattern
String str = "";
for (int i = 0; i < 10; i++) {
    str += i; // no optimisation
}
// Correct
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i);
}
String result = sb.toString();

6. Use Set when contains() is called frequently

List.contains()

is O(n); converting the list to a HashSet makes the operation O(1).

// Anti‑pattern
if (list.contains(i)) {
    // O(n)
}
// Correct
Set<Object> set = new HashSet<>(list);
if (set.contains(i)) {
    // O(1)
}

7. Initialise static collection members in a static block

Assign values to static collections inside a static initializer instead of using an anonymous subclass.

// Anti‑pattern
private static Map<String, Integer> map = new HashMap<String, Integer>() {{
    put("Leo", 1);
    put("Family-loving", 2);
}};
// Correct
private static Map<String, Integer> map = new HashMap<>();
static {
    map.put("Leo", 1);
    map.put("Family-loving", 2);
}

8. Remove unused local variables, method parameters, private methods, fields and redundant brackets

Cleaning dead code improves readability and reduces maintenance overhead.

9. Shield utility class constructors

Declare a private constructor to prevent accidental instantiation of classes that only contain static members.

// Anti‑pattern
public class PasswordUtils {
    // implicit public constructor
}
// Correct
public class PasswordUtils {
    private PasswordUtils() {}
    // static members only
}

10. Eliminate redundant catch blocks that only re‑throw

If a catch block does nothing but re‑throw, remove it or add meaningful handling.

// Anti‑pattern
try {
    // code
} catch (Exception e) {
    throw e; // no handling
}
// Correct (remove catch or add handling)
try {
    // code
} // optional handling here

11. Use String.valueOf(value) instead of "" + value

String.valueOf

is more efficient than concatenating with an empty string.

int num = 520;
String str = String.valueOf(num); // preferred

12. Avoid BigDecimal(double) due to precision loss

Construct BigDecimal from String or valueOf to preserve exact value.

BigDecimal bd = BigDecimal.valueOf(0.11); // correct
Precision loss illustration
Precision loss illustration

13. Return empty arrays or collections instead of null

Returning empty results prevents NullPointerException and simplifies caller code.

// Anti‑pattern
public static Result[] getResults() { return null; }
// Correct
public static Result[] getResults() { return new Result[0]; }

14. Call equals() on a constant or known non‑null object

This avoids possible NullPointerException.

// Anti‑pattern
return fileName.equals("Charming"); // may NPE
// Correct
return "Charming".equals(fileName);
// or Objects.equals(fileName, "Charming")

15. Enum fields should be private, final and immutable

Declare enum attributes as private final and provide only getters.

public enum SwitchStatus {
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");
    private final int value;
    private final String description;
    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }
    public int getValue() { return value; }
    public String getDescription() { return description; }
}

16. Escape special characters in String.split(String regex)

Since the argument is a regular expression, characters like . and | must be escaped.

// Incorrect
String[] parts = "a.ab.abc".split("."); // results in empty array
// Correct
String[] parts = "a.ab.abc".split("\\."); // ["a", "ab", "abc"]
String.split regex illustration
String.split regex illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaperformancecoding standardsMyBatisExceptions
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.