4 ms·
On the other hand, when skimming some code, does it matter on the first pass whether a given variable is mutable? Probably not if we're just trying to get an id
by tn1 4y ago
On the other hand, when skimming some code, does it matter on the first pass whether a given variable is mutable? Probably not if we're just trying to get an idea of how it works; later on a closer read we can look closer if it matters.
- mojuba 4y agoIt absolutey matters when skimming a well written code. Whether a variable is immutable or not is almost as important as its type.
- hoseja 4y agoWell, it is part of its type.
- nicoburns 4y agoI find this super-important. If a variable if mutable then I need to look closely through the whole of the rest of the scope to see if/where it is mutated. If it's not then I can often mostly forget about it. Thus marking variables as immutable where possible dramatically reduces the mental overhead of reading a function.
- vbezhenar 4y agoWhat I've found helpful is to configure IDE to use a separate formatting for mutable variables. You don't even need `var`/`val` for that, just smart enough IDE. Something like single underline for those variables. This way they're obvious and you'll know it when reading the code.
- nicoburns 4y agoI mostly use JavaScript (which uses `const` and `let`) and Rust (which uses `let` and `let mut`), so I've find them quite easy to tell apart just based on the syntax :)
- unwind 4y agoThis is the reasoning behind the "const all the things" in C and similar languages, which doesn't have distinct keywords but where you can use "const" to make things immutable. If a variable is const-declared, I react in exactly the same way and know that I don't have to look for further uses, which I find very valuable. I even do stuff like this, which might be extreme but I find it coherent and nice: void * allocate_and_fill(size_t size, unsigned char x) { void * const p = malloc(size); if (p != NULL) memset(p, x, size); return p; } The above const-declares the local pointer p, so that it can never be intentionally clobbered inside the function, which would leak the memory. Since it's the pointer itself that is constant, not the data being pointed at, there is no problem in modifying that memory, and the return value is not const-declared in any way.