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

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

问题描述

我正在为那些通过在顶部声明所有变量并将它们初始化为 null/0/whatever 来启动其函数的人清理 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天全站免登陆