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

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

    From Google Java Style Guide:

    4.8.2.2 Declared when needed

    Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.

    Well, I'd follow what Google does, on a superficial level it might seem that declaring all variables at the top of the method/function would be "neater", it's quite apparent that it'd be beneficial to declare variables as necessary. It's subjective though, whatever feels intuitive to you.

提交回复
热议问题