On Tuesday, 24 October 2017 at 20:36:00 UTC, H. S. Teoh wrote:
On Tue, Oct 24, 2017 at 01:22:41PM -0600, Jonathan M Davis via Digitalmars-d wrote: [...]
Personally, I don't want them in D. If you have enough arguments that it matters, then the function probably has too many parameters or too many similar parameters.

If a function has too many parameters, or only a small subset of parameters need to be something other than some default value, or the set of parameters may change frequently, then my default approach is to abstract the parameters into a struct:

        struct OutputArgs {
                string filename;
                int width = 300;
                int height = 300;
                string fontDir = "/usr/share/local/fonts/arial.ttf";
                int fontSize = 12;
                Color background = Color.black;
                Color foreground = Color.white;
                bool antiAlias = true;
        }

        void generateOutput(OutputArgs args) { ... }

        void main() {
                // Setup function arguments.
                // N.B.: only .filename needs to be explicitly set.
                OutputArgs args;
                args.filename = "/tmp/output.png";

                // Call function with mostly default arguments.
                generateOutput(args);
        }

This approach means that if you ever need to add more parameters to OutputArgs, as long as the default value is compatible with previous behaviour, you won't have to change existing code. Also, the caller can set the arguments in any order without needing to memorize which parameter is in which position.
...

good alternative, I already forgot about the power of structs after Java.

Reply via email to