How to do polymorphism in a process-based world

I am getting more and more used to writing things in Elixir. However, when trying to create intermediate applications that use multiple processes, my years of working with Object-Oriented Programming languages kick in, wanting to create processes that re-use some of the logic of other processes. In other words: Some kind of polymorphism.

Say I have a type of GenServer called Vehicle. This Vehicle has a function called drive(pid, kilometers), which modifies the given vehicle process’s state, to keep track of the total kilometers driven.

I also have a GenServer called Car, also having a drive/2 function. Car behaves in exactly the same way as Vehicle, except that the amount of kilometers driven also subtracts some of the gasoline amount left in the cars fuel tank.

How is functionality like above properly constructed in Elixir? How can I re-use things defined in Vehicle for Car?

1 Like

To clarify: I totally understand that processes are not the same thing as objects from an OOP-language. (Although some might argue that they are closer to what Alan Kay envisioned).

I am just wondering how to properly re-use code (i.e. avoiding code-duplication), and how to talk to two different but similar types of processes properly.

1 Like

I say In FP you do everything by operate on pure functions, functions composition, higher order functions.
So for example you can have higher order function drive-common with common logic for drive that has as input parameter lower order function with logic specific to Car car-specific or Vehicle vehicle-specific.
pseudo code:

drive-for-car = drive-common(car-specific)
drive-for-vehicle = drive-common(vehicle-specific)

Processes are not the same as objects in OOP and I will say they has nothing to do with polymorphisms.



You should probably look into Elixir Protocols.


Yep protocols are interesting. They allow to add implementation for protocol (interface in OOP) functions to existing module without modifying code of this module. Maybe something like monkey patching but much better.

Thank you. Protocols indeed seem to be what I was looking for.