5 things every Java developer should know about null and why Optional is not always the answer. You might reach for Optional the moment you see a possible null. That instinct is not always right. Here are the rules that actually matter: - Optional.of(value) throws NPE if value is null. Always use ofNullable() when you are not certain. - The isPresent() + get() pattern is just a null check in a suit. Use orElse(), orElseGet(), or orElseThrow(). - Never put Optional in a class field. JPA and Jackson do not handle it well. Use nullable fields in entities and DTOs. - Never return Optional<List<T>>. Return an empty list. A collection already signals absence. - orElse(x) evaluates x even when a value is present. orElseGet(supplier) is lazy. Use it for DB calls or object creation. Optional is powerful when used at the right boundary the service layer return type, not everywhere a null could exist. #Java #SpringBoot #CleanCode #JavaDeveloper #SoftwareEngineering
Thanks for sharing
Well explained. Optional is useful, but only when it is used in the right place. This is a very practical reminder that cleaner code is not about using more abstractions, it is about using the right ones.