←back to thread

498 points azhenley | 2 comments | | HN request time: 0.439s | source
Show context
EastLondonCoder ◴[] No.45770007[source]
After a 2 year Clojure stint I find it very hard to explain the clarity that comes with immutability for programmers used to trigger effects with a mutation.

I think it may be one of those things you have to see in order to understand.

replies(17): >>45770035 #>>45770426 #>>45770485 #>>45770884 #>>45770924 #>>45771438 #>>45771558 #>>45771722 #>>45772048 #>>45772446 #>>45773479 #>>45775905 #>>45777189 #>>45779458 #>>45780612 #>>45780778 #>>45781186 #
ErroneousBosh ◴[] No.45771722[source]
I guess I'm not that good a programmer, because I don't really understand why variables that can't be varied are useful, or why you'd use that.

How do you write code that actually works?

replies(4): >>45771824 #>>45772583 #>>45773343 #>>45787597 #
jayd16 ◴[] No.45772583[source]
If you need new values you just make new things.

If you want to do an operation on fooA, you don't mutate fooA. You call fooB = MyFunc(fooA) and use fooB.

The nice thing here is you can pass around pointers to fooA and never worry that anything is going to change it underneath you.

You don't need to protect private variables because your internal workings cannot be mutated. Other code can copy it but not disrupt it.

replies(2): >>45774996 #>>45775589 #
ErroneousBosh ◴[] No.45775589[source]
> If you want to do an operation on fooA, you don't mutate fooA. You call fooB = MyFunc(fooA) and use fooB.

This is the bit I don't get.

Why would I do that? I will never want a fooA and a fooB. I can't see any circumstances where having a correct fooB and an incorrect fooA kicking around would be useful.

replies(2): >>45775807 #>>45776159 #
jayd16 ◴[] No.45775807[source]
As Carmack points out, naming the intermediate values aides in debugging. It also helps you write code as you can give a name to every mutation.

But also keep in mind that correct and incorrect is not binary. You might want to pass a fooA to another class that does not want the fooB mutation.

If you just have foo, you end up with situations where a copy should have happened but didn't and then you get unwanted changes.

replies(1): >>45777571 #
1. ErroneousBosh ◴[] No.45777571[source]
But that's just it, why would a copy ever happen? Why would you want a correct and an incorrect version of your variable hanging about?
replies(1): >>45783489 #
2. kubanczyk ◴[] No.45783489[source]
Taking your point of view: you assigned a value1 to a name. Then you assigned a value2 to the same name.

You say that value2 is correct. It logically follows that value1 was incorrect. Why did you assign it then?

The names are free, you can just use a correct name every single time.