方法内有多个打开和关闭的花括号。 - Java [英] Multiple open and close curly brackets inside method. - Java
问题描述
public class MyTestClass {
public static void main(String[] args) {
new MyTestClass().myMethod();
}
public void myMethod(){
{
//do something
}
{
//do something
}
{
//do something
}
}//method close
}//class close
这样做有什么好处?我见过这种代码。
What is the benefit of doing this? I have seen this kind of code.
推荐答案
做这种事并不常见,我不会通常这样做。
It is not common practice to do this kind of thing, and I wouldn't do it normally.
这些内部块(即 {...}
)可用于以下几个目的:
Those inner blocks ( i.e. { ... }
) can serve a couple of purposes:
-
块限制在其中声明的任何变量的范围;例如。
Blocks limit the scope of any variables declared within them; e.g.
public void foo() {
int i = 1;
{
int j = 2;
}
// Can't refer to the "j" declared here. But can declare a new one.
int j = 3;
}
但是,我不建议这样做。 IMO,最好使用不同的变量名称或将代码重构为更小的方法。无论哪种方式,大多数Java程序员都会认为 {
和}
是令人讨厌的视觉混乱。
However, I wouldn't recommend doing this. IMO, it's better to use different variable names OR refactor the code into smaller methods. Either way, most Java programmers would regard the {
and }
as annoying visual clutter.
可以使用块来附加标签。
Blocks can be used to attach labels.
HERE : {
...
break HERE; // breaks to the statement following the block
...
}
但是,在实践中,你几乎看不到带标签的断言。而且因为它们非常不寻常,它们往往会使代码的可读性降低。
However, in practice you hardly ever see labelled break statements. And because they are so unusual, they tend to render the code less readable.
这篇关于方法内有多个打开和关闭的花括号。 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!