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

前端 未结 12 1366
猫巷女王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:41

    I am doing this very same thing at the moment. All of the variables in the code that I am reworking are declared at the top of the function. I've seen as I've been looking through this that several variables are declared but NEVER used or they are declared and operations are being done with them (ie parsing a String and then setting a Calendar object with the date/time values from the string) but then the resulting Calendar object is NEVER used.

    I am going through and cleaning these up by taking the declarations from the top and moving them down in the function to a spot closer to where it is used.

提交回复
热议问题