dart-lang / core

This repository is home to core Dart packages.
https://pub.dev/publishers/dart.dev
BSD 3-Clause "New" or "Revised" License
17 stars 4 forks source link

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

Open DartBot opened 9 years ago

DartBot commented 9 years ago

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 commented 9 years ago

Comment by sethladd


Added Area-Pkg, Pkg-Args, Triaged labels.