3 ms·
"const" does not add anything new to a variable. If you don't want to change the value of a variable ... don't change the value of the variable. I've got
by noelwelsh 15y ago
"const" does not add anything new to a variable.
If you don't want to change the value of a variable ...
don't change the value of the variable.
I've got a better idea: how about we mark the variable in some way and get the compiler to remember this for us. Then, when we come back to the code in 6 months, we won't make mistakes.
I have a decade of experience in "dynamically" typed languages, and I prefer modern statically typed languages in almost all situations. Now it turns out you can have both: see Racket and Typed Racket for instance.
- samstokes 15y agoAbsolutely. I don't to have to remember which variables are safe to change and which ones aren't; I want the language to remember that, and to remind me if I get it wrong. Sometimes I might want to use a library in a way its author didn't previously intend, so I might then want to modify a variable even if it's marked as const. It makes sense in a dynamic language to have a way to bypass the checks (like Ruby's "send" to access a private method). But that isn't an argument for discarding checks altogether.
- stdbrouw 15y ago"I've got a better idea: how about we mark the variable in some way" — if all you need is a mark, the Python convention to add an underscore in front of your private method or variable works just fine, as does the convention to make constants uppercased. I've seen quite a bit of JS code use these conventions too. The trouble with true private/protected variables is that you never really know how your code is going to get used and which parts of your library people may want to mess with. In that case, you can either play around with things you aren't really supposed to touch, or if that's not possible because everything's encapsulated, being in a hurry, you'll just fork the code and turn private methods into public ones. Both approaches suck, and the problem exists regardless of whether your language supports `private` and `const` keywords or not.
- ootachi 15y ago"if all you need is a mark, the Python convention to add an underscore in front of your private method or variable works just fine, as does the convention to make constants uppercased. I've seen quite a bit of JS code use these conventions too." Until you have a user subclass your class and accidentally stomp over one of your private names, causing your class to mysteriously fail. I've been bitten by this before, and it'd be nice for JS to offer a solution.