# Code Smell 172 - Default Argument Values Not Last

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

# Problems

- [Fail Fast principle](https://maximilianocontieri.com/fail-fast) violation

- Readability

# Solutions

1. Move your optional arguments last.

2. Avoid [Optional Arguments](https://maximilianocontieri.com/code-smell-19-optional-arguments).

# Context

Optional Arguments are a code smell.

Defining optional arguments before mandatory ones is an error.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/ed058f746a6eefe2d303743cd82c6fb0)
```php
<?

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

buildCar("Volvo")}}  
// Runtime error: Missing argument 2 in call to buildCar()
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/a1cf6479f6b0820fb0843441b5ea7499)
```php
<?

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

buildCar("Volvo")}} 
// Works as expected
```

[Gist Url]: # (https://gist.github.com/mcsee/f70b209c640d706fdb0d87dacb7f2ee1)
```python
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

%[https://maximilianocontieri.com/code-smell-19-optional-arguments]

# More Info

%[https://maximilianocontieri.com/fail-fast]

[Rule on Sonar Source](https://rules.sonarsource.com/php/type/Code%20Smell/RSPEC-1788)

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Manuel Torres Garcia](https://unsplash.com/ja/@matoga) on [Unsplash](https://unsplash.com/s/photos/precipicio)
  
* * *

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

_Donald Knuth_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
