An Interest In:
Web News this Week
- March 22, 2024
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
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
Fail Fast principle violation
Readability
Solutions
Move your optional arguments last.
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 argumentbuildCar("Volvo")}} // Runtime error: Missing argument 2 in call to buildCar()
Right
<?function buildCar($model, $color = "Red", ){...}buildCar("Volvo")}} // Works as expected
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
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
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
Software Engineering Great Quotes
Maxi Contieri Dec 28 '20 13 min read
This article is part of the CodeSmell Series.
Original Link: https://dev.to/mcsee/code-smell-172-default-argument-values-not-last-1al7
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To