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.
source share