Const: The Final Chapter

I was more or less weaned on C/C++, and one of the many *-isms I developed from that weaning (like ++pre-incrementing variables in for-loops for efficiency’s sake) was placing constants on the left side of comparisons to avoid accidental assignments (e.g. NULL == x). This practice has carried over to my Java code, serving no purpose other than to make people not used to writing code this way go cross-eyed when they read mine. Sorry, co-workers.

I also went through a “const correct” C++ phase where everything in my code was decorated with const. I even learned how to speak const-ese, and parse a “const pointer to a const pointer to const” and all its perverted little cousins. With Java’s weaker “final” concept, I never really went on a similar jag, although the temptation did occur occasionally.

Looking at some Java code recently, I noticed a combo of my constant == x idiom and my simultaneous urge to make x (a function parameter) final. Kind of like a couple being on the pill and using condoms at the same time. Then I had a thought: why aren’t all function parameters implicitly final/const/([insert language]’s concept of immutable)? It seems like it would automatically ratchet up the safety (and potentially performance) without all the syntactic bloat of variable decoration. What is the use case for actually wanting to alter function parameters? What do other non-Java/C languages have to say about this? I’m sure there are insurmountable legacy code issues, but is there any reason this is not a good idea in theory?

Blog comments powered by Disqus