5 ms·
One take away from functional programming that I have incorporated into my Java (and C#) code: If/When possible, never (ever ever!!!) re-assign a local variable
by throwaway2037 4y ago
One take away from functional programming that I have incorporated into my Java (and C#) code: If/When possible, never (ever ever!!!) re-assign a local variable. (Rare exception: Classic C-style for-loop iteration with mutable `i` integer variable.) Really, really, I am not trolling / not a joke. How / Why? How? All primative parameter value must be final, e.g., `final iint level`, and local variables must always be final. Why? Final vars are significantly easier to "reason about" when reading code, as compared to non-final (mutable) vars. If you are using containers, always, always, always use immutable containers from Google Guava unless you have an exceptionally good reason. Yes, the memory overhead will be higher, but big enterprise corps do not care about adding 4/8/16 extra GB RAM to host your Java / C# app. Yes, I know that any `Object` in Java is potentially mutable. As a work-around, try to make all `Object`s immutable where possible. On the surface, the whole thing / exercise feels like a terrible Computer Science nitemare. In practice, it becomes trivial to convert code from single-threaded to multi-threaded because most of your data classes are already "truly" final.
- wtetzner 4y ago> If you are using containers, always, always, always use immutable containers from Google Guava unless you have an exceptionally good reason. I actually prefer pcollections: https://github.com/hrldcpr/pcollections https://github.com/hrldcpr/pcollections AtomicReference + immutable data types is a really nice way to program in Java, and is basically the way most Clojure programs are written.
- acchow 4y agoRead the example about “producers” - If I chain a whole bunch of producing together across many different Pcollections, I’m essentially forming a graph behind the scenes? Since no copying is happening Surely this would cause some strange performance outcomes with, say, a gradually built up immutable list.
- wtetzner 4y agoWhat do you mean by “strange performance outcomes”?
- waynesonfire 4y ago> If/When possible, never (ever ever!!!) re-assign a local variable. Neat rule, but, it won't work. Firstly, as an example, Scala which allows you to declare a read only val, you still see vars used. There is no way you're going to get any traction enforcing this across the developer spectrum. The benefit of these concepts are realized when they are the only option, hence FP and why mixed paradigm languages are half-assed. Java isn't even a mixed-paradgim. You're wishing.
- viscanti 4y ago> Neat rule, but, it won't work. You'd get the benefit of easier to reason about code everywhere you used it, even if others within the codebase don't. Using that argument, we would argue that it's never worth trying to find a cleaner way to implement something because maybe some intern some day will do something weird in a different part of the code base. We don't have to drop down to the lowest common denominator for code quality and we benefit every time we simplify things, even if not everyone does.
- kaba0 4y agoLocal mutability is perfectly fine, and depending on the algorithm can be much more readable. Use the best tool for the job.
- throwaway2037 4y agoCan you provide an example algortithm?
- lmm 4y ago> Scala which allows you to declare a read only val, you still see vars used. You see them very rarely, and usually with a narrow scope. I agree that you probably can't enforce an absolute rule of no mutable variables. But making it the exception rather than the rule (e.g. require it to be justified in code review) makes a huge difference.
- quickthrower2 4y agoI rarely reassign local variables too. (Other then the set to null as a fallback then set again in a branch “pattern”). The only excuse is when I am doing something algorithmic and that would improve the performance. By extension I prefer local variables over class state and static state and other “self managed lifetime” stuff like that. And I am a GC blub programmer, I don’t use Rust or C.
- throwaway2037 4y agoYou wrote: <<GC blub programmer>> This is a great expression! Hat tip to Joel Spolsky for his blub programming language paradox. I know the feeling. When you read too much HN, you think the whole world is writing C & Rust.
- quickthrower2 4y agoThanks… I was being tongue in cheek of course.
- senand 4y agoAgreed, I see this as a code smell. It's already hard from a semantic point-of-view, normally you have then the same name for two different meanings.
- P_I_Staker 4y agoThat's interesting. On the other hand, I've seen code go through great lengths to not do a double assign. I doubt it was easier to reason about at all. The code set an error var on a number of if / else conditions. They then used a separate flag, so that a double write wouldn't be necessary. ie. int flag = 0; int err; // notice no initializer if(stuff) { flag = 1; err = 1; } else {} if(other_stuff) { flag = 1; err = 2; } else {} if(flag) { LogError(err); } I follow the "avoid double write" convention too, but in some cases, it can become very difficult to reason whether a local is uninitialized; this is a pretty terrible class of bug, because you work with garbage data off of the stack. Setting to zero at declaration makes it much clearer that it will never be uninitialized, but it's essentially meaningless and arguably a form of dead code. Maybe someone will suggest a redesign? More functions, smaller functions? It seems that there's a strong (though unpopular) argument that you should use medium sized functions, and some teams insist on doing this. In some cases, it can be easier to find the content, verify specifications. Edit: On second thought I can see we didn't avoid the double write, just did it in a different variable. So I don't understand what the author's point is, lol.
- bluefirebrand 4y agoWhen I have a flag that is bouncing through a bunch of conditionals only to return at the end, I prefer to change it to multiple return paths instead of multiple spots to modify the flag that is being returned. If you are doing a lot of work inside those branches it may be worth a refactor to simplify the branching logic.
- throwaway2037 4y agoYou wrote: <<multiple return paths>> From experience, I have never once heard anyone from higher-level languages (above C & C++) complain about "multiple return paths". That said, for C, I definitely understand the need for reduced return paths due to lack of auto-free / destructor mechanics.
- P_I_Staker 4y agoIt wasn't THAT bad, but still annoying to figure out; and I would argue that this is never definitive. At least by basic inspection it's so easy to set an error. The fact that it set off the static analyzer is very annoying too. Now I have to somehow debug the static analyzer, or just accept the risks. I've had some uncomfortable experiences assuming the analyzer is wrong and ignoring or suppressing it... theoretically, the static analysis will do a much better job than a human, so I can't help but doubt, and feel I missed something. Just as an aside, some teams try to avoid multiple return paths. I believe there's some studies indicating a higher incidence of bugs... for a solid code quality reason you could theoretically deviate.
- rzzzt 4y agoJava 11+ has factory methods for unmodifiable collections: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#unmodifiable https://docs.oracle.com/en/java/javase/11/docs/api/java.base...
- hinkley 4y agoThere's a short list of reasons to factor out a method. The most popular one is "if you see the need for inline comments for a block of code, maybe the code shouldn't be inline", but feeling the need to redefine a variable, especially in the middle of a function, is often a good indicator of a new scope starting. Sending variable foo with an increment, a merge, or a concatenation to another function is fairly readable. Having foo and foo' inline is quite a bit harder on working memory.
- matheusmoreira 4y ago> Yes, the memory overhead will be higher, but big enterprise corps do not care about adding 4/8/16 extra GB RAM to host your Java / C# app. Stuff like this is the reason why functional programming is synonymous with inefficiency and why Real Programming™ is still done in languages like C.
- throwaway2037 4y agoIt is interesting that you wrote <<why functional programming is synonymous with inefficiency>>. Most people would say <<why GC blub languages [Java, C#, etc.] are synonymous with inefficiency>>. I actually agree with my rewrite, but I deliver value much slower with non-GC languages. The IDE uplift from Java & C# is just so crazy good. It is hard to beat for many enterprise scenarios. Plus, the developers are much cheaper than C, C++, and Rust programmers.
- gregmac 4y agoI agree with the other comments about it often being a hint to break apart a method, but there's still valid reasons to reassign. I'd rather focus my energy on adding unit testing, and refactoring to be testable. If you have easy-to-read unit tests that cover all possible edge cases, I stop caring (as much) about how the actual method is written. Be as optimized/clever/concise as you want. I don't care if you reassign your local variables.
- lupire 4y agoIt's much more important to make global variables (object fields) final, not locals. Locals are much much easier to test and reason about, and functional languages lie Haskell and Clojure have great support for mutable locals (ST / transient)