Skip to content

Instantly share code, notes, and snippets.

@up1
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save up1/8ab1f712fd5868f10e9d to your computer and use it in GitHub Desktop.

Select an option

Save up1/8ab1f712fd5868f10e9d to your computer and use it in GitHub Desktop.
Avoid IFs
PersonDAO personDAO = new PersonDAO();
Person person = personDAO.getPersonByID(1);
if(person != null) {
person.setName("My name");
}
personDAO.getPersonByID(personID, new Action<Person>() {
public void act(Person person) {
person.setName("My name");
}
});
public interface Action<T> {
void act(T object);
}
public void call() throws PersonNotFoundException {
PersonDAO personDAO = new PersonDAO();
Person person = personDAO.getPersonByID(1);
person.setName("My name");
}
public String findCarInsurance(Person person) {
if (person != null) {
Car car = person.getCar();
if (car != null) {
Insurance insurance = car.getInsurance();
if (insurance != null) {
return insurance.getName();
}
}
}
return "Unkonwn";
}
public String findCarInsurance(Person person) {
if (person == null) {
return "Unkonwn";
}
Car car = person.getCar();
if (car == null) {
return "Unkonwn";
}
Insurance insurance = car.getInsurance();
if (insurance == null) {
return "Unkonwn";
}
return insurance.getName();
}
public String findCarInsurance(Optional<Person> person) {
return person.flatMap(person1 -> person1.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unkonwn");
}
List<Person> persons = personDAO.getPersonByID(1);
persons.forEach(person -> {
person.setName("My name");
});
person_dao.person(id) do |person|
person.name = name
end
public class PersonDAO {
public Person getPersonByID(int personID) throws PersonNotFoundException {
Person person = null;
...
...
if(person == null) {
throw new PersonNotFoundException();
}
return person ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment