尽可能晚地声明局部变量还是在它们所属的最近的花括号中声明

尽可能晚地声明局部变量还是在它们所属的最近的花括号中声明

本文介绍了尽可能晚地声明局部变量还是在它们所属的最近的花括号中声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力为我的组织制定一些编程实践标准.这样做我遇到了问题这个问题的标题"

I am working to set some programming practices standards for my organization.Doing so i came across the issue "Title of this question"

有些人认为最好尽可能晚地声明变量,有些人认为它很好将它们放在方法的顶部开始大括号.

Some finds it best declaring variables as late as possible and some finds its goodto have them at the top of method starting brace.

Oracle Standard 还说要尽早声明它们.我也赞成在它们所属的最近的花括号中声明它们.

Oracle Standard also says to declare them as early as possible.So do i in favor of declaring them at the closest curly brace they belong.

顾虑是

  1. 代码可读性

  1. Code Readability

性能

不易出错

欢迎任何评论.

推荐答案

这是 McConnell 在他的必读书籍 Code Complete 2 中所说的:

This is what McConnell says in his must-read book Code Complete 2:

理想情况下,在靠近使用位置的位置声明和定义每个变量.声明建立了变量的类型.定义为变量分配特定值.在支持它的语言中,例如 C++ 和 Java,变量的声明和定义应该靠近它们首次使用的位置.

他还建议让变量保持活动的时间尽可能短,并尽量减少范围.

He also recommends keeping variables alive for as short a time as possible, and to minimize scope.

对我来说重要的是遵循命名约定(Sun 的 Java 代码约定被广泛使用).至于他们第一次声明在哪里,出于性能原因,我会尽可能推迟声明(声明一个你可能不使用的 var 是一种浪费).除非您事先知道它肯定会被使用,否则您可以将它与其他变量组合在一起以提高可读性.我认为这是JCC 所说的.

The important thing for me is following naming conventions (Sun's Java Code Conventions are widely used). As for where are they first declared, I'd delay the declaration as much as possible for performance reasons (declaring a var you might not use is kind of a waste). Unless you know in advance it is going to be used for sure, in that case you can group it with other vars to improve readability. I think that is what JCC says about it.

这篇关于尽可能晚地声明局部变量还是在它们所属的最近的花括号中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:30