| name | java-quality |
| description | Java code quality standards and best practices for CPS project. |
Java Code Quality Skill
Overview
This skill ensures Java code follows CPS (Configuration Persistence Service) quality standards and best practices.
Core Principle
Simple is Good, Complex is Bad - Always prefer simple, readable code over complex patterns. When choosing between solutions, select the one that is easiest to understand and maintain.
Code Quality Checks
1. Naming Conventions
2. String Constants
3. Null Safety
- Put constants first in equals() to prevent NPEs:
4. Control Flow
-
Avoid using ! (negation) or != ONLY when an else block is implemented - invert the condition:
if (x != null) {
do something;
} else {
report error;
}
if (x == null) {
report error;
} else {
do something;
}
Note: This rule does NOT apply when there's no else block. Simple guard clauses are acceptable:
if (x != null) {
throw new Exception("error");
}
-
No need for else after return:
if (ROOT_NODE_PATH.equals(xpath) {
return something;
} else {
return somethingElse;
}
if (x == true) {
return something;
}
return something-else;
5. Collections
-
No need to check isEmpty before iterating:
if (!myCollection.isEmpty()) {
collection.forEach(some action);
}
collection.forEach(some action);
-
Initialize collections/arrays with known size:
void processNames(Collection<String> orginalNames) {
String[] processedNames = new String[0];
void processNames(Collection<String> orginalNames) {
String[] processedNames = new String[orginalNames.size()];
6. Performance
- Use string concatenation instead of String.format (5x slower) where possible:
7. Spring Annotations
- Use
@Service when a class includes operations
- Use
@Component when it is a data object only
- Currently no functional difference but may change in future Spring versions
8. Prefer Simplicity Over Optional Patterns
Security Checks
Never Log User Data
- Do not log any user data at any log level
- User data may contain sensitive information
- When logging objects, ensure toString() implementation doesn't include user data
- Only log well-defined fields that do not contain user data
Commit Guidelines
Follow the ONAP commit message guidelines
Application
When reviewing or writing Java code:
- Check for these patterns in new/modified code
- Suggest simpler alternatives when complex code is found
- Ensure security checks (especially logging) are followed
- Verify naming conventions are consistent
- Look for performance anti-patterns (String.format, uninitialized collections)