The goal is to build a String
from a given set where Feedback
is an interface and DeliveryFeedback
, and ProductFeedback
are its implementing classes.
private void formatOrderFeedbackZendeskBody(final ImmutableSet<Feedback> feedback) {
StringBuilder feedbackMessage = new StringBuilder("The feedback: ");
feedback.forEach(
f -> {
if (f instanceof DeliveryFeedback) {
feedbackMessage
.append("\n\nType: ")
.append(FeedbackType.DELIVERY)
.append("\nReason(s): ")
.append(
((DeliveryFeedback) f)
.getReasons()
.stream()
.map(Reason::name)
.collect(joining("\n\t\t\t")));
if (((DeliveryFeedback) f).getComment().isPresent()) {
feedbackMessage
.append("\nComment: ")
.append(((DeliveryFeedback) f).getComment().get());
}
} else if (f instanceof ProductFeedback) {
feedbackMessage
.append("\n\nType: ")
.append(FeedbackType.PRODUCT)
.append("\nReason(s): ")
.append(
((ProductFeedback) f)
.getReasons()
.stream()
.map(
ProductFeedbackInterface.Reason
::name)
.collect(joining("\n\t\t\t")))
.append("\nArticle ID: ")
.append(((ProductFeedback) f).getArticleId());
if (((ProductFeedback) f).getImageIds().isEmpty()) {
feedbackMessage.append(
"\nNo images available.");
} else {
feedbackMessage
.append("\nImage URLs: ")
.append(
((ProductFeedback) f)
.getImageIds()
.stream()
.collect(joining(", ")));
}
if (((ProductFeedback) f).getComment().isPresent()) {
feedbackMessage
.append("\nComment: ")
.append(((ProductFeedback) f).getComment().get());
}
}
});
}
I am getting the expected String
:
Detailed feedback:
Type: DELIVERY
Reason(s): REASON1
REASON2
Comment: another comment
Type: PRODUCT
Reason(s): REASON3
REASON4
Article ID: idsug
Image URLs: idsug, dfgh
Comment: comment
Type: PRODUCT
Reason(s): REASON5
REASON6
REASON7
Article ID: dfddddddddgh
No images available
I just think this code is not very readable and maybe there is another better way to do this that I am missing :)
Edit 1:
Just to make clear, the usage of the OrderFeedback
interface is only to give a type:
@JsonSubTypes({
@Type(name = FeedbackType.PRODUCT, value = ProductFeedback.class),
@Type(name = FeedbackType.DELIVERY, value = DeliveryFeedback.class),
})
@JsonTypeInfo(include = As.PROPERTY, property = "type", use = Id.NAME)
public interface OrderFeedback {}