13

Is there an easier (and cleaner) way to pass an optional parameter from one function to another than doing this:

void optional1({num x, num y}) {
  if (?x && ?y) {
    optional2(x: x, y: y);
  } else if (?x) {
    optional2(x: x);
  } else if (?y) {
    optional2(y: y);
  } else {
    optional2();
  }
}

void optional2({num x : 1, num y : 1}) {
   ...
}

The one I actually want to call is:

void drawImage(canvas_OR_image_OR_video, num sx_OR_x, num sy_OR_y, [num sw_OR_width, num height_OR_sh, num dx, num dy, num dw, num dh])

At least I don't get a combinatorial explosion for positional optional parameters but I'd still like to have something simpler than lot's of if-else.

I have some code that uses the solution proposed in the first answer (propagating default values of named optional parameters, but I lose the ability to check whether or not the value was provided by the initial caller).

4

2 回答 2

12

I've been burned by this corner of Dart several times. My current guidelines, which I encourage anyone to adopt are:

  1. Do not use default values. Instead, use the implicit default of null and check for that in the body of the function. Document what value will be used if null is passed.
  2. Do not use the ? argument test operator. Instead, just test for null.

This makes not passing an argument and explicitly passing null exactly equivalent, which means you can always forward by explicitly passing an argument.

So the above would become:

void optional1({num x, num y}) {
  optional2(x: x, y: y);
}

/// [x] and [y] default to `1` if not passed.
void optional2({num x, num y}) {
   if (x == null) x = 1;
   if (y == null) y = 1;
   ...
}

I think this pattern is cleaner and easier to maintain that using default values and avoids the nasty combinatorial explosion when you need forward. It also avoids duplicating default values when you override a method or implement an interface with optional parameters.

However, there is one corner of the Dart world where this doesn't work: the DOM. The ? operator was designed specifically to address the fact that there are some JavaScript DOM methods where passing null is different from passing undefined (i.e. not passing anything).

If you're trying to forward to a DOM method in Dart that internally uses ? then you will have to deal with the combinatorial explosion. I personally hope we can just fix those APIs.

But if you're just writing your own Dart code, I really encourage you to avoid default values and ? entirely. Your users will thank you for it.

于 2013-02-01T19:08:14.837 回答
0

Would positional paremeters be an option four your case?

void optional([num x = 1, num y = 1]) {


}

Since you call optional2 with default parameters anyway, this seems like a good replacement without knowing, what the purpose of the function is

于 2013-01-31T16:00:39.160 回答