In Java, should variables be declared at the top of a function, or as they're needed?

前端 未结 12 1396
猫巷女王i
猫巷女王i 2020-12-02 13:09

I\'m cleaning up Java code for someone who starts their functions by declaring all variables up top, and initializing them to null/0/whatever, as opposed to declaring them a

12条回答
  •  一向
    一向 (楼主)
    2020-12-02 13:48

    Defining variable in a wider scope than needed hinders understandability quite a bit. Limited scope signals that this variable has meaning for only this small block of code and you can not think about when reading further. This is a pretty important issue because of the tiny short-term working memory that the brain has (it said that on average you can keep track of only 7 things). One less thing to keep track of is significant.

    Similarly you really should try to avoid variables in the literal sense. Try to assign all things once, and declare them final so this is known to the reader. Not having to keep track whether something changes or not really cuts the cognitive load.

提交回复
热议问题