Description
Hello,
I have been using anonymous blocks to break up long procedural code that will not be reused anywhere. I ran into an interesting idea for a language feature that I think would be a great addition to Dart. I can imagine there being a lot of apathy towards this proposal due to procedural programming being seen as "old", but since all applications use procedural to some extent I think its worth considering.
Here is a function using anonymous blocks. Its not a shining example, but it gets us started! The nice thing about anonymous blocks is that they encapsulate the scope within steps in procedural code while preserving the order to the reader. Do this, then this, then this. All the code is there and easy to reason about. The problem is that these anonymous blocks perform shadowing and its not clear what variables from the parent scope are being used.
myFunction(){
final foo = "foo";
String bar;
{
final result = "$foo bar";
bar = result;
}
String baz;
{
final result = "$bar baz";
baz = result;
}
return baz;
}
Many people would rewrite this as below. Problem is, its not sequential, harder to understand (although so common many would argue this is not a consideration), and makes non-repetitive code very repetitive in a way that normally supports reuse but in this case reuse is not valued.
_generateBar(String foo){
final result = "$foo bar";
return result;
};
_generateBaz(String bar){
final result = "$bar baz";
return result;
};
myFunction(){
final foo = "foo";
final bar = _generateBar(String foo);
final baz = _generateBaz(String baz);
return baz;
}
Proposal: Allow strict scope for anonymous blocks.
Introduce a use
keyword that restricts the scope of an anonymous block to the variables provided to use
.
myFunction(){
final foo = "foo";
final bar = use foo {
final result = "$foo bar";
return result;
}
final baz = use bar {
final result = "$bar baz";
return result;
}
return baz;
}
An example with multiple arguments might be:
final a = "a";
final b = "b";
final c = use a, b {
return "$a $b";
}