Common Java Coding Pitfalls and Best‑Practice Recommendations

This article enumerates typical Java coding mistakes—such as using "where 1=1" in MyBatis, iterating Map inefficiently, neglecting Collection.isEmpty, omitting collection size hints, concatenating strings in loops, overusing List.contains, misusing static initializers, keeping redundant code, and more—while providing concise, performance‑oriented corrections with clear examples.

Java Captain
Java Captain
Java Captain
Common Java Coding Pitfalls and Best‑Practice Recommendations

1. Avoid "where 1=1" in MyBatis queries – Adding a constant filter forces a full table scan and prevents index usage, leading to severe performance loss and possible SQL‑injection risk. Use <where> tags to conditionally add predicates instead.

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

2. Iterate entrySet() to obtain Map keys and values – When both key and value are needed, iterating entrySet() avoids the extra get() lookup and improves performance.

for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

3. Use Collection.isEmpty() instead of checking size – isEmpty() is O(1) and makes intent clearer than size() == 0.

if (collection.isEmpty()) {
    System.out.println("collection is empty.");
}

4. Specify collection capacity when initializing – Pre‑allocating the expected size reduces the number of costly resize operations (which are O(n)).

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 – The compiler cannot optimise repeated += operations in a loop, so a mutable builder should be used.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i);
}

6. Replace frequent List.contains() with a Set – contains() on a List is O(n); a HashSet provides O(1) lookup.

Set<Object> set = new HashSet<>();
// populate set
if (set.contains(i)) {
    System.out.println("list contains " + i);
}

7. Initialise static members in a static block – For collections or maps, assign values inside a static initializer rather than using an anonymous subclass.

private static Map<String, Integer> map = new HashMap<>();
static {
    map.put("Leo", 1);
    map.put("Family-loving", 2);
    map.put("Cold on the outside passionate on the inside", 3);
}

private static List<String> list = new ArrayList<>();
static {
    list.add("Sagittarius");
    list.add("Charming");
    list.add("Perfectionist");
}

8. Remove unused local variables, method parameters, private methods, fields, and superfluous parentheses – Clean code improves readability and reduces maintenance overhead.

9. Hide utility‑class constructors – Declare a private no‑arg constructor to prevent accidental instantiation of classes that only contain static members.

public class PasswordUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
    private PasswordUtils() { }
    // static utility methods …
}

10. Eliminate redundant catch blocks that only re‑throw – If no handling is performed, the catch can be removed or replaced with proper handling logic.

private static String fileReader(String fileName) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
        // removed empty catch block
    }
}

11. Prefer String.valueOf(value) over "" + value – The former avoids creating an intermediate StringBuilder and is more efficient.

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

12. Avoid new BigDecimal(double) – Use BigDecimal.valueOf(double) to prevent precision loss. BigDecimal bd = BigDecimal.valueOf(0.11D); 13. Return empty arrays or collections instead of null – This prevents NullPointerException and simplifies client code.

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

14. Call equals() on a constant or known non‑null object – This avoids potential NullPointerException.

return "Charming".equals(fileName);
// or
return Objects.equals("Charming", fileName);

15. Make enum fields private and immutable – Declare fields as private final and provide only getters; do not expose setters.

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 regex metacharacters when using String.split() – Characters such as . and | must be escaped.

String[] parts = "a.ab.abc".split("\\."); // ["a", "ab", "abc"]
String[] parts2 = "a|ab|abc".split("\\|"); // ["a", "ab", "abc"]

By following these guidelines, Java developers can write cleaner, more efficient, and less error‑prone code.

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.

JavaperformanceException HandlingCode OptimizationCollections
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

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.