On Github bjartek / pres_lightning_nullref
package org.bjartek.nullref.model; public class Person { private final Address address; public Person(Address address) { this.address = address; } public Address getAddress() { return address; } }
package org.bjartek.nullref.model; public class Address { private final String streetname; public Address(String streetname) { this.streetname = streetname; } public String getStreetName() { return streetname; } }
package org.bjartek.nullref; import com.google.common.base.Objects; import org.bjartek.nullref.model.Person; public class PlainJava implements StreetnameProvider { @Override public String streetName(Person person) { String name = person.getAddress().getStreetName(); return Objects.firstNonNull(name, StreetnameProvider.DEFAULT); } }
package org.bjartek.nullref; import com.google.common.base.Objects; import org.bjartek.nullref.model.Person; public class PlainJavaNullsafe implements StreetnameProvider { @Override public String streetName(Person person) { if (person == null || person.getAddress() == null) { return StreetnameProvider.DEFAULT; } String name = person.getAddress().getStreetName(); return Objects.firstNonNull(name, StreetnameProvider.DEFAULT); } }
package org.bjartek.nullref
import com.google.common.base.Objects import org.bjartek.nullref.model.Person
class Groovy implements StreetnameProvider {
@Override String streetName(Person person) { String name = person?.address?.streetName return Objects.firstNonNull(name, StreetnameProvider.DEFAULT) }
}
package org.bjartek.nullref; import com.google.common.base.Optional; import org.bjartek.nullref.gmodel.Person; public class GuavaManual implements StreetnameProviderOptional { @Override public String streetName(Optional<Person> p) { if (!p.isPresent()) { return StreetnameProviderOptional.DEFAULT; } Person person = p.get(); if (!person.getAddress().isPresent()) { return StreetnameProviderOptional.DEFAULT; } Optional<String> name = person.getAddress().get().getStreetName(); return name.or(StreetnameProviderOptional.DEFAULT); } }
package org.bjartek.nullref; import com.google.common.base.Optional; import org.bjartek.nullref.gmodel.*; public class GuavaIterator implements StreetnameProviderOptional { @Override public String streetName(Optional<Person> p) { for (Person person : p.asSet()) { for (Address adr : person.getAddress().asSet()) { return adr.getStreetName().or(StreetnameProvider.DEFAULT); } } return StreetnameProviderOptional.DEFAULT; } }
case class Address(streetName: Option[String]) case class Person(address: Option[Address]) def streetName(person:Option[Person]): String = { val name = person.flatMap{pers => pers.address.flatMap{adr => adr.streetName } } name.getOrElse("Not Found") }
case class Address(streetName: Option[String]) case class Person(address: Option[Address]) def streetName(person:Option[Person]): String = { val name = for { p <- person a <- p.address sn <- a.streetName } yield sn name.getOrElse("Not Found") }