Common Java Coding Pitfalls and Recommended Best Practices
This article presents a collection of typical Java coding mistakes—such as using "where 1=1" in MyBatis, iterating maps inefficiently, neglecting Collection.isEmpty, improper collection initialization, string concatenation in loops, and more—along with clear, performance‑oriented alternatives and code examples to help developers write cleaner, safer, and faster backend code.
1. Avoid "where 1=1" in MyBatis
Using where 1=1 to simplify dynamic conditions prevents the database from using indexes and may cause full‑table scans and SQL‑injection risks.
Bad 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>Good example:
<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 get Map keys and values
When both key and value are needed, iterating entrySet() is more efficient than iterating keySet() and calling get() for each key.
// Bad
for (String key : map.keySet()) {
String value = map.get(key);
}
// Good
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}3. Use Collection.isEmpty() instead of size check
isEmpty()is O(1) and makes the intent clearer.
// Bad
if (collection.size() == 0) { ... }
// Good
if (collection.isEmpty()) { ... }
// Also, CollectionsUtils.isEmpty() can check for null.4. Specify collection size at initialization
Pre‑allocating capacity reduces costly resizing operations.
// Bad
List<Integer> list = new ArrayList<>();
for (int i : arr) { list.add(i); }
// Good
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) { list.add(i); }5. Use StringBuilder for string concatenation in loops
// Bad
String str = "";
for (int i = 0; i < 10; i++) {
str += i; // no compile‑time optimisation
}
// Good
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}6. Replace frequent List.contains() with a Set
Lookup in a HashSet is O(1) compared to O(n) for a list.
// Bad
if (list.contains(i)) { ... }
// Good
Set<Object> set = new HashSet<>(list);
if (set.contains(i)) { ... }7. Initialise static collection members in a static block
// Bad
private static Map<String,Integer> map = new HashMap<String,Integer>(){{
put("Leo",1);
}};
// Good
private static Map<String,Integer> map = new HashMap<>();
static {
map.put("Leo",1);
}8. Remove unused variables, parameters, methods and redundant parentheses
Clean code improves readability and reduces maintenance cost.
9. Hide utility‑class constructors
Declare a private constructor to prevent accidental instantiation.
// Bad
public class PasswordUtils { ... }
// Good
public class PasswordUtils {
private PasswordUtils() {}
...
}10. Delete redundant catch blocks that only re‑throw
// Bad
try { ... } catch (Exception e) { throw e; }
// Good
try { ... } // no catch needed, or add real handling11. Prefer String.valueOf(value) over "" + value
int num = 520;
String s = String.valueOf(num); // faster than "" + num12. Avoid BigDecimal(double)
// Bad
BigDecimal bd = new BigDecimal(0.11D);
// Good
BigDecimal bd = BigDecimal.valueOf(0.11D);13. Return empty arrays/collections instead of null
// Bad
return null;
// Good
return new Result[0];
return Collections.emptyList();
return Collections.emptyMap();14. Call equals on a constant or known non‑null object
// Bad
return fileName.equals("Charming");
// Good
return "Charming".equals(fileName);
// or Objects.equals(fileName, "Charming");15. Enum fields should be private final and 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 metacharacters in String.split()
// Bad
"a.ab.abc".split("."); // results in empty array
// Good
"a.ab.abc".split("\\."); // ["a","ab","abc"]Following these guidelines helps Java developers write code that is more efficient, safer, and easier to maintain.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
