Socket (re)assign or update?

I understand that update/3 takes a function and raises for non-existing keys. I know the key exists, I have a value to change and I can do it using inline function, variable, named function, … all using assign/3. Why (in what kind of situations) would I want to use update/3? Is it only about raising on non-existent keys? Or are there other reasons to use it?

I usually use update in places where a event is meant to trigger a certain change, rather than set a value.

update(socket, :count, fn x -> x + 1 end)

This to me very clearly communicates that this event handler is about incrementing a counter. It’s all about the provided callback and not at all about what x evaluates to when this is called – it couldn’t affect any other behaviour in the event handler, besides how count is updated.

Any alternative might be able got get to the same result, but not commuicate the same constraint.

5 Likes

So – if I understand correctly – in your case it is more about communicating your intents than any technical differences, right? I remember in the beginning I was only using assign as I didn’t even know that update existed and things surely worked as expected. Then I found update and started to use it for – well – updating values of preexisting keys but kept wondering whether there is something more to that than mostly semantics.

1 Like