14 Practical Java Code‑Optimization Tips for Cleaner, More Maintainable Code
This article presents fourteen actionable Java coding‑style and architecture tips—ranging from using configuration properties and Lombok constructors to modularizing methods, throwing exceptions, reducing DB calls, avoiding null returns, and leveraging IDE suggestions—to help developers write cleaner, more robust backend code.
When it comes to code optimization many people start with theories or architectures, but the most important factor is good coding habits; a "code dump" is built over time, so cultivating proper habits makes code elegant, maintainable, and systems robust. Below are fourteen concise tips that turn optimization into a routine.
1. Define configuration file information
Store frequently used variables in a YAML configuration file instead of scattering magic numbers throughout the code. Changing a value then only requires editing the config file.
Example
Use @ConfigurationProperties instead of @Value . Usage
@Data
// specify prefix
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
private String name;
private String website;
private String qq;
private String phoneNumber;
}Inject this bean where needed:
@RestController
@RequiredArgsConstructor
public class PropertyController {
private 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 constructor automatically.
3. Code modularization
The Alibaba Java Development Manual suggests keeping methods under 50 lines. Split interfaces and methods so each handles a single piece of logic, making reuse easier.
4. Throw exceptions instead of returning error codes
Returning different messages for different outcomes makes code messy. Use exceptions to signal errors.
Bad example
Good example
5. Reduce unnecessary DB queries
Avoid extra database look‑ups. Example: when deleting a service, do not first query by ID then decide; combine checks into a single query.
Bad example
Good example
6. Do not return null
Returning null forces callers to perform null checks and can cause NPEs.
Bad example
Good example
7. Reduce if‑else chains
Too many if‑else if blocks become hard to maintain; consider the Strategy pattern as a replacement.
8. Keep controller thin
Business logic should reside in the service layer, leaving controllers simple and maintainable.
Bad example
Good example
9. Leverage IntelliJ IDEA
IDEA can analyze code and suggest improvements, such as replacing anonymous classes with lambda expressions.
Click “Replace” to apply the suggested lambda.
10. Read source code
Regularly read high‑quality open‑source projects (stars > 1000) to learn design ideas, advanced APIs, and to gain interview advantage.
11. Apply design patterns
There are 23 classic design patterns; using them makes code more standardized, elegant, and impressive.
12. Embrace new knowledge
Junior developers should explore unfamiliar technologies, build demo projects after hours, and avoid staying in a CRUD‑only comfort zone.
13. Fundamental issues
Map iteration
HashMap<String, String> map = new HashMap<>();
map.put("name", "du");
for (String key : map.keySet()) {
String value = map.get(key);
}
map.forEach((k, v) -> { /* ... */ });
// Recommended
for (Map.Entry<String, String> entry : map.entrySet()) {
// ...
}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 When processing large data sets recursively, avoid creating new objects inside the recursive method; pass reusable objects as parameters instead.
Comments Classes, interfaces, methods, annotations, and complex logic should all have clear comments for future readers and for yourself.
14. Check element existence efficiently
Use HashSet (backed by HashMap) instead of List for existence checks.
ArrayList<String> list = new ArrayList<>();
// check if "a" is in list
for (int i = 0; i < list.size(); i++) {
if ("a".equals(elementData[i])) {
return i;
}
}Complexity: O(n).
HashSet<String> set = new HashSet<>();
// check if "a" is in set
int index = hash(a);
return getNode(index) != null;Complexity: O(1).
Source: blog.csdn.net/weixin_44912855/article/details/120866194
Java Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
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.
