16 Java Coding Best Practices for Performance and Clean Code

This article presents sixteen practical Java coding best‑practice guidelines—including avoiding ‘where 1=1’ in MyBatis, using entrySet for map iteration, preferring Collection.isEmpty(), pre‑sizing collections, employing StringBuilder, leveraging Set for contains checks, static initialization blocks, and other tips—to improve performance, readability, and safety of backend applications.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
16 Java Coding Best Practices for Performance and Clean Code

1. Avoid "where 1=1" in MyBatis

Using where 1=1 can prevent the database from using indexes, leading to full‑table scans and potential SQL‑injection risks.

Incorrect example:

<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>

Correct example (use <where> tag):

<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 !='' ">
      AND title = #{title}
    </if>
    <if test="author !=null and author !='' ">
      AND author = #{author}
    </if>
  </where>
</select>

2. Iterate Maps with entrySet() when both key and value are needed

Iterating over keySet() and then calling get() incurs extra lookups; entrySet() is more efficient.

Incorrect example:

// Map get value – anti‑pattern
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()) {
    String value = map.get(key);
}

Correct example:

// Map get key & value – proper usage
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() instead of size() == 0

isEmpty()

is O(1) and makes intent clearer.

Incorrect example:

LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0) {
    System.out.println("collection is empty.");
}

Correct example:

LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()) {
    System.out.println("collection is empty.");
}
// Null‑safe check using Spring's CollectionUtils
if (CollectionUtils.isEmpty(collection)) {
    System.out.println("collection is null.");
}

4. Pre‑size collections when possible

Specifying an initial capacity reduces costly resizing operations.

Incorrect example:

int[] arr = new int[]{1,2,3,4};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
    list.add(i);
}

Correct example:

int[] arr = new int[]{1,2,3,4};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
    list.add(i);
}

5. Use StringBuilder for string concatenation inside loops

Plain += concatenation cannot be optimized inside loops.

Incorrect example:

String str = "";
for (int i = 0; i < 10; i++) {
    // Java does not optimize this inside a loop
    str += i;
}

Correct example:

String str1 = "Love";
String str2 = "Courage";
String strConcat = str1 + str2; // compile‑time optimization
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i);
}

6. Replace frequent List.contains() checks with a Set

Contain checks on a List are O(n); a HashSet provides O(1).

Incorrect example:

List<Object> list = new ArrayList<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // O(n) lookup
    if (list.contains(i)) {
        System.out.println("list contains " + i);
    }
}

Correct example:

List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // O(1) lookup
    if (set.contains(i)) {
        System.out.println("list contains " + i);
    }
}

7. Initialise static collections in a static block, not via anonymous inner classes

Using an anonymous subclass for initialisation adds hidden references and can cause memory leaks.

Incorrect example:

private static Map<String, Integer> map = new HashMap<String, Integer>(){
    {
        map.put("Leo",1);
        map.put("Family-loving",2);
        map.put("Cold on the out side passionate on the inside",3);
    }
};
private static List<String> list = new ArrayList<>(){
    {
        list.add("Sagittarius");
        list.add("Charming");
        list.add("Perfectionist");
    }
};

Correct example:

private static Map<String, Integer> map = new HashMap<String, Integer>();
static {
    map.put("Leo",1);
    map.put("Family-loving",2);
    map.put("Cold on the out side passionate on the inside",3);
}
private static List<String> list = new ArrayList<>();
static {
    list.add("Sagittarius");
    list.add("Charming");
    list.add("Perfectionist");
}

8. Hide utility‑class constructors

Utility classes should not be instantiated; declare a private constructor to suppress the default public one.

Incorrect example:

public class PasswordUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
    public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
    public static String encryptPassword(String aPassword) throws IOException {
        return new PasswordUtils(aPassword).encrypt();
    }
}

Correct example:

public class PasswordUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
    // Private constructor prevents instantiation
    private PasswordUtils() {}
    public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
    public static String encryptPassword(String aPassword) throws IOException {
        return new PasswordUtils(aPassword).encrypt();
    }
}

9. Remove redundant catch blocks that only re‑throw

If the catch block does nothing but re‑throw, it can be omitted.

Incorrect example:

private static String fileReader(String fileName) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (Exception e) {
        // merely re‑throwing
        throw e;
    }
}

Correct example:

private static String fileReader(String fileName) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
        // optional: handle other exceptions here
        /*catch (Exception e) {
            return "fileReader exception";
        }*/
    }
}

10. Prefer String.valueOf() over concatenation with an empty string

String.valueOf()

avoids creating intermediate String objects.

Incorrect example:

int num = 520;
String strLove = "" + num;

Correct example:

int num = 520;
String strLove = String.valueOf(num);

11. Avoid new BigDecimal(double) due to precision loss

Construct BigDecimal from String or valueOf instead.

Incorrect example: BigDecimal bigDecimal = new BigDecimal(0.11D); Correct example:

BigDecimal bigDecimal1 = BigDecimal.valueOf(0.11D);

12. Return empty collections/arrays instead of null

Returning empty objects prevents NullPointerException and simplifies caller code.

Incorrect example:

public static Result[] getResults() { return null; }
public static List<Result> getResultList() { return null; }
public static Map<String, Result> getResultMap() { return null; }

Correct example:

public static Result[] getResults() { return new Result[0]; }
public static List<Result> getResultList() { return Collections.emptyList(); }
public static Map<String, Result> getResultMap() { return Collections.emptyMap(); }

13. Call equals() on a constant or use Objects.equals()

Calling equals() on a potentially null variable can throw an exception.

Incorrect example:

private static boolean fileReader(String fileName) throws IOException {
    return fileName.equals("Charming"); // may NPE
}

Correct example:

private static boolean fileReader(String fileName) throws IOException {
    return "Charming".equals(fileName);
    // or
    return Objects.equals("Charming", fileName);
}

14. Make enum fields private and final without setters

Enums should be immutable; expose values via getters only.

Incorrect example:

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

Correct example:

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; }
}

15. Escape regex metacharacters when using String.split()

Characters like . and | are regex operators and must be escaped.

Incorrect example:

String[] split = "a.ab.abc".split(".");
System.out.println(Arrays.toString(split)); // []
String[] split1 = "a|ab|abc".split("|");
System.out.println(Arrays.toString(split1)); // ["a","|","a","b","|","a","b","c"]

Correct example:

String[] split2 = "a.ab.abc".split("\\.");
System.out.println(Arrays.toString(split2)); // ["a","ab","abc"]
String[] split3 = "a|ab|abc".split("\\|");
System.out.println(Arrays.toString(split3)); // ["a","ab","abc"]

By following these sixteen guidelines, Java developers can write code that is faster, safer, and easier to maintain.

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.

BackendJavaperformanceCode Optimizationbest practicesMyBatisCollections
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

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.