14 Essential Java Code Optimization Tips Every Backend Developer Should Know
Discover 14 practical Java code optimization techniques—from using configuration properties and @RequiredArgsConstructor to modularizing methods, avoiding null returns, leveraging IDE suggestions, and applying design patterns—each illustrated with clear examples and snippets to help backend developers write cleaner, more maintainable code.
Good coding habits are essential to avoid the gradual buildup of a "code mountain"; this article shares 14 concise tips to make code optimization effortless.
1. Define Configuration File Information
Store variables in a YML configuration file instead of hard‑coding magic numbers, allowing easy updates without searching the whole project.
Example using @ConfigurationProperties instead of @Value:
@Data
// Specify prefix
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
private String name;
private String website;
private String qq;
private String phoneNumber;
}Inject the bean where needed:
@RestController
@RequiredArgsConstructor
public class PropertyController {
final DeveloperProperty developerProperty;
@GetMapping("/property")
public Object index() {
return developerProperty.getName();
}
}2. Use @RequiredArgsConstructor Instead of @Autowired
Spring recommends constructor injection for beans. Lombok’s @RequiredArgsConstructor generates the required constructor automatically.
3. Code Modularization
Keep methods under 50 lines (as suggested by Alibaba’s Java development manual) and split logic so each method handles a single responsibility.
4. Throw Exceptions Rather Than Returning Error Codes
Avoid returning varied error messages; use exceptions to keep business code clean.
5. Reduce Unnecessary Database Queries
Only query the database when needed; for deletions, verify the record first instead of a blind query.
6. Do Not Return Null
Returning null leads to NullPointerExceptions; prefer empty collections or Optional.
7. Minimize if‑else Chains
Replace long if‑else chains with the Strategy pattern where appropriate.
8. Keep Controller Business Logic Minimal
Move business logic to the service layer for better maintainability and readability.
9. Leverage IDEA Suggestions
IDEA can recommend lambda expressions, string concatenation improvements, and other refactorings.
10. Read Source Code
Study high‑quality open‑source projects (stars > 1000) to learn design ideas and advanced APIs, which also helps in interviews.
11. Apply Design Patterns
Familiarize yourself with the 23 classic design patterns to write more structured and elegant code.
12. Embrace New Knowledge
Beyond daily CRUD tasks, explore unfamiliar technologies and build demo projects after work.
13. Basic Issues
Map iteration:
HashMap<String, String> map = new HashMap<>();
map.put("name", "du");
for (String key : map.keySet()) {
String value = map.get(key);
}
// Recommended
for (Map.Entry<String, String> entry : map.entrySet()) {
// use entry.getKey() and entry.getValue()
}Optional null‑check:
public List<CatalogueTreeNode> getChild(String pid) {
if (V.isEmpty(pid)) {
pid = BasicDic.TEMPORARY_DIRECTORY_ROOT;
}
CatalogueTreeNode node = treeNodeMap.get(pid);
return Optional.ofNullable(node)
.map(CatalogueTreeNode::getChild)
.orElse(Collections.emptyList());
}Recursion tip: avoid creating new objects inside deep recursion; pass reusable objects as parameters.
Comments: write clear comments for classes, interfaces, methods, and complex logic.
14. Check Element Existence Efficiently
Use HashSet instead of List for existence checks (O(1) vs O(n)).
ArrayList<String> list = new ArrayList<>();
// Check if "a" is in list (O(n))
for (int i = 0; i < list.size(); i++) {
if ("a".equals(elementData[i])) return i;
}
HashSet<String> set = new HashSet<>();
// Check if "a" is in set (O(1))
int index = hash(a);
return getNode(index) != null;These practices collectively improve code readability, maintainability, and performance.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
