Skip to content

Instantly share code, notes, and snippets.

View SilverioMG's full-sized avatar

Silverio Martinez Garcia SilverioMG

View GitHub Profile
@Test
public void getStateField_with_StateNull() {
Person personWithStateNull = personRepository.getPersonWithStateNull();
//Se lanza una Exception ya que 'personWithStateNull.getAdress().getState()' vale 'null'.
assertThrows(NullPointerException.class,
() -> {
String stateNameFails = personWithStateNull.getAddress().getState().getName();
});
@Test
public void getAddressField_with_AddressNotNull() {
Person personWithAddress = personRepository.getPersonTest();
String street = personWithAddress.getAddress().getStreet();
assertTrue(street != null);
//En este caso se utiliza 'MethodReference' en el método 'map()' en vez de expresiones lambda pero el resultado es el mismo.
String streetOptional = Optional.ofNullable(personWithAddress)
.map(Person::getAddress) //Es equivalente a '.map(person -> person.getAddress())'
.map(Address::getStreet)
@Test
public void getAddressField_with_AddressNull() {
Person personWithAddressNull = personRepository.getPersonWithAddressNull();
//Se lanza una Exception ya que 'personWithAddressNull.address' vale 'null'.
assertThrows(NullPointerException.class,
() -> {
String streetFails = personWithAddressNull.getAddress().getStreet();
});
package net.atopecode.optionals.repository;
import net.atopecode.optionals.model.Address;
import net.atopecode.optionals.model.Person;
import net.atopecode.optionals.model.State;
public class PersonRepository {
private State getState() {
return new State("State1", 12345);
public String getStateName(Person person){
string stateName = person?.address?.state?.getName();
return stateName;
}
public String getStateName(Person person){
String stateName = null;
if(person != null){
Address address = person.getAddress();
if(address != null){
State state = address.getState();
if(state != null){
stateName = state.getName();
}
@Test
public void safeGetFromOptional_with_orElseGet_ExecuteFunction_onlyWhen_emptyOptional() {
Person person = personRepository.getPersonTest();
//Declaro la expresión Lambda en una variable para poder reutilizarla en ambos casos.
String modifiedName = "Modified Name";
Supplier<String> supplierLambda = () -> {
person.setName(modifiedName);
System.out.println("LambdaModifiedPersonName() executed!"); //Nunca se va a ejecutar esta función lambda.
return person.getName();
@Test
public void safeGetFromOptional_with_orElse_alwaysExecuteFunction() {
Person person = personRepository.getPersonTest();
String notEmptyValue = "NotEmptyOptional";
Optional<String> optional = Optional.ofNullable(notEmptyValue);
//El objeto 'optional' no está vacío, pero al utilizar 'orElse()' para recuperar su valor, se ejecutará de todas forma la función enviada como parámetro 'getPersonName()'.
//Para evitar que esto suceda es mejor utilizar siempre 'orElseGet()', o si se utiliza 'orElse()' indicar siempre un valor directamente en vez de una función.
String modifiedName = "Modified Name";
String value = optional.orElse(getModifiedPersonName(person, modifiedName));
@Test
public void checkingOptionalValue() {
Optional<String> emptyOptional = Optional.ofNullable(null);
boolean isEmpty = emptyOptional.isEmpty();
assertTrue(isEmpty);
Optional<String> notEmptyOptional = Optional.ofNullable("Valor1");
isEmpty = notEmptyOptional.isEmpty();
assertFalse(isEmpty);
}
@Test
public void whenCreateFrom_NullValue_then_NullPointerException() {
Exception ex = assertThrows(NullPointerException.class,
() -> {
Person person = null;
Optional<Person> personOpt = Optional.of(person);
});
}
@Test