Geekin.gs

geek writings 
« Back to blog

Switching from ruby to erlang part 1, immutability

I've been recently speaking about the Erlang adoption at wooga at the Erlang Factory in San Francisco. While preparing that talk I wrote few slides about my experience of switching from ruby to erlang, those slides weren't included in the final talk because of time reason to make space for content more relevant for the specific talk.

I still thought that I'll share my experience as it might be interesting for others currently devoting their time to ruby but looking into approaching erlang.

Immutability

For some reason this seems to be the weirdest and most exotic carcateristic of erlang, I have to say that instead getting used - and taking profit - from immutability was very quick. It's sufficient to follow a very simple rule "Assign a variable only once" and it soon becomes natural.

I think that the constraint of immutability seems bigger to people coming from a ruby background because in ruby some variables happen to be long lived, in erlang a variable lives only within a function and if your functions are tight you'll soon notice that you don't really miss mutable variables.

One benefit you get from immutability is clarity, once a value is bound to variable you're sure about its content, no surprises.

Immutability enforces the following if a function applied to a variable returns a different value then a new variable is needed in order to store the new value, this is actully a big deal, because it means that every time you change a value you have always availble the previous value, this make very easy to implement transactions in your application logic.

Let's look at some code just cut out from the gen_server standard docs

We have a function that given a request (Request variable) coming from some other process (From variable) and the current state (State variable) applies the function 'myfun' from the module 'mylib' in order to move from the current state to a different state that will be bound to the variable NewState.

Now, let's say that we detect that something is wrong in the NewState, the good news is that we have still the original state bound to the variable State and we can just use it to rollback to it.

It' very easy to follow the same pattern in other languages, but the fact that in erlang this is the default (and only possible) behavior let you operate in a very consistent and safe environment.

I'm going to close this post here, I have few more points to cover and I'll do so in the near future. Thanks for reading.

Comments (0)

Leave a comment...