args icon indicating copy to clipboard operation
args copied to clipboard

args: deprecate `callback` and replace with `parse`

Open DartBot opened this issue 9 years ago • 1 comments

<img src="https://avatars.githubusercontent.com/u/444270?v=3" align="left" width="96" height="96"hspace="10"> Issue by seaneagan Originally opened as dart-lang/sdk#20079


callback doesn't seem to provide much benefit over just accessing the value from the results. If it could perform validation and parsing into other types (e.g. int) and throw nice error messages, I think it would be more useful. Example:

Old:

  parser.addOption('x', callback: (x) => print('x: $x'));   parser.addOption('y', callback: (y) => print('y: $y'));

  var results = parser.parse(arguments);

  var x = int.parse(results['x']);   var y = int.parse(results['y']);   print('x + y: ${x + y}');

New:

  parser.addOption('x', parse: int.parse);   parser.addOption('y', parse: int.parse);

  var results = parser.parse(arguments);

  int x = results['x'];   int y = results['y'];   print('x: $x');   print('y: $y');   print('x + y: ${x + y}');

If --x or --y are not formatted as integers, this would lead to something like:

  foo.dart: --foo value "xyz" is invalid: FormatException: ...

Of course you could throw whatever error you want, for example you could use matchers:

  parser.addOption('foo', parse: (s) {     var matchState = {};     if(!isNumeric.matches(s, matchState) {       throw isNumeric.describeMismatch(s, new StringDescription(), matchState);     }     return num.parse(s);   });

DartBot avatar Jun 05 '15 22:06 DartBot