How to optionally pass an optional parameter?

Is there a simpler (and cleaner) way to pass an optional parameter from one function to another than 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 that I really want to name:

 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 do not get a combinatorial explosion for positional optional parameters, but I would still like to have something simpler than a lot of if-else.

I have a code that uses the solution proposed in the first answer (propagating default values ​​for named optional parameters, but I lose the ability to check if the value was provided by the initial subscriber).

+4
source share
2 answers

I have been burned this corner of Darth several times. My current guidelines, which I recommend everyone to accept:

  • Do not use the default values. Instead, use the implicit default value of null and check this in the function body. Specify which value will be used if null passed.
  • Don't use a test argument operator ? . Instead, just check for null .

This does not result in passing the argument and explicitly passes null exactly equivalent, which means you can always redirect by explicitly passing the argument.

So the above would be:

 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 template is cleaner and easier to maintain that uses the default values, and avoids the unpleasant combinatorial explosion when you need to move forward. It also avoids duplicating default values ​​when overriding a method or implementing an interface with additional parameters.

However, there is one corner of the Dart world where this does not work: DOM. The operator ? was designed specifically to eliminate the fact that there are some JavaScript DOM methods where the null transmission is different from the undefined transmission (i.e., it does not skip anything).

If you are trying to forward the DOM method to Dart, which uses ? then you have to deal with a combinatorial explosion. I personally hope that we can just fix these APIs.

But if you just write your own Dart code, I really recommend that you completely abandon the default values ​​and ? . Your users will thank you for this.

+6
source

Can positional parameters be the four options for your business?

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

Since you still call optional2 with default parameters, this seems like a good substitute, not knowing that the purpose of the function

0
source

All Articles