Java中的变量声明放置指南 [英] Variable declaration placement guidelines in Java

查看:176
本文介绍了Java中的变量声明放置指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有两个可接受的Java变量的变量声明展示位置,每个变量都具有不同的

There seems to be two accepted variable declaration placements for Java variables, each with different raison d'être.

href =http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html> Sun的代码约定,我们可以看到:

From the Sun's code conventions we can see:

仅在块的开头放置声明。 (一个块是由大括号{和}包围的任何
代码。)不要等到声明
变量,直到它们第一次使用;它可以混淆在范围内的不经意的程序员
和hamper代码的可移植性。

Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

但是在高度赞扬的代码完成和一些其他作者主张将变量的范围缩小到最小。这基本上等待声明变量直到第一次使用。

However in the highly praised "Code Complete" and some other authors advocate for reducing the scope of a variable to a minimum. That is basically waiting to declare variables until their first use.

这两种方法显然是矛盾的,虽然我可以看到他们两个的点。

These two approaches are clearly contradictory although I can see the point for both of them.

我应该跟着什么?关于这个问题是否有共识?

Which should I follow? Is there any consensus on the matter?

推荐答案

应该声明变量可能,原因有二:

Variables should be declared as close to their use as possible, for two reasons:


  • 垂直位置

  • 工具提示

垂直局部性可以更容易地解释大块代码。读者必须做的扫描越少,就越容易理解代码的作用和副作用。

Vertical locality makes it easier to reason about chunks of code. The less scanning a reader has to do the easier it is to understand what code does, and what side-effects it

减少变量范围也允许更好的工具提示用于自动化工具,例如重构。

Reducing variable scope also allows better tool hinting for automated tools, like refactoring. The closer together related things are the more obvious they are.

这就是说:如果一个方法足够长,以上的点来玩,很可能该方法是已经太长了,反正应该重构。

That said: if a method is long enough that the above points come in to play, it's likely the method is already too long, and should be refactored anyway.

这篇关于Java中的变量声明放置指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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