I have the below code to write. It is taking one kind of enum type and return other enum value. How to remove the too much if else condition in the code and make it clean?
private static QuestionType parseQuestionType(QuestionTypeInfo questionTypeInfo) {
if (questionTypeInfo instanceof OpenEndedTextQuestionTypeInfo) {
return QuestionType.OPEN_ENDED;
} else if (questionTypeInfo instanceof MultiChoiceQuestionTypeInfo) {
return QuestionType.MULTI_CHOICE;
} else if (questionTypeInfo instanceof MatrixSinglePerRowQuestionTypeInfo) {
return QuestionType.MATRIX_SINGLE_PER_ROW;
} else if (questionTypeInfo instanceof OpenEndedTextQuestionTypeInfo) {
return QuestionType.OPEN_ENDED;
} else if (questionTypeInfo instanceof MatrixMultiPerRowQuestionTypeInfo) {
return QuestionType.MATRIX_MULTI_PER_ROW;
} else if (questionTypeInfo instanceof MatrixSideBySideQuestionTypeInfo) {
return QuestionType.MATRIX_SIDE_BY_SIDE;
} else if (questionTypeInfo instanceof MatrixSpreadSheetQuestionTypeInfo) {
return QuestionType.MATRIX_SPREAD_SHEET;
} else if (questionTypeInfo instanceof DataListQuestionTypeInfo) {
return QuestionType.DATA_LIST;
} else if (questionTypeInfo instanceof FileUploadQuestionTypeInfo) {
return QuestionType.FILE_UPLOAD;
} else if (questionTypeInfo instanceof InteractiveSlidingScaleQuestionTypeInfo) {
return QuestionType.INTERACTIVE_SLIDING_SCALE;
} else if (questionTypeInfo instanceof NetPromoterQuestionTypeInfo) {
return QuestionType.NET_PROMOTER;
} else if (questionTypeInfo instanceof RankOrderQuestionTypeInfo) {
return QuestionType.RANK_ORDER;
} else if (questionTypeInfo instanceof PresentationHeaderQuestionTypeInfo) {
return QuestionType.PRESENTATION_HEADER;
} else if (questionTypeInfo instanceof PresentationHtmlQuestionTypeInfo) {
return QuestionType.PRESENTATION_HTML;
} else if (questionTypeInfo instanceof AutoIncrementQuestionTypeInfo) {
return QuestionType.AUTO_INCREMENT;
} else if (questionTypeInfo instanceof SingleChoiceQuestionTypeInfo) {
return QuestionType.SINGLE_CHOICE;
}
return null;
}
You can use a Map
as others suggested, but I personally would make use of delegation, if it makes sense in your case. In your QuestionTypeInfo
interface, declare an abstract method getQuestionType
that returns instance of the QuestionType
enum, and override it in all of its implementations with proper value.
interface QuestionTypeInfo {
QuestionType getQuestionType();
}
enum OpenEndedTextQuestionTypeInfo implements QuestionTypeInfo {
@Override
public QuestionType getQuestionType() {
return QuestionType.OPEN_ENDED;
}
}
Then, in the parseQuestionType
method, just use:
private static QuestionType parseQuestionType(QuestionTypeInfo questionTypeInfo) {
return questionTypeInfo.getQuestionType();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With