Boost Java Code Quality: Essential Practices to Eliminate Bad Smells

This article compiles practical Java best‑practice tips—from using entrySet() for map iteration and Collection.isEmpty() for emptiness checks to pre‑sizing collections, avoiding magic numbers, employing try‑with‑resources, and cleaning unused code—helping developers write more efficient, readable, and bug‑free code.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Boost Java Code Quality: Essential Practices to Eliminate Bad Smells

Prefer entrySet() when both key and value are needed

Iterating keySet() and then calling get() is less efficient than iterating entrySet(), which provides both key and value directly.

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

Use Collection.isEmpty() to check emptiness

isEmpty()

is O(1) and more readable than size() == 0, which may be O(n) for some collections.

if (collection.isEmpty()) {
    // ...
}

Avoid passing a collection to itself

Passing a collection to methods that expect it to remain unchanged can cause unexpected behavior.

List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
if (list.containsAll(list)) { // always true, meaningless
    // ...
}
list.removeAll(list); // inefficient, use clear()

Pre‑size collections when possible

Specifying an initial capacity reduces costly resizing operations.

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

Use StringBuilder for concatenation inside loops

String concatenation in a loop should be replaced with StringBuilder to avoid repeated object creation.

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

Check for RandomAccess before random list access

If a List implements RandomAccess, random indexing is efficient; otherwise, consider alternative traversal.

List<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
    System.out.println(list.get(list.size() - 1));
} else {
    // fallback for linked‑list implementation
}

Convert frequently used List.contains() to a Set

Transforming a list to a HashSet reduces the lookup from O(n) to O(1).

ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet<>(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    set.contains(i); // O(1)
}

Prefer try‑with‑resources

Java 7’s try‑with‑resources automatically closes resources, making code safer and shorter.

private void handle(String fileName) {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = reader.readLine()) != null) {
            // ...
        }
    } catch (Exception e) {
        // handle
    }
}

Remove unused private fields, methods, and parameters

Eliminate dead code to keep the codebase clean; keep in mind that overridden methods must retain their signature.

public class DoubleDemo1 {
    public int sum(int a, int b) {
        return a + b;
    }
}

Avoid magic numbers; define constants instead

Replace literal numbers with named constants for clarity and maintainability.

private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++) {
    // ...
}

Make utility classes non‑instantiable

Declare a private constructor to prevent accidental instantiation.

public class MathUtils {
    public static final double PI = 3.1415926;
    private MathUtils() {}
    public static int sum(int a, int b) { return a + b; }
}

Return empty collections/arrays instead of null

Returning empty results avoids null‑pointer checks for callers.

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

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

Calling constant.equals(variable) prevents NullPointerException.

return OrderStatus.FINISHED.equals(status);
// or
return Objects.equals(status, OrderStatus.FINISHED);

Make enum fields private and immutable

Enum attributes should be private final with no setters.

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

Escape regex metacharacters in String.split()

Remember that the argument to split() is a regular expression.

"a.ab.abc".split("\\."); // -> ["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // -> ["a", "ab", "abc"]

Summary

This Java‑focused guide collects practical tips to avoid common pitfalls, improve performance, and write cleaner, more maintainable 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.

Javacode qualityrefactoring
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

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.