声明局部变量尽可能晚或属于最近的花括号? [英] Declare local variables as late as possible or at the nearest curly brace they belong?

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

问题描述

我的工作设置了一些编程实践,我的组织的标准。 否则,我碰到这个问题来了这个问题标题

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 good to have them at the top of method starting brace.

甲骨文标准也说要尽早申报。 我也是赞成的,他们属于最接近的大括号宣布他们。

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. code可读性

  1. Code Readability

性能

不容易出错

任何意见都欢迎。

推荐答案

这是什么麦康奈尔说,在他必读的书code完成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 code约定被广泛使用)。至于在哪里,他们首先声明,我耽误报关,尽可能的性能的原因(声明你可能不会使用变种是一种浪费)。除非你事先知道它要用于肯定的是,在这种情况下,你可以将它与其他增值经销商,以提高可读性组。我认为这是<一href="http://www.oracle.com/technetwork/java/javase/documentation/$c$cconventions-141270.html#16817">what江铜集团表示,它的。

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.

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

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