vendredi 27 novembre 2020

Alternative approach for checking data types to build an object

I'm trying to build an object, which uses different methods based on different data types. I.e. it differs from withBooleanValue,withStringValue and withDateValue depending on the data type. What I have is a string, and depending on what that string is (boolean, string or date), I need to build this object. Below is how I went about it.

private List<Answer> getAnswers(Set<Question> questions) {
        List<Answer> answers = new ArrayList<>();
        questions.forEach(question -> {
            Answer.Builder answer = Answer.builder()
                    .withQuestion(question.question());
            if (BooleanUtils.toBooleanObject(question.value()) != null) {
                answer.withValue(AnswerValue.builder()
                        .withBooleanValue(BooleanUtils.toBoolean(question.value()))
                        .build());
            } else {
                try {
                    Date dateValue = DateUtils.parseDate(question.value(), new String[]{"dd-MM-YYYY"});
                    answer.withValue(AnswerValue.builder()
                            .withDateValue(dateValue)
                            .build());

                } catch (ParseException e) {
                    answer.withValue(AnswerValue.builder()
                            .withStringValue(question.value())
                            .build());
                }
            }
            answers.add(answer.build());
        });
        return answers;
    }

Is there a better way to do this in Java8? Somehow the ifs, and try-catch statements make it look very complicated and I'd like to reduce the lines and complexity with a better way. Any advice would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire