Hacker News new | ask | show | jobs
by danielscrubs 2228 days ago
When I read that it's const I can in my mind "drop it". It's there, I know where the value was set and don't have to skim any longer for updates. It isn't for the compiler, its for me, the next guy who has to read your code.

Same thing with doing two separate things in the loop. Not only can it stop the the compiler from optimisations from time to time (the c++ compiler is very clever... but many times it gives up), I've had speed increases in breaking it up into several loops, but I also have to search and in my mind break things up. Very easy to do when I'm writing the code (and I'd probably do the same because of laziness), but quite annoying when I read someone else's code that does it.

1 comments

If you as a reader need const to make sure a local variable is not changed this is usually a symptom of this function being too long to see at a glance. And quite often as code changes I do need to make some local variable non-const, and it quickly becomes annoying to fiddle back and forth enforcing const-ness of every local variable.

The argument about optimization is almost certainly premature optimization. Most of the time how you write a loop doesn't matter. You only find out what matters via profiling and refactor accordingly.

> If you as a reader need const to make sure a local variable is not changed this is usually a symptom of this function being too long to see at a glance

If the compiler can enfore an invariant (constness), why cede that functionality on the hopes you can ensure it yourself?

By the same line of argumentation you should do away with the static type system.

Most people hate const at first (myself included) but once you get used to it, it really does reduces mental load. Not having to glance around is precisely the point, its not a big thing but it does help.
I stopped using it for locals after it increased my mental load. The maintenance cost of const for all local variables is huge during refactor like you're fighting it just to get things done. And in most cases where the type of a variable matters I do have to glance around like when I need to remove a variable or change its type or refactor its dependent variables so const doesn't really for those cases.
If you have to assign to a const variable during a small refactor, then maybe it shouldn't have been const in the first place? I'm struggling to imagine examples where this is a real problem
So you prioritise the writing of the code instead of the reading.

In that case, it makes sense.