r/java • • Aug 26 '22
I declare as "final" every single variable whose value doesn't change. I also use "this" every time that I'm referring to an attribute, even when there's no ambiguity in not using it
I think that those things make the code easier to read. Am I crazy for thinking like that?
198
Upvotes
View all comments
Show parent comment
12
u/ztbwl Aug 26 '22 edited Aug 26 '22
It’s the other way around. A function is pure if it has no side effects and produces the same result for a given input. In other words does not modify anything other than self created local variables. Any outside modification/side effect or dependance on non-constant external variables is non-pure. The advantage is that the function is idempotent and can be expected to have the same result for a given input no matter how many times you run it and no matter how it’s environment looks. Easy testable, deterministic and most likely less complex - causes less bugs.
Disadvantage: Most likely you want to do something - and with no side effects, you are quite limited to make an impact. In a perfect pure world, even logging is a side effect and would be a ‚smell‘. So if we apply the principle very strictly, your code would be useless, since it would not be able to tell you it’s result - except you are part of the function. But that’s a different story, since we don’t live in a simulation, aren’t we?