DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Code Smell 172 - Default Argument Values Not Last
Maxi Contieri ⭐⭐⭐
Maxi Contieri ⭐⭐⭐

Posted on • Originally published at maximilianocontieri.com

Code Smell 172 - Default Argument Values Not Last

Function signature should be error prune

TL;DR: Don't use Optional Arguments before mandatory ones. In fact: Don't use Optional Arguments at all

Problems

Solutions

  1. Move your optional arguments last.

  2. Avoid Optional Arguments.

Context

Optional Arguments are a code smell.

Defining optional arguments before mandatory ones is an error.

Sample Code

Wrong

<?

function buildCar($color = "red", $model){...}  
// First argument with optional argument

buildCar("Volvo")}}  
// Runtime error: Missing argument 2 in call to buildCar()
Enter fullscreen mode Exit fullscreen mode

Right

<?

function buildCar($model, $color = "Red", ){...}

buildCar("Volvo")}} 
// Works as expected
Enter fullscreen mode Exit fullscreen mode
def functionWithLastOptional(a, b, c='foo'):
    print(a)
    print(b)
    print(c)
functionWithLastOptional(1, 2)

def functionWithMiddleOptional(a, b='foo', c):
    print(a)
    print(b)
    print(c)
functionWithMiddleOptional(1, 2)

# SyntaxError: non-default argument follows default argument
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Many Linters can enforce this rule since we can derive it from function signature.

Also, many compilers directly forbid it.

Tags

  • Readability

Conclusion

Try to be strict when defining functions to avoid coupling.

Relations

More Info

Rule on Sonar Source

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Manuel Torres Garcia on Unsplash


Programs are meant to be read by humans and only incidentally for computers to execute.

Donald Knuth


This article is part of the CodeSmell Series.

Top comments (0)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.