I've never really seen examples of anonymous blocks being used like this (not involving conditionals, a try
block for a transaction, etc) 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 if it actually really benefited practically from a genuine SE standpoint from the anonymous blocks. 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.
As an example, if you are trying to do this to reuse a variable named count
, then it suggests you're counting two disparate things. If the variable name is going to be as short as count
, then it makes sense to me to tie it to the context of the function, which could potentially just be counting one type of thing. Then you can instantly look at the function's name and/or documentation, see count
, and instantly know what it means in the context of what the function is doing without analyzing all the code. I don't often find a good argument for a function to count two different things reusing the same variable name in ways that make anonymous scopes/blocks so appealing compared to the alternatives. That's not so suggest that all functions have to count only one thing. I'm saying I see little practical engineering benefit to a function reusing the same variable name to count two or more things and using anonymous blocks to limit scope of each individual count. If the function is simple and clear, it's not the end of the world to have two differently named count variables with the first one possibly having a few more lines of scope visibility than ideally required. Such functions generally are not the source of errors lacking such anonymous blocks to reduce the minimal scope of its local variables even further.