Top 11 clean code practices
| No | Practice | Explanation | Bad Practice | Good Practice |
|---|---|---|---|---|
| 1 | Nulls and Optionals | Avoid returning null from methods to prevent NullPointerException. Use Optional to handle null values explicitly. |
Returning null from a method. |
Use Optional to handle null explicitly. |
| 2 | Optimal String Conversion | String.valueOf() is designed to convert data types into strings efficiently and safely. |
Manually converting numeric data types to strings. | Use String.valueOf() for conversions. |
| 3 | Copying Arrays | Manual array copying is inefficient. Arrays.copyOf() is optimized and safer. |
Copy arrays manually. | Use Arrays.copyOf() to copy arrays. |
| 4 | Check Empty Collections | Using isEmpty() is clearer and more efficient than checking size or length. |
Using length() or size(). |
Use isEmpty() to check emptiness. |
| 5 | Avoid Concurrent Modification | Removing elements during iteration causes ConcurrentModificationException. |
Removing items directly while iterating. | Use iterator remove() or removeIf(). |
| 6 | Precompile Regex | Pre-compiling regular expressions improves performance and avoids repeated compilation. | Compiling regex at runtime. | Pre-compile and reuse regular expressions. |
| 7 | Direct Data Retrieval | Checking existence before retrieval causes redundant operations. | Checking data existence first. | Retrieve directly and check for null. |
| 8 | Collection to Array Conversion | toArray() handles resizing efficiently without manual size calculation. |
Manually calculating size and creating arrays. | Use the toArray() method. |
| 9 | Default Methods | Default methods allow interface evolution without breaking implementations. | Avoiding default methods. | Use default methods in interfaces. |
| 10 | Date/Time API | The old Date class is error-prone. The Java 8+ Date/Time API is safer and clearer. |
Using the old Date class. |
Use Java 8+ Date/Time API classes. |
| 11 | Using Generics | Generics ensure compile-time type safety and prevent runtime errors. | Not using generics. | Use generics for type safety. |
Comments
Post a Comment