Erlang 101: an attempt to implement CQRS
As you might have noticed in one of my previous posts, I am currently focussing on Erlang, because I assume that this platform might be the most efficient way to handle umphteen connections over the web for now (but that is the subject for another post).
After running my first experiments and getting everything up and running on Windows, I finally decided to stop fighting usage of windows combined with Erlang so I installed myself a virtualbox with Lubuntu LXDE (please note that you have to set the available memory on the virtual appliance to 512MB, or the installation will crash).
2nd attempt for a virtualbox install of Lubuntu LXDE; aparently the installer crashes with mem != 512MB #LOL— Tom * suǝssuɐſ (@ToJans) October 4, 2012
Before I start implementing what might be my next startup, I tried implementing one of the things that I consider to be my personal kata (I made numerous attempts in .Net): a CQRS implementation of a simple stock system.
Disclaimer: I am a complete newb in Erlang, so I presume I am still miles away from a more elegant implementation.
"Show me da Codez!!"
Here are the events:
And here is the code (including unit tests)
Running this on windows
In case you would like to test this on windows: install Erlang, and start werl.exe (= Erlang for windows). Download the source and save them in item.erl and item.hrl. Start up the Erlang console perform the following steps:
As usual, I learn new tech by diving in head-first; nevertheless this still looks ugly as hell; a few points where I could improve:
- Make sure the routing works in a proper way, i.e. spawn one process per id, and make sure the respective commands get sent to the correct AR's, this would allow me to remove the top 4 handle statements filtering out all the ones where the Id does not match the instance's.
- Instead of passing in records to
on-methods, I could probably shortcut this using a custom behavior, and use some kind of a convention, so I could replace
by something like
And the same for events.
- Getting to learn Erlang/OTP to the state that it is usable will probably require at least some months, being able to produce "nice" code even longer...
All in all this has been a valuable exercise to start with, next on my agenda is trying to build an minimum viable product for yet another start-up idea that crossed my mind.
In closing a message to more experienced Erlangers: feel free to fork the example and show me the proper way to do it!