Backend Development 14 min read

How to Write More Standardized Java Code

This article presents a comprehensive set of Java coding best‑practice guidelines—ranging from MyBatis query writing, efficient Map iteration, collection handling, StringBuilder usage, to proper enum design and exception handling—each illustrated with clear anti‑pattern and correct‑pattern code examples.

Java Captain
Java Captain
Java Captain
How to Write More Standardized Java Code

The article provides a detailed checklist for writing cleaner, more efficient, and safer Java code, emphasizing performance, readability, and maintainability.

1. Avoid using where 1=1 in MyBatis – Adding a dummy condition prevents the database from using indexes, leading to full‑table scans and possible SQL‑injection risks. Use <where> 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 !='' "> AND 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 extra lookups and improves performance.

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

3. Use Collection.isEmpty() instead of checking size() – isEmpty() is O(1) and more readable; size() may be O(n) for some collections.

if (collection.isEmpty()) {
    System.out.println("collection is empty.");
}
// For null‑safe check
if (CollectionUtils.isEmpty(collection)) {
    System.out.println("collection is null.");
}

4. Specify collection initial capacity – Pre‑allocating the expected size reduces costly resizing operations.

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

5. Use StringBuilder for string concatenation inside loops – Direct += concatenation cannot be optimized by the compiler in loops.

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

6. Replace frequent List.contains() with a Set – Converting a list to a HashSet changes the lookup from O(n) to O(1).

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

7. Initialise static members in a static block – Avoid inline collection initialisation that creates an anonymous subclass.

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

8. Remove unused variables, parameters, methods, and redundant parentheses – Clean code should contain only necessary elements.

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

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

10. Eliminate redundant catch‑and‑rethrow blocks – If the catch block does nothing but rethrow, remove it or add meaningful handling.

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();
    }
    // No empty catch needed
}

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

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 caller code.

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

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

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

15. Make enum fields private, final, and immutable – Do not provide setters; keep fields immutable.

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 meta‑characters in String.split() – Characters like . and | must be escaped.

String[] split2 = "a.ab.abc".split("\\.");
String[] split3 = "a|ab|abc".split("\\|");
JavaPerformancebest-practicescoding standardsMyBatisCollectionsexceptions
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

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