0% found this document useful (0 votes)
61 views

Clean - Code - Check - List

The document discusses principles of writing clean code, including: 1) Clean code is readable, straightforward, and has clear intent without obscuring the designer's purpose. It has tests and meaningful names. 2) Advantages of clean code include better use of time, easier debugging, easy to test, and easier onboarding of new team members. 3) The document provides a checklist for writing clean code, covering general rules, design rules, understandability tips, naming conventions, functions guidelines, comments guidelines, source code structure, objects and data structures, and tests. It also discusses code smells to avoid.

Uploaded by

Hemak
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Clean - Code - Check - List

The document discusses principles of writing clean code, including: 1) Clean code is readable, straightforward, and has clear intent without obscuring the designer's purpose. It has tests and meaningful names. 2) Advantages of clean code include better use of time, easier debugging, easy to test, and easier onboarding of new team members. 3) The document provides a checklist for writing clean code, covering general rules, design rules, understandability tips, naming conventions, functions guidelines, comments guidelines, source code structure, objects and data structures, and tests. It also discusses code smells to avoid.

Uploaded by

Hemak
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 12

Pavankumar Clean Code

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."

-“Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategy

Advantages of Clean Code:

Better Use of Your Time

Easier Debugging

Easy to Test

You’ll Feel Good

1
Pavankumar Clean Code

Easier On-boarding of New Team Members

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

6. Avoid encodings. Don't append prefixes or type information.

## 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.

## Source code structure


1. Separate concepts vertically.
2. Related code should appear vertically dense.
3. Declare variables close to their usage.
4. Dependent functions should be close.
5. Similar functions should be close.
6. Place functions in the downward direction.
7. Keep lines short.
8. Don't use horizontal alignment.
9. Use white space to associate related things and disassociate weakly related.
10. Don't break indentation.

4
Pavankumar Clean Code

## Objects and data structures


1. Hide internal structure.
2. Prefer data structures.
3. Avoid hybrids structures (half object and half data).
4. Should be small.
5. Do one thing.
6. Small number of instance variables.
7. Base class should know nothing about their derivatives.
8. Better to have many functions than to pass some code into a function to select a
behavior.
9. Prefer non-static methods to static methods.

## 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.

Using Intention-Revealing Names


Name of a variable/function/class should convey the intent of it i.e., When
reading the name of a variable/function/class, everyone should understand the
same intent for which it is written.
D = 10
number_of_students_registered = 10

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.

Use appropriate names. Use plural in case of a group of objects. Use


suffixes like _dict, _list, etc. to properly convey the intent.
accounts_list = {"account_id": 1, "balance": 1000 ...}
user = User.objects.all()
fruit = ["apple", "banana" ...]

account_dict = {"account_id": 1, "balance": 1000 ...}


users = User.objects.all()
fruits = ["apple", "banana" ...]

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

XYZControllerForEfficientStringsHandling <- variation at ending


XYZControllerForEfficientStringsStorage

Make Meaningful Distinctions

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):

def sum(number_one, number_two): # intended


return number_one + number_two
def is_subset(subset_list, superset_list):

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

Use Pronounceable Names

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 = ...

Functions should be Small!


"The first rule of functions is that they should be small. The second rule of
functions is that they should be smaller than that."
Functions should be small: each function shouldn't cross 20 lines (with a
hard limit of 30 lines for exceptional cases). Each line shouldn't cross 80
characters

Blocks and Indenting

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

def register_user(name, email, age, gender):


if name == '':
raise InvalidNameException

if age < 18:


raise UserAgeShouldbeAbove18

if gender not in [Gender.MALE.value, Gender.FEMALE.value]:


raise InvalidGenderException

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."

def send(user, email_template=None, sms_template=None,


email=False, sms=False):
if email:
# send email logic
if sms:
# send sms logic

def send_emal(user, email_template):


# send email logic

def send_sms(user, sms_template):


# send sms logic

9
Pavankumar Clean Code

Encapsulate Conditionals

Extract functions that explain the intent of the conditional.

if (shouldBeDeleted(timer)) - is preferable to - if (timer.hasExpired() && !

timer.isRecurrent())

The expression in a conditional statement should be very simple to


understand. If it's becoming a complicated expression, create a function which
calculates the expression and use that function in the conditional statement.

def get_lucky_winners(users, no_of_winners):


selected_locations = []
filtered_winners = []
for user in users:
if user.age <= 30 and user.location in selected_locations
and user.gender = "Female" and user.name.startswith() = "A":
filtered_winners.append(user)

import random
random.shuffle(filtered_winners) # changes the order of list
to a random order
return filtered_winners[:no_of_winners]

def get_lucky_winners(users, no_of_winners):


selected_locations = []
filtered_winners = []
for user in users:
if is_lucky_winner(user):
filtered_winners.append(user)

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

Avoid Negative Conditionals

if (buffer.shouldCompact()) - is preferable to - if (!buffer.shouldNotCompact())

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

Extract Try/Catch Blocks

Each one of the try-catch block should have a maximum of 4 lines. If it is


getting longer, extract the bodies of the try and catch blocks out into functions of
their own.

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

You might also like