Summarizing clean code practices for Java
Naming Conventions: Use meaningful names conveying the intent of the object.
Constants: Use Constants to manage static values (Constants help improve memory as they are cached by the JVM. For values that are reused across multiple places, create a constant file that holds static values.) use ENUMs to group constants.
Clean Code: Remove Console print statements, Remove Unnecessary comments
Deprecate Methods: Use @deprecated on method/variable names that aren’t meant for future use
Strings: If you need to perform a lot of operations on a String, use StringBuilder or StringBuffer.
Switch statement: Rather than using multiple if-else conditions, use the cleaner and more readable switch-case.
Exception Handling: https://kamalmeet.com/java/exception-handling-basic-principles/
Code Structure: Follow the Separation of Concerns strategy – controller, service, model, utility
Memory Leaks: Unclosed resources, e.g. unclosed URL connections can cause memory leaks. https://rollbar.com/blog/how-to-detect-memory-leaks-in-java-causes-types-tools/
Concurrent code: Avoid unnecessary synchronization, and at the same time identify areas to be synchronized where multiple threads can cause problems.
Lambdas and Streams: If you’re using Java 8+, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java. The following snippet filters odd numbers in the traditional imperative way:
List<Integer> oddNumbers = new ArrayList<>();
for (Integer number : Arrays.asList(1, 2, 3, 4, 5, 6)) {
if (number % 2 != 0) {
oddNumbers.add(number);
}
}
This is the functional way of filtering odd numbers:
List<Integer> oddNumbers = Stream.of(1, 2, 3, 4, 5, 6)
.filter(number -> number % 2 != 0)
.collect(Collectors.toList());
NullPointerException: When writing new methods, try to avoid returning nulls if possible. It could lead to null pointer exceptions.
Use final: When you want to make sure a method should not be overridden
Avoid static: Static can cause issues if not used properly as it shares variables at class level
Data Structures: Java collections provide ArrayList
, LinkedList
, Vector
, Stack
, HashSet
, HashMap
, Hashtable
. It’s important to understand the pros and cons of each to use them in the correct context. A few hints to help you make the right choice
Least visibility: Use of Public, private, and protected
Stay SOLID: https://kamalmeet.com/design/solid-principles-for-object-oriented-design/
DRY: Don’t Repeat Yourself, common code should be part of utilities and libraries
YAGNI: You Are not Going to Need It, code only what is needed
Static Code Review: SonarQube in Eclipse
Size of Class and Functions: Class and Function should be small – 400 / 40
Input checks: Inputs into methods should be checked for valid data size and range
Database Access: Use best practices like Connection Pool, JPA, Prepared statements, etc.