Code Smell 19 - Optional Arguments

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Disguised as a friendly shortcut is another coupling smell.

Problems

  • Coupling

  • Unexpected results

  • Side effects

  • Ripple Effect

  • In languages with optional arguments but limited to basic types, we need to set a flag and add an accidental IF (another smell).

Solutions

  1. Make arguments explicit.
  2. All function calls must have same arity.
  3. Use Named Parameters if your language supports them.

Sample Code

Wrong

Detection

Detection is easy if language supports optional arguments.

Tags

  • Optional

  • Laziness

Conclusion

Be explicit. Favor readability over shorter (and more coupled) function call.

More info


The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.

Seymour Cray


This article is part of the CodeSmell Series.

Comments (2)

Rodion Borisov's photo

I fail to see a problem. All it couples to are sensible defaults, which actually tend to solve such side effect as tons of unnecessary boilerplate code.

Yes, methods are used not with full list of arguments, but if their types don't overlap, then it's got to be right. (Another good example would be named parameters in Python - you avoid binding to the order of arguments and call out parameters' names and values instead, which is way more specific.) Again, optionals save the hassle of calls being too over the defaults that might change with the environment.

Maxi Contieri's photo

Named parameters and optionals are great.

But you are still coupled to defaults (implementative), when you should just couple to declarative

I’ll add this to the article. Thank you so much