mardi 28 mars 2017

If versus '?'. Which one is cleaner

Person person = Person.getRandomPerson();
if (person.getSex().equals(PersonSex.MAN))) {
    person.setName("John");
    person.setSurname("Wick");
    person.setWeight(80.0);
    ...
} else {
    person.setName("Alice");
    person.setSurname("Carrot");
    person.setWeight(50.0);
    ...
}

vs

Person person = Person.getRandomPerson();
person.setName(person.getSex().equals(PersonSex.MAN) ? "John" : "Alice");
person.setSurname(person.getSex().equals(PersonSex.MAN) ? "Wick" : "Carrot");
person.setWeight(person.getSex().equals(PersonSex.MAN) ? 80.0 : 50.0);
...

Which version is better for you? Personally I would choose IF version, because in this case we have only one conditional expression. However, we have much more code lines there. I would like to ask you, which version you would like to choose and why?

Aucun commentaire:

Enregistrer un commentaire