方法重构以避免许多 npe 检查

Method refactoring to avoid to many npe checks

我创建了以下方法,其中 returns 一个字符串的三元组。但是,我不喜欢我写它的方式,因为我认为我进行了太多的 Npe 检查,使它变得不可读。

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<>("", "", "");
}

如何使上面的代码看起来更简单?我已经看到 Optional 的一些使用,但我不知道在我的情况下使用它们是否好。有人可以帮助重构方法吗?

你需要把庞大的方法拆分成几个简单的方法,这样会降低复杂度。

    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;
    }