🚀 Spring Boot 4.0: Writing Safer Code with Null Safety One of the biggest causes of production bugs in Java applications is the infamous NullPointerException. Modern Java development is moving toward explicit null safety, making our code more predictable and maintainable. Instead of relying only on runtime checks, developers can design APIs that clearly define what can be null and what cannot. Why this matters for backend systems: 🔹 Fewer Runtime Errors By clearly defining nullable and non-nullable values, many issues can be caught early during development. 🔹 Cleaner API Design Well-defined method contracts make the code easier for other developers to understand. 🔹 Better Code Readability Annotations and clear patterns make the intent of the code obvious. 🔹 More Reliable Microservices In distributed systems, predictable APIs reduce unexpected failures between services. Modern Java practices combined with Spring Boot, Optional, and clear API design help developers build robust and production-ready backend systems. Small improvements in code safety can prevent big problems in production. 🚀 #Java #SpringBoot #Microservices #BackendDevelopment #CleanCode #SoftwareEngineering
getOptionalBio() the name is lie! It can return a string or null. If it is called getOptional... it should return a damn Optional<>.
My take about this: re-implement a 'Maybe' class (don't use Optional, it's still too oriented towards OO/Java and Exceptions) and use this everywhere. Also, avoid the names Option/Optional, they often only work for 1 side (consumer/provider). A function returning an "Option" or "Optional" suggests that you, as the consumer, have a choice, an option. Wrong. What you'll get is maybe something, maybe nothing. Hey, notice, maybe. That works for both: I implement a function that will maybe return something or maybe nothing, and you reuse my function that will maybe return something, or maybe return nothing.
Writing code to make sure that input parameters are not null or nullable does not make Java code “safer”, exactly the opposite, it makes code less readable and less safe. https://javadevguy.wordpress.com/2018/11/24/why-i-never-null-check-parameters/ We could instead pretend that nulls don’t exist and treat any occurrence of null as a programming error, at least in public method parameters or return values. Specifically: - Methods and constructors should not check for nulls - Methods should not return nulls Instead: - Methods/constructors should assume that all parameters are non-null - Methods that allowed null should be redesigned or split into multiple methods - Constructors with multiple parameters that aren’t required should consider using the Builder Pattern. - Methods that returned null could return Optional, or better a special implementation of whatever logic was expected on null previously. --> Use the null object-pattern https://anubhav-gupta62.medium.com/null-object-design-pattern-f16e426ec15f