Simple example: I have a content that can have plain or html body and a static or dynamic abstract. We can model it to use composition in the following way:
So, it’s pretty simple to use and understand how it works. If I want plain text content with dynamic abstract I just build my Content object with the respective concrete classes. If I want a static abstract it’s just a matter of creating a new object.
Do we have anything similar in Elixir and/or functional programming in general? Should I think of this problem in a different way?
From a horribly broken OOP perspective, think of an interface as a ‘behaviour’, a ‘class definition’ as a module, and a ‘class instance’ as an Actor/Process (should use a GenServer most of the time). You pass the Actor/Process PID around like you would a pointer in OOP languages.
However, that is really quite wrong if you went all out like that, in reality functional composition is significantly shorter and more powerful than OOP constructs and those should be used in general. As per the XY Problem, instead of saying ‘how’ you want to accomplish something, say ‘what’ you are wanting to accomplish, like what inputs and what outputs, we can help you convert from OOP to better methods then (that can help you when in OOP languages too).
By body and abstract, what are the possible values they can contain, let’s define that first as that will drive the rest of the code. For this post I will assume:
body : string() # Body is always a string
abstract : string() | nil # abstract is also a string or nil
post : { body, abstract } # post is a tuple of a body and an abstract
As always you should access data via functions, so you’d have something like a get_abstract call, maybe like this:
So we either have an empty input or a filled input for both fields.
Yes, I meant body. So if I fill an URL in the “body” textarea, a link to some news for instance, let’s suppose that the client will load the relevant html, fill the “body-content-type” and send it back to me.
Since I want to handle complex data - contents that have not only abstract and body, but also authorship metadata, publishing info, tags and other stuff - I guess I’m going to look into structs now.