Coding Style – Using Named Arguments for Readability

coding-style

A long time ago I programmed a lot in ADA, and it was normal to name arguments when invoking a function – SomeObject.DoSomething(SomeParameterName => someValue);

Now that C# supports named arguments, I'm thinking about reverting to this habit in situations where it might not be obvious what an argument means.

You might argue that it should always be obvious what an argument means, but if you have a boolean argument, and callers are passing in "true" or "false" then qualifying the value with the name makes the call site more readable.

contentFetcher.DownloadNote(note, manual : true);

I guess I could create Enums instead of using true or false (Manual, Automatic in this case).

What do you think about occasionally using named arguments to make code easier to read?

Best Answer

This was suggested in the development of C++, and Stroustrup discusses it in his "Design and Evolution of C++", pages 153 and following. The proposal was well-formed, and drew on prior experience with Ada. It wasn't adopted.

The biggest reason was that nobody wanted to encourage functions with large numbers of parameters. Each additional feature in a language costs something, and there was no desire to add a feature to make it easier to write bad programs.

It also raised questions of what the canonical parameter names were, particularly in the usual header and code file convention. Some organizations had longer and more descriptive parameter names in the .h file, and shorter and easier to type names in the .cpp file (substitute file suffixes as desired). Requiring that these be the same would be an additional cost on compilation, and getting names mixed up between source files could cause subtle bugs.

It can also be handled by using objects rather than function calls. Instead of a GetWindow call with a dozen parameters, create a Window class with a dozen private variables, and add setters as necessary. By chaining the setters, it's possible to write something like my_window.SetColor(green).SetBorder(true).SetBorderSize(3);. It's also possible to have different functions with different defaults that call the function that actually does the work.

If you're just worried about the documentation effect of contentFetcher.DownloadNote(note, manual : true);, you can always write something like contentFetcher.DownloadNote(note, /* manual */ true);, so it's not even very helpful in documentation.

Related Topic