在Java中,应该将变量声明在函数的顶部,还是需要它们? [英] In Java, should variables be declared at the top of a function, or as they're needed?

查看:162
本文介绍了在Java中,应该将变量声明在函数的顶部,还是需要它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过声明所有变量向上,并将它们初始化为null / 0 /无论什么,而不是像以后需要的那样声明它们,开始他们的函数的人清理Java代码。

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 as they're needed later on.

有什么具体的指导方针?有没有优化原因的方式或其他,或者是一种方式只是好的做法?是否有任何偏离任何正确方法的可接受的情况?

What are the specific guidelines for this? Are there optimization reasons for one way or the other, or is one way just good practice? Are there any cases where it's acceptable to deviate from whatever the proper way of doing it is?

推荐答案

将变量声明为接近第一点,你使用他们尽可能。这不是真的与效率有关,但使你的代码更加可读性。变量越靠近它被使用的地方,在后面读代码时,滚动/搜索就越少。将变量声明为更接近第一个位置,它们也会自然缩小其范围

Declare variables as close to the first spot that you use them as possible. It's not really anything to do with efficiency, but makes your code much more readable. The closer a variable is declared to where it is used, the less scrolling/searching you have to do when reading the code later. Declaring variables closer to the first spot they're used will also naturally narrow their scope.

这篇关于在Java中,应该将变量声明在函数的顶部,还是需要它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆