Skip to content

yasmramos/nullsafe

Repository files navigation

NullSafe - Safe Null Value Handling in Java

Build Status License GitHub stars Tests

A more powerful alternative to Optional<T> for handling null values safely, cleanly and functionally in Java.


πŸ“Œ What is NullSafe?

NullSafe<T> is a class designed to encapsulate values that can be null, offering chainable methods, validations, error recovery, functional adapters and support for collections, maps and strings.

It prevents dreaded NullPointerException and provides a rich and flexible API for developing clean, safe and expressive code.


✨ Key Features

Feature Description
βœ… Functional chaining Methods like map, flatMap, filter, etc.
βœ… Error recovery .recover(...), .recoverWith(...)
βœ… Integrated validations .validate(pred, msg), .validate(pred, () -> ex)
βœ… Type conversions .toOptional(), .toResult("error"), .stream()
βœ… Custom adapters .adapt(adapter)
βœ… Integrated logging .logIfPresent(...), .logIfAbsent(...))
βœ… Multiple value combination .combine(a, b, (x, y) -> x + y)
βœ… Collections and maps usage Static methods like filterNonNull(...), mapNonNullValues(...)
βœ… Specialized primitive types NullSafeInt, NullSafeLong, NullSafeDouble, NullSafeFloat, NullSafeBoolean, NullSafeByte, NullSafeShort

β˜• Java 11 Compatibility

This project has been fully configured and optimized for Java 11, ensuring broad compatibility and future-proof development:

  • βœ… Configuration Unified: All Maven compiler settings consistently use Java 11
  • βœ… Compilation: Built with --release=11 flag for backward compatibility
  • βœ… Test Coverage: 73 tests passing (37 primitive tests + 36 core tests)
  • βœ… API Compatibility: All existing features fully maintained
  • βœ… Performance: Optimized for Java 11 runtime environment

Recent Improvements: Fixed pom.xml inconsistencies by unifying maven.compiler.source, maven.compiler.target, and plugin configurations to Java 11, ensuring consistent build behavior.

The library works seamlessly with Java 11+ while maintaining full API compatibility with newer Java versions.


πŸ’‘ Quick Example

NullSafe.of("   hello world   ")
        .map(String::trim)
        .filter(s -> s.length() > 5)
        .map(String::toUpperCase)
        .recover(ex -> "DEFAULT VALUE")
        .validate(s -> s.contains("HELLO"), "Does not contain 'HELLO'")
        .ifPresent(System.out::println);

🧩 Integration with Result<T, E>

You can easily convert between NullSafe and Result<T, E>:

 
Result<String, String> result = NullSafe.of("value").toResult("Value not found");

result.ifSuccess(System.out::println)
       .ifFailure(err -> System.err.println("Error: " + err));

πŸ”’ Primitive NullSafe Types

In addition to NullSafe<T>, the library includes specialized classes for safely handling primitive types:

  • NullSafeInt - Safe handling of Integer values
  • NullSafeLong - Safe handling of Long values
  • NullSafeDouble - Safe handling of Double values
  • NullSafeFloat - Safe handling of Float values
  • NullSafeBoolean - Safe handling of Boolean values
  • NullSafeByte - Safe handling of Byte values
  • NullSafeShort - Safe handling of Short values

Primitive Type Usage Examples

// NullSafeInt
int result = NullSafeInt.of(42)
    .ifPresent(value -> System.out.println("Value: " + value))
    .orElse(0);

// NullSafeDouble with validations
double price = NullSafeDouble.of(product.getPrice())
    .validate(p -> p > 0, "Price must be positive")
    .orElse(0.0);

// NullSafeBoolean for conditional logic
boolean isValid = NullSafeBoolean.of(userInput)
    .orElse(false);

// Handling extreme values
NullSafeLong.of(Long.MAX_VALUE)
    .orElseThrow(() -> new RuntimeException("Value too large"));

NullSafeDouble.of(Double.NaN)
    .ifPresent(value -> System.out.println("Is NaN: " + value))
    .orElseGet(() -> 0.0);

Primitive Type Advantages

  • Performance: Avoid automatic boxing/unboxing
  • Memory: Lower memory usage than boxed types
  • Safety: Same NullPointerException protection
  • Consistency: Same API as NullSafe<T> but optimized for primitives

πŸ“¦ Installation

Prerequisites

  • Java 11 or higher
  • Maven 3.6+ or Gradle 6+

Build from Source

# Clone the repository
git clone https://github.com/yasmramos/nullsafe.git
cd nullsafe

# Build with Java 11 compatibility
mvn clean compile test

# Or with Gradle
./gradlew build

Include in Your Project

Maven

<dependency>
    <groupId>com.github.yasmramos</groupId>
    <artifactId>nullsafe</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle

implementation 'com.github.yasmramos:nullsafe:1.0.0'

πŸ§ͺ Unit Tests

All functions are covered by unit tests using JUnit 5. You can run them like this:

   mvn test

Or if you use Gradle:

   gradle test

πŸ“Š Code Coverage

Supports coverage analysis with JaCoCo:

   mvn clean test jacoco:report

The report is generated in:

   target/site/jacoco/index.html

🧱 Contributing

We are open to contributions! If you want to improve the library, fix errors, add new functions or translate documentation, go ahead!

  1. Open an issue
  2. Fork the repository
  3. Create a new branch (git checkout -b feature/foo)
  4. Commit your changes (git commit -m 'Add some foo')
  5. Push the changes (git push origin feature/foo)
  6. Create a pull request

πŸ“„ License

This project is under the MIT License.

Β© 2025 yasmramos / Java Community.


πŸ“¬ Contact

If you have questions, suggestions or want to collaborate:

πŸ“§ Email: yasmramos95@gmail.com 
πŸ™ GitHub: @yasmramos 

About

NullSafe - Safe Null Value Handling in Java

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Languages