Clean - Code - Check - List
Clean - Code - Check - List
Clean Code
“Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.”– Martin Fowler
Clean Code
"Clean code is simple and direct. Clean code reads like well-written prose. Clean
code never obscures the designer’s intent but rather is full of crisp abstractions and
straightforward lines of control."
- Grady Booch, author of Object Oriented Analysis and Design with Applications
"Clean code can be read, and enhanced by a developer other than its original author. It
has unit and acceptance tests. It has meaningful names. It provides one way rather than
many ways for doing one thing. It has minimal dependencies, which are explicitly defined,
and provides a clear and minimal API. Code should be literate since depending on the
language, not all necessary information can be expressed clearly in code alone."
Easier Debugging
Easy to Test
1
Pavankumar Clean Code
2
Pavankumar Clean Code
Check_List
## General rules
1. Follow standard conventions.
2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as
possible.
3. Boy scout rule. Leave the campground cleaner than you found it.
4. Always find the root cause. Always look for the root cause of a problem.
## Design rules
1. Keep configurable data at high levels.
2. Prefer polymorphism to if/else or switch/case.
3. Separate multi-threading code.
4. Prevent over-configurability.
5. Use dependency injection.
6. Follow the Law of Demeter. A class should know only its direct dependencies.
## Understandability tips
1. Be consistent. If you do something a certain way, do all similar things in the same way.
2. Use explanatory variables.
3. Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put
the processing for them in one place.
4. Prefer dedicated value objects to primitive type.
5. Avoid logical dependency. Don't write methods which works correctly depending on
something else in the same class.
6. Avoid negative conditionals.
## Names rules
1. Choose descriptive and unambiguous names.
2. Make meaningful distinctions.
3. Use pronounceable names.
4. Use searchable names.
5. Replace magic numbers with named constants.
3
Pavankumar Clean Code
## Functions rules
1. Small.
2. Do one thing.
3. Use descriptive names.
4. Prefer fewer arguments.
5. Have no side effects.
6. Don't use flag arguments. Split method into several independent methods that can be
called from the client without the flag.
## Comments rules
1. Always try to explain yourself in code.
2. Don't be redundant.
3. Don't add obvious noise.
4. Don't use closing brace comments.
5. Don't comment out code. Just remove.
6. Use as explanation of intent.
7. Use as clarification of code.
8. Use as warning of consequences.
4
Pavankumar Clean Code
## Tests
1. One assert per test.
2. Readable.
3. Fast.
4. Independent.
5. Repeatable.
## Code smells
1. Rigidity. The software is difficult to change. A small change causes a cascade of
subsequent changes.
2. Fragility. The software breaks in many places due to a single change.
3. Immobility. You cannot reuse parts of the code in other projects because of involved
risks and high effort.
4. Needless Complexity.
5. Needless Repetition.
6. Opacity. The code is hard to understand.
If a name requires a comment, then the name does not reveal its intent.
5
Pavankumar Clean Code
Choose a name that specifies what is being measured and the unit of that
measurement.
file_age = 10
file_age_in_days = 10
The name of a variable, function, or class, should answer all the big questions. It
should tell you
● Why it exists
● What it does
● How it is used
Avoid Disinformation
Programmers must avoid leaving false clues that hide the actual meaning
of the code.
6
Pavankumar Clean Code
For names which vary in small ways - Put the variation at the beginning or
ending to differentiate easily. This will help in avoiding common mistakes like
referring to wrong variables
XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings
Sometimes, when you can’t use the same name to refer to two different
things in the same scope, you might be tempted to change one name in an
arbitrary way
quiz = Quiz.objects.get(id=1)
kwiz = Quiz.objects.get(id=2)
django_quiz = Quiz.objects.get(id=1)
python_quiz = Quiz.objects.get(id=2)
You shouldn't create a variable named kar just because the name car was
used for something else.
def sum(number_one, number_two):
return number_one + number_two
def is_subset(list_one, list_two):
Don't use number-series naming (a1, a2, .. aN), unless they are intended.
Product product
Product_details Product_image_details
Product_info product_complete_details
Don't use noise words (ex: [data, info]) for distinction. Ex: Don't use
StudentInfo and StudentData as different class/variable names.
7
Pavankumar Clean Code
Make your variable names pronounceable Ex: There should not be variable
name like genymdhms (generation date, year, month, day, hour, minute, and
second)
genymdhms = ....
modymdhms = ....
generation_timestamp = ...
modified_timestamp = ...
The indent level of a function should not be greater than three. (it can be
four only in some exceptional cases)
def register_user(name, email, age, gender):
if name != '':
if age > 18:
if gender in [Gender.MALE.value, Gender.FEMALE.value]:
if email != '':
user = create_user()
...
else:
raise EmailAlreadyRegistered
else:
raise InvalidGenderException
else:
raise UserAgeShouldbeAbove18
else:
raise InvalidNameException
8
Pavankumar Clean Code
if email == '':
raise EmailAlreadyRegistered
user = create_user()
…
Blocks within if, else, while and for statements, should be a maximum of 4
lines. If it's getting longer, it should be changed to a function call.
Flag Arguments
"Don't use flag (boolean, enums, integers) arguments for functions. Flag
arguments loudly declare that the function does more than one thing. It is better
to have many functions than to pass a variable into a function to select the
behavior."
9
Pavankumar Clean Code
Encapsulate Conditionals
timer.isRecurrent())
import random
random.shuffle(filtered_winners) # changes the order of list
to a random order
return filtered_winners[:no_of_winners]
import random
random.shuffle(filtered_winners) # changes the order of list
to a random order
return filtered_winners[:no_of_winners]
def is_lucky_user(user):
age_condition = user.age <= 30
location_condition = user.location in selected_locations
gender_condition = user.gender = "Female"
name_condition = user.name.startswith() = "A"
return age_condition and location_condition and
gender_condition and name_condition
10
Pavankumar Clean Code
def filter_odd_numbers_from_list(numbers):
odd_numbers = []
for number in numbers:
if not is_not_odd_number(number):
odd_numbers.append(number)
return odd_numbers
def is_not_odd_number(number):
if number % 2 != 0:
return True
return False
Using not in conditional statements might be confusing sometimes.
def filter_odd_numbers_from_list(numbers):
odd_numbers = []
for number in numbers:
if is_odd_number(number):
odd_numbers.append(number)
return odd_numbers
def is_odd_number(number):
if number % 2 != 0:
return False
return True
(or)
def filter_odd_numbers_from_list(numbers):
odd_numbers = []
for number in numbers:
if is_odd_number(number):
odd_numbers.append(number)
return odd_numbers
def is_not_odd_number(number):
if number % 2 != 0:
return True
return False
def is_odd_number(number):
return not is_not_odd_number(number)
11
Pavankumar Clean Code
File length
File sizes should be typically 200 lines long (with a hard limit of 350 for
exceptional cases)
Code is clean if it can be understood easily – by everyone on the team. Clean code can be read
and enhanced by a developer other than its original author. With understandability comes
readability, changeability, extensibility and maintainability.
_____________________________________
12