Skip to content

Latest commit

 

History

History
78 lines (53 loc) · 2.93 KB

Java - Optional.md

File metadata and controls

78 lines (53 loc) · 2.93 KB

Java - Optional

Remarkable Tips

Optional.of() and Optional.ofNullable()

  • As a key here, keep in mind that Optional.of(null) will throw NullPointerException, while Optional.ofNullable(null)* will result in an Optional.empty.
    • Optional.of(nullObject) throws NullPointerException
    • Optional.ofNullable(nullObject) return result in an Optional.empty

Do not assign 'null' to an Optional Variable

Optional<Cart> emptyCart = Optional.empty(); // Avoid Exempla: Optional<Cart> emptyCart = null;

Ensure that Optional HAS value before calling Optional.get()

Optional<Cart> cart = ...
[Avoid] Cart myCart = cart.get(); //if "cart"is empty then this code will throw a java.util.NoSuchElementException

Unwrap Optionals

There Is No Need to Unwrap Optionals for Asserting Equality Having twoOptionalsin anassertEquals() doesn't require unwrapped values.

Optional<String> actualItem = Optional.of("Shoes");
Optional<String> expectedItem = Optional.of("Shoes");        
assertEquals(expectedItem, actualItem);

Optional.orElse() and Optional.map()

Using the Optional.orElse() method represents an elegant alternative to the isPresent() & get() pair for setting/returning a value.

  • What Does Optional.orElse do? Returns the value, otherwise, returns the value defined in the parameter.

  • What Does Optional.map(someFunction) do? If the value is present, then apply the function passed as argument in the value, otherwise, returns a Optional.empty

     Optional<Cart> cart = ...
     cart.map(Cart::getName)
       .orElse(UNKNOWN);
     //.orElseGet(Constants::getName) //returns the value generated by getName  
     //.orElseThrow(IllegalArgumentException::new)
     
    
  • Consume an Optional if it Is Present [ifPresent()]

    Optional status ... ; status.ifPresent(System.out::println);

  • Do Not Declare Any Class Field of Type Optional [AVOID]

     public class Customer {
     	[access_modifier] [static] [final] Optional<String> zip;
     	[access_modifier] [static] [final] Optional<String> zip = Optional.empty();
     	...
     }
    
    
  • Do Not Use Optional in Constructors Arguments

  • Do Not Use Optional in Setters Arguments

  • Do Not Use Optional in Methods Arguments

    [AVOID]

    public void renderCustomer(Optional<Renderer> renderer, Optional<String> name) {} [PREFER] public void renderCustomer(Cart cart, Renderer renderer, String name) { String customerName = Objects.requireNonNullElseGet(name, () -> "anonymous"); }

  • Avoid Optional and Choose Non-Generic OptionalInt, OptionalLong, or OptionalDouble

Java 9: Executing fallbacks with Optional::or

TODO - ref

References

[Using Optional Correctly](https://dzone.com/articles/using-optional-correctly-is-not-optional)

[Optional no Java 8 e no Java 9](https://medium.com/@racc.costa/optional-no-java-8-e-no-java-9-7c52c4b797f1)