# Clean Code Best Practices
## Definition
**Clean code is code that is easy to understand and easy to change.**
It is easy to understand the execution flow of the entire application.
It is easy to understand how the different objects collaborate with each other.
It is easy to understand the role and responsibility of each class.
It is easy to understand what each method does.
It is easy to understand what is the purpose of each expression and variable.
## Motivation
Clean code enables us to keep our software products adaptable and maintainable.
It allows us to make changes with confidence and estimate the impact of these changes.
Clean code makes us a reliable and trustworthy partner for our stakeholders.
## Guide Lines
### Boy Scout Rule
> Leave the campground cleaner than you found it
### Write code for humans
Your code is directed at your future self and your co-workers, not the machine.
### K.I.S.S. - Keep it simple stupid
A simpler solution is better than a complex one because simple solutions are easier to maintain.
This includes increased readability, understandability, and changeability.
Furthermore writing simple code is less error prone.
### Y.A.G.N.I - You ain't gonna need it
When faced with a decision what to implement, implement only the features that are necessary at the moment.
Features which are regarded as useful but don't seem necessary at the moment are better left for the time when they are deemed necessary.
That way the necessary features will be developed faster.
In addition no time will be lost on creating and maintaining features that never become necessary.
### Avoid premature optimization
The performance of readable and maintainable code will be sufficient most of the time.
Optimizations that harm the readability should only be made after severe bottlenecks have been doubtlessly identified and been considered mission critical.
### The Great Refactoring in the Sky
If you find yourself thinking: 'We can clean that up later' - Try to replace the word 'later' with 'never'.
The reality of software development is that tasks move out of focus quickly and this clean up work gets forgotten or overruled by new interests.
Most of the time if you do not clean it up now it will never be cleaned.
### Naming
> Say what you mean. Mean what you say.
#### Use meaningful and pronouncable names
This makes the code searchable and reveals its intend.
Pronouncable names are easier for the human mind to process and facilitate collaboration when referencing these names.
Meaningful names are more valuable than a few saved keystrokes.
```
// DON'T
let d;
const ages = arr.map((i) => i.age);
// DO
let daysSinceModification;
const agesOfUsers = users.map((user) => user.age);
```
#### Use the same vocabulary for the same context
```
// DON'T
getUserInfo();
getClientData();
getCustomerRecord();
// DO
getUser();
```
#### Avoid unneeded context
```
// DON'T
const car = {
carColor: 'red',
startCar() {},
};
throw new AccessViolationException;
// DO
const car = {
color: 'red',
start() {},
};
throw new AccessViolation;
```
#### Avoid disinformation
```
// DON'T
// the getUser() function will actually create new entities
function getUser(id) {
const user = userRepository.get(id);
if (!user) {
user = userRepository.create(id);
}
return user;
}
// DO
// the function name makes it clear that new entities may be created
function getOrCreateUser(id) {
const user = userRepository.get(id);
if (!user) {
user = userRepository.create(id);
}
return user;
}
```
#### Classes
Classes and objects should have a noun like `Customer`, `Account` etc.
#### Methods
Methods should have verb or verb phrases like `postPayment`, `deleteAccount` etc.
### Functions
> First rule: functions should be small
> Second rule: functions should be smaller than that
#### One or Two arguments
Limiting the number of arguments to 1-2 makes the function easier to test.
Having more arguments leads to an combinatorial explosion of possible test cases and takes a lot of conceptual power.
#### Do one thing
A function should only do the thing its name indicates.
```
// DON'T
function getUser(id) {
const user = userRepository.get(id);
user.isActiveUser = true;
UserCache.add(id, user);
return user;
}
```
#### One level of Abstraction per Function
Function that traverse multiple layers of abstraction are hard to test and reason about.
```
// DON'T
function storeUser(user) {
// code to serialize the user
// code to get a file handle
// code to write the serialized user to disk
}
// DO
function serializeUser(user) {
// code to serialize user
};
function writeSerializedData(data) {
// code to get a file handle
// code to write serialized data
}
function storeUser(user) {
const serializedUserData = serializeUser(user);
writeSerializedData(serializedUserData);
}
```
#### Avoid flag arguments
Having a flag argument directly indicates that this function is not only doing one thing.
Split them into separate functions.
```
// DON'T
function save(toTempFile) {
if (toTempFile) {
writeToDisk(tempPath);
} else {
writeToDisk(defaultPath);
}
}
// DO
function save() {
writeToDisk(defaultPath);
}
function saveToTempFile() {
writeToDisk(tempPath);
}
```
#### Argument objects
When a function seems to need more than two or three arguments it is likely that some of these arguments ought to be wrapped into a class of their own.
```
// DON'T
function makeCircle(x, y, radius) { }
// DO
function makeCircle(point, radius) { }
```
#### Have no side effects
A function should only do what it promises and not execute hidden functionality.
```
// DON'T
function checkPassword(userName, password) {
const passwordHash = getUserPasswordHash(userName);
if (hash(password) === passwordHash) {
// side effect
Session.initialize();
return true;
}
return false;
}
```
#### Command Query Separation
Functions should either do something or answer something, but not both.
```
// DON'T
// does 'set':
// - check wether username is set?
// - return true when the 'username' equals 'foo'
// - return true when username was set successfully?
if (set('username', 'foo')) { ... }
// DO
if (attributeExists('username')) {
setAttribute('username', 'foo');
}
```
### Comments
#### Explain yourself in code
When you feel the need to explain your code in comments the code should probably be refactored to be clearer.
```
// DON'T
// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))
// DO
const moduleDependees = smodule.getDependSubsystems();
const ourSubSystem = subSysMod.getSubSystem();
if (moduleDependees.contains(ourSubSystem))
```
#### Avoid Commented-Out code
Others who see that commented-out code won’t have the courage to delete it.
They’ll think it is there for a reason and is too important to delete.
So commented-out code gathers.
#### Avoid Noise comments
```
// get the user data
function getUserData() {}
```
#### Good comments
- Warning of consequences
- Provision of additional context
- TODO comments
### Formatting
Use automatic tooling like `eslint` and/or `prettier`.
#### Vertical density
Related code should be vertically dense.
Unrelated code should be vertically separated.
### Objects and Data structures
#### Law of Demeter
> A module should not know about the innards of the objects it manipulates.
If this is not the case the object encapsulation is non-existant.
#### Do not mix objects and data structures
Objects expose behavior and hide data.
This makes it easy to add new kinds of objects without changing existing behaviors.
It also makes it hard to add new behaviors to existing objects.
Data structures expose data and have no significant behavior.
This makes it easy to add new behaviors for existing data structures but makes it hard to add new data structures to existing functions.
### Unit Tests
#### Basic TDD process
1) Write the test that defines the behavior
2) Write the code to make the test succeed in any shape or form. Do not focus on style here.
3) Refactor the code until it is fit to be understood by other developers.
#### F.I.R.S.T. rules
**Fast**
Tests should be fast. They should run quickly. When tests run slow, you won’t want to run them frequently.
If you don’t run them frequently, you won’t find problems early enough to fix them easily.
You won’t feel as free to clean up the code.
Eventually the code will begin to rot.
**Independent**
Tests should not depend on each other. One test should not set up the conditions for the next test.
You should be able to run each test independently and run the tests in any order you like.
When tests depend on each other, then the first one to fail causes a cascade of downstream failures, making diagnosis difficult and hiding downstream defects.
**Repeatable**
Tests should be repeatable in any environment.
You should be able to run the tests in the production environment, in the QA environment, and on your laptop while riding home on the train without a network.
If your tests aren’t repeatable in any environment, then you’ll always have an excuse for why they fail.
You’ll also find yourself unable to run the tests when the environment isn’t available.
**Self-Validating**
The tests should have a boolean output. Either they pass or fail.
You should not have to read through a log file to tell whether the tests pass.
You should not have to manually compare two different text files to see whether the tests pass.
If the tests aren’t self-validating, then failure can become subjective and running the tests can require a long manual evaluation.
**Timely**
The tests need to be written in a timely fashion.
Unit tests should be written just before the production code that makes them pass.
If you write tests after the production code, then you may find the production code to be hard to test.
You may decide that some production code is too hard to test.
You may not design the production code to be testable.
## Additional references
### Books
[Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/)
[The Pragmatic Programmer](https://www.amazon.de/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/)
### Language specific Style Guides
[Clean Code JavaScript](https://github.com/ryanmcdermott/clean-code-javascript)
[Airbnb JavaScript](https://github.com/airbnb/javascript)
[Clean Code PHP](https://github.com/jupeter/clean-code-php)
### Videos
[Uncle Bob Martin - Expecting Professionalism](https://www.youtube.com/watch?v=BSaAMQVq01E)
[Uncle Bob Martin - The Principles of Clean Architecture](https://www.youtube.com/watch?v=o_TH-Y78tt4)