1. What I would recommend
Even though it makes the function more verbose, for more than one argument, I think this is best — the example below is from Python —:
def my_function(
argument_one,
argument_two,
argument_three,
argument_four,
argument_five,
):
...
2. Why?
- Having each argument on one line makes it very simple to use
git diffs, since changing one variable will only show that change. If you have more than one argument on each line, it's gonna be more visually annoying later.
- Notice that the trailing comma after the last argument makes it easier to add or remove an argument later, while also conforming to the PEP 8's Trailing Comma Convention, and yielding a better
git diff later.
- One of the reasons I really dislike the "align the arguments with the opening parenthesis" paradigm is that it doesn't yield easily maintainable code.
- Kevlin Henney explains it is a bad practice in his ITT 2016 - Seven Ineffective Coding Habits of Many Programmers lecture (around 17:08).
- The major reason it is a bad practice is that if you change the name of the function (or if it is too long), you're going to have to re-edit the spacing on all the arguments' lines, which is not at all scalable, though it may be (sometimes) (subjectively) prettier.
- The other reason, closely related to the one immediately above, is about metaprogramming. If the codebase becomes too big, you will eventually find yourself needing to program changes to the code file itself, which might become hell if the spacing on arguments is different for each function.
- Most editors, once the parentheses are open and you press enter, will open a new line with a tab and shove the closing parenthesis to the next line, untabbed. So, formatting the code this way is very quick and kind of standardized. For instance, this formatting is very common in
JavaScript and Dart.
- Lastly, if you think having each argument is too unwieldy because your function might have a lot of arguments, I would say that you're compromising easy formatting of your code due to rare exceptions.
- Don't legislate by exceptions.
- If your function has a lot of arguments, you're probably doing something wrong. Break it into more (sub)functions and (sub)classes.
3. Anyway...
A good convention is better than a bad one, but it's much more important to enforce one than be unnecessarily picky about them.
Once you've decided to use a standard, share your decision with your colleagues and use an automated formatter — for example, Prettier is a popular choice for JavaScript in VS Code; and the Dart language has standardized one globally: dartfmt — to enforce it consistently, diminishing the need of manual editing.