在Java中的方法中是否使用了自由浮动块? [英] Is there a use of free floating block inside a method in Java?

查看:69
本文介绍了在Java中的方法中是否使用了自由浮动块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道方法可能有这样的浮动块:

  class X {
public static void main(String [] args){
{//< --- start
int i;
} //< - ends
}
}

我知道方法之外的浮动块,但从未在内部尝试过。



这可能用于定义本地范围或其他内容。



Java中的方法内是否有浮动块?

解决方案

< blockquote>

是否有用?


是 - 限制局部变量的范围。


这是一个好主意吗?


可能存在争议(也可能会)。



亲阵营会说缩小变量范围从不会受到伤害。 con阵营会说,如果你在一个方法中使用它并且你的方法足够长以保证将变量的范围缩小到特定的部分,那么它可能表明你应该从不同的部分中制作单独的方法。



我个人使用它们,例如:

  public void doGet (
最后的HttpServletRequest请求,
最后的HttpServletResponse响应)
抛出IOException {
final PersistenceManager pm = PMF.get()。getPersistenceManager();

final List< ToDoListGaejdo> toDoLists;
{
final Query query = pm.newQuery(ToDoListGaejdo.class);
query.setOrdering(listName asc);
toDoLists =(List< ToDoListGaejdo>)query.execute();
}

final List< ToDoItemGaejdo>项;
{
final Query query = pm.newQuery(ToDoItemGaejdo.class);
query.setOrdering(listName asc,priority asc);
entries =(List< ToDoItemGaejdo>)query.execute();
}

final ServletOutputStream out = response.getOutputStream();

out.println(< head>);
out.println(< title> Debug View< / title>);
....


I didn't know methods could have floating blocks like this:

class X { 
    public static void main( String [] args ) {
        { //<--- start
            int i;
        } //<-- ends
    }
}

I was aware of floating blocks outside methods, but never tried them inside.

This could probably be used to define local scope or something.

Is there a use for floating blocks inside methods in Java?

解决方案

Is there a use?

Yes - to limit the scope of local variables.

Is it a good idea?

Probably debatable (and likely will be).

The "pro" camp will say it never hurts to narrow the scope of variable. The "con" camp will say that, if you use it in a method and your method is long enough to warrant narrowing the scope of variables to specific sections, then it is probably an indication that you should make separate methods out of the different sections.

Personally, I use them, e.g.:

public void doGet(
        final HttpServletRequest request,
        final HttpServletResponse response)
  throws IOException {
    final PersistenceManager pm = PMF.get().getPersistenceManager();

    final List<ToDoListGaejdo> toDoLists;
    {
        final Query query = pm.newQuery(ToDoListGaejdo.class);
        query.setOrdering("listName asc");
        toDoLists = (List<ToDoListGaejdo>) query.execute();
    }

    final List<ToDoItemGaejdo> entries;
    {
        final Query query = pm.newQuery(ToDoItemGaejdo.class);
        query.setOrdering("listName asc, priority asc");
        entries = (List<ToDoItemGaejdo>) query.execute();
    }

    final ServletOutputStream out = response.getOutputStream();

    out.println("<head>");
    out.println("  <title>Debug View</title>");
    ....

这篇关于在Java中的方法中是否使用了自由浮动块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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