Java Best Practices
ASecurityUsually, yes — returning `Optional<T>` is better than returning `null` when “no result” is a normal, expected outcome. Why: - `Optional` makes the absence explicit in the method signature. - It reduces accidental `NullPointerException`s. - It forces callers to handle the empty case intentionally. Example: ```java public Optional<User> findUserById(String id) { return repository.lookup(id); } ``` Then the caller can do: ```java findUserById(id).ifPresent(this::sendEmail); ``` or ```java User u...
- 584 stars
- 0 votes
- 1 copy
- 4 views
- Added September 5, 2026
Security analysis
100/100Pro scans all 18 files and shows the line behind each finding
npx -y skills add HoangNguyen0403/agent-skills-standard --skill java-best-practices --agent claude-codeAre you the author of Java Best Practices?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/hoangnguyen0403-java-best-practices-b129971e)Usually, yes — returning `Optional<T>` is better than returning `null` when “no result” is a normal, expected outcome.
Why:
- `Optional` makes the absence explicit in the method signature.
- It reduces accidental `NullPointerException`s.
- It forces callers to handle the empty case intentionally.
Example:
```java
public Optional<User> findUserById(String id) {
return repository.lookup(id);
}
```
Then the caller can do:
```java
findUserById(id).ifPresent(this::sendEmail);
```
or
```java
User user = findUserById(id).orElseThrow(() -> new UserNotFoundException(id));
```
A few caveats:
- Don’t use `Optional` for fields or most method parameters.
- For collections, return an empty collection instead of `Optional<List<T>>` in most cases.
- If the method is internal and performance-critical, `null` may still be acceptable, but it should be a deliberate choice.
So the general Java best practice is: don’t return `null` for “not found”; prefer `Optional<T>` or an empty collection, depending on the return type.
Files in this skill
- eval-1.baseline.md
- eval-1.with-skill.md
- eval-2.baseline.md
- eval-2.with-skill.md
- eval-3.baseline.md
- eval-3.with-skill.md
- trigger-1.md
- trigger-10.md
- trigger-11.md
- trigger-2.md
- trigger-3.md
- trigger-4.md
- trigger-5.md
- trigger-6.md
- trigger-7.md
- trigger-8.md
- trigger-9.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.