[LRUG] The advantage of immutability?

jc at panagile.com jc at panagile.com
Wed Sep 9 03:41:49 PDT 2015


In the absense of any smart people replying so far I’ll give this a go.




This isn’t a straightforward question, and it’s complicated by the fact that the example you gave is specifically about updating shared global state (the database) and by wanting to use an ORM which is designed to act like a local representation of that shared global state. So now that the problem is phrased in terms of wanting to manipulate shared global state then mutability seems like the correct option.




So how about this:




1) You load the Request from the database

2) You call some other method, passing in the Request object (e.g., maybe you pass it to logging method)

3) You update the status

4) You save the Request




What is the state of the world now? You probably expect it to be the same as the state of the world before, plus the change to the status. But you don’t know that - you don’t know if the other method also modified the Request object, either intentionally or by accident.




When you get to step 2 you want the Request object to be immutable. Of course, if the object is immutable then you need to change the way you write steps 3 & 4. Treating objects as immutable doesn’t work well with an ActiveRecord style ORM.

On Wed, Sep 9, 2015 at 11:25 AM, Jonathon Horsman <jonathon at arctickiwi.com>
wrote:

> Hey smart people
> Can you shed some light on why an immutable object is an advantage for a
> web-based Ruby app?
> For example this app I'm working on has these Request things and a user has
> the ability to deny a Request.
> So the user would click a button which performs a post to the Request
> controller's deny action.
> If I were using Rails or some non-immutable based system I would fetch the
> object from the database, set it's status to denied, and save it.
> However since this Request is an immutable object, I have to either:
> 1. Write an update_status method which sets that value in the database,
> which becomes tedious when there's lots of possible attribute update
> combinations
> or
> 2. Read the object from the database, copy all the values to a new object
> with the denied status, and stick that back into the database. Seems like
> pointless overhead and could be dangerous if later that object gets another
> attribute which I forget to copy.
> My knowledge of immutable objects originates with Java Strings which I
> understand makes sense for performance and memory management reasons.
> I don't think this applies here though?
> Thanks!
> Jonno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150909/eaaafe6e/attachment-0003.html>


More information about the Chat mailing list