3 ms·
> However, declaring variables close to where they use is a different kind of "cohesion", since it's keeping related things together Cohesion is about keeping
by jstimpfle 11y ago
> However, declaring variables close to where they use is a different kind of "cohesion", since it's keeping related things together
Cohesion is about keeping unrelated things apart (to avoid accidental complexity).
If two things are semantically unrelated, you should be able to name both (yes, it is hard). If you want the separation statically asserted keep them syntactically separated [1]. There you go -- make two smaller functions, each with a clear scope and a descriptive name.
If you feel a function is doing unrelated things (because the data is not very "cohesive") but can't tell why, why not being honest about it and still host all the variables at the top.
Being disciplined in this way has found me appropriate code factorings, and many bugs in previously ill-factored code, both syntactic and semantic.
[1] in John Carmack's words "what's syntactically allowed will eventually end up in your codebase"