Named blocks to limit variable scope: good idea?

2019-01-16 11:25发布

For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default.

I've used this to good effect, I think, in my own code. But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here:

  1. avoid doing it, or
  2. promote it, with the hope that it will become an idiom.

Example (within a larger method):

final Date nextTuesday;
initNextTuesday: {
    GregorianCalendar cal = new GregorianCalendar();
    ... // About 5-10 lines of setting the calendar fields
    nextTuesday = cal.getTime();
}

Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.

Some people have commented that you don't actually need to name the block. While that's true, a raw block looks even more like a bug, as the intent is unclear. Furthermore, naming something encourages you to think about the intention of the block. The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.

Many people have commented that it's best to go straight to small methods. I agree that this should be your first instinct. However, there may be several mitigating factors:

  • To even consider a named block, the code should be short, one-off code that will never be called elsewhere.
  • A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters. This is especially true when a class is in flux, and the inputs are likely to change from version to version.
  • Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established. A named block is easier (psychologically, at least) to throw away.
  • Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.

Advantages of using the named scope:

  1. Can't accidentally reuse temporary variables
  2. Limited scope gives garbage collector and JIT compiler more information about programmer intent
  3. Block name provides a comment on a block of code, which I find more readable than open-ended comments
  4. Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.

Disadvantages:

Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name. (Just like Eclipse does.) And getting something to become idiomatic is an uphill battle.

It can be used as an excuse for bad programming habits, such as:

  • Making huge, monolithic methods where several small methods would be more legible.
  • Layers of indentation too deep to read easily.

Note: I've edited this question extensively, based on some thoughtful responses. Thanks!

14条回答
淡お忘
2楼-- · 2019-01-16 11:29

If you have 5-10 lines of code that can safely be put into a block like that, the same code could just as well be extracted into a method.

This might seem like it's only a semantic difference, but at least with extracting into a method then you would gain the benefit of the ability of re-use.

查看更多
萌系小妹纸
3楼-- · 2019-01-16 11:30

It's a good technique in my book. Managing large numbers of throwaway methods is evil and the reasons you're providing for naming the blocks are good.

What does the generated bytecode look like? That'd be my only hesitation. I suspect it strips away the block name and might even benefit from greater optimizations. But you'd have to check.

查看更多
爷、活的狠高调
4楼-- · 2019-01-16 11:30

I have done this in some of my c#. I didn't know you could name the blocks though, I'll have to try that see if it works in c# too.

I think the scope block can be a nice idea, because you can encapsulate code specific to something within a block of code, where you might not want to split it out into its own function.

As for the disadvantage of nesting them, I see that as more of a fault of a programmer not of scope blocks themselves.

查看更多
我命由我不由天
5楼-- · 2019-01-16 11:30

I love the idea of using block to limit var scope. So many times I was confused by short-lived vars given large scope which should go away immediately after use. Long method + many non-final vars make it difficult to reason about the coder's intention, especially when comments are rare. Considering much of the logic I see in a method were like below

Type foo(args..){
    declare ret
    ...
    make temp vars to add information on ret
    ...

    make some more temp vars to add info on ret. not much related to above code. but previously declared vars are still alive
    ...


    return ret
}

if vars can have smaller scope than the entire method body, I can quickly forget most of them (good thing).

Also I agree that too many or too few private things leads to spaghetti code.

Actually what I was looking for was something like nested method in functional languages, and seems its cousin in Java is a {BLOCK} (inner class and labmda expression are not for this..).

However, I would prefer to use a unnamed block since this may be misleading to people trying to find the reference to the label, plus I can explain better with commented block.

For using a private method, I would consider it as the next step of using blocks.

查看更多
Ridiculous、
6楼-- · 2019-01-16 11:31

Sometimes I use unnamed blocks to isolate mutable things needed to prepare some immutable thing. Instead of having a label I put the Block under the immutable variable declaration.

final String example;
{
   final StringBuilder sb = new StringBuilder();
   for(int i = 0; i < 100; i++)
     sb.append(i);
   example = sb.toString();

}

When I find some other use for the block, or just think that it's in the way, I turn it into a method.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-16 11:32

I'd just go straight for refactoring into smaller methods. If a method is big enough that it needs breaking up like this, it really needs breaking up into multiple methods if at all possible.

While limiting scope is nice, this isn't really what named blocks are for. It's unidiomatic, which is very rarely a good thing.

查看更多
登录 后发表回答