Rahul Pandit.

5 Mar 2022

Method refactoring to avoid to many npe checks


I have created the following method which returns a Triple of strings. However, I don't like the way I've written it because I think I've put in too many Npe checks making it unreadable.

private Triplet<String, String, String> getInfoFromTable(Person person) {
 StringBuilder idWithText = new StringBuilder();
 String idText;
 Date time = null;
 Level level;

 Exercise exerciseRecord = getExercise(person);
 if (exerciseRecord != null && exerciseRecord.getId() != null) {

 if(exerciseRecord.getLevel1() != null && exerciseRecord.getLevel2() != null){
 level = new Level(exerciseRecord.getLevel1(), exerciseRecord.getLevel2());
 } else {
 level = new Level("1", "1");
 idText = getIdText(level, exerciseRecord.getId());

 if(!Strings.isNullOrEmpty(idText)) {
 idWithText = idWithText.append(exerciseRecord.getId()).append(" " + idText);

 if (exerciseRecord.getTime() != null) {
 time = exerciseRecord.getTime().toDate();

 return new Triplet<>(idWithText.toString(), "1", formatTime(time));

 return new Triplet<>("", "", "");

Ηow can I make the above code look simpler? I've seen a little use of Optional but I don't know if it's good to use them in my case. Could someone help with the method refactor?


No Comments to show

© 2023 Copyrights reserved for web-brackets.com