Search code examples
javanullpointerexceptionrefactoring

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?


Solution

  • You need to split the huge method into several simple, it will decrease complexity.

        private Triplet<String, String, String> getInfoFromTable(Person person) {
            Exercise exerciseRecord = getExercise(person);
            if (exerciseRecord != null && exerciseRecord.getId() != null) {
                 return new Triplet<>(getIdWithText(exerciseRecord, getLevel(exerciseRecord)), "1", formatTime(exerciseRecord.getTime()));
            }
            return new Triplet<>("", "", "");
        }
    
        private String formatTime(LocalTime time) {
            if (time == null) {
                return "";
            }
            return formatTime(time.toDate());
        }
    
        private Level getLevel(Exercise exerciseRecord) {
            Level level;
            if(exerciseRecord.getLevel1() != null &&  exerciseRecord.getLevel2() != null){
                level = new Level(exerciseRecord.getLevel1(), exerciseRecord.getLevel2());
            } else {
                level = new Level("1", "1");
            }
            return level;
        }
    
        private String getIdWithText(Exercise exerciseRecord, Level level) {
            String idWithText = "";
            String idText = getIdText(level, exerciseRecord.getId());
            if(!Strings.isNullOrEmpty(idText)) {
                idWithText = String.format("%s %s", exerciseRecord.getId(), idText);
            }
            return idWithText;
        }