Skip to main content
1 of 17
user avatar
user avatar

In my humble opinion, it's generally something to avoid largely for production code because you're generally not tempted to do it except in sporadic functions that perform disparate tasks. I tend to do it in some scrap code used to test things, but find no temptation to do it in production code where I've put some thought in advance as to what each function should do, since then the function will naturally have a very limited scope with respect to its local state.

If I feel tempted to reach for it, I see it as a sign to create new functions instead. Of course you have the benefit of allowing resources to potentially be collected/destroyed earlier, but such is the same case with reducing a variable's scope in general which generally doesn't require reaching for anonymous blocks.

I've never really seen examples of blocks being used like this to reduce scope in a meaningful way in a function which didn't beg the question of why it couldn't be divided further into simpler functions with reduced scopes. It's usually eclectic code that's doing a bunch of loosely related or very unrelated things where we're most tempted to reach for this.

user204677