How to create an object of proper type elegantly from the given input?

Viewed 63

I get packets from the network that looks as follows in the following DTO form:

data class ContentElementField(
    val text: String? = null,
    val style: String? = null,
    val imagePath: String? = null,
    val caption: String? = null
)

The packet has the following invariant that specifies that either text and style or imagePath and caption are set together. One group excludes the other.

By following this invariant,

abstract class ContentElement

data class TextElement(val text: Text, val style: Style) : ContentElement()

data class ImageElement(val picturePath: Path, val caption: Text) : ContentElement()

either TextElement or ImageElement is created.

I abstain from writing a code as follows to implement this behavior:

if (isTextElementField(contentElementField)) createTextElement(contentElement.text, contentElement.style)

else if (isImageElementField(contentElementField)) createImageElement(contentElement.imagePath, contentElement.caption)

Because in the future, there will be more specific content elements to be added. This leads me to expand the branching above as more specific content elements are added. I believe it can be implemented through polymorphism or double-dispatching through the visitor pattern.

What would you offer to solve this?

0 Answers
Related