💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝐌𝐢𝐬𝐬𝐢𝐧𝐠 𝐕𝐚𝐥𝐮𝐞𝐬 🔥 💎 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝘃𝘀 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹 💡 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 are designed for truly exceptional, unexpected errors that occur outside normal program flow. When thrown, they propagate up the call stack until caught by an appropriate handler. ✔ Exceptions should never be used for routine control flow due to significant performance costs from stack unwinding and object creation. 🔥 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹 provides an explicit alternative for representing absence of a value. It wraps a value that may or may not be present, making null-safe code more expressive and functional. ✔ Optional is ideal for modeling "value might be missing" scenarios and works seamlessly with streams and lambda expressions. ✅ 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗘𝗮𝗰𝗵 ◾ 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀: Rare failures like I/O errors, database connection issues, or invalid business transactions. ◾ 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹: Expected absence like cache misses, lookup results not found, or optional configuration values. ◾ 𝗛𝘆𝗯𝗿𝗶𝗱 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Use both strategically for optimal code clarity and performance. 🤔 Which approach do you prefer for handling missing values? #java #springboot #programming #softwareengineering #softwaredevelopment
for the second approach just let repo return an Optional directly, or return Optional.ofNullable(user)
Or you could use structs which are value types in .net or records. Optional looks nice as a generic, I just hope that developers don’t get obsessed with syntax sugar and keep demanding new syntax instead of creating apps that a C++ developer can use. As a C# and C++ developer, I understand that new syntax comes but if the byte code doesn’t change then did you achieve anything great?
public class Opinional<E>{ public record E? Data { get; } private Optional(E m) { Data = m; } public static E? of<E>() => new Optional(default(E)); public static E? of(E? m) = > new Optional(m); }
Simple, clear, and very practical advice for Java/Spring developers. Thanks for the reminder!
you can also use this approach, User user = userRepository.findById(id); return Optional.ofNullable(user); very simple to understand.
Thanks for Sharing.
use Optional for expected missing value and exceptions only for truly unexpected situations
Test du null inutile et encombrant
What's the difference between Optional and Result pattern ?
A method starting with the name findBy should return Optional because the entity can be find or not. A NotFoundException should be used when the method start with getById. The intention is linked with the sementic naming.