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

Introduction To Clean Code

Uploaded by

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

Introduction To Clean Code

Uploaded by

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

Unit 1: Introduction to Clean Coding

Clean coding is essential for writing code that is easy to understand, maintain, and extend. This
unit explains the fundamentals of clean code and contrasts it with bad code. It covers naming
conventions, function design, error handling, and best practices followed by experienced
programmers.

1.1 What is Bad Code?

Bad code is code that works but is hard to read, maintain, and modify. It often results from
shortcuts, lack of clarity, poor design, and ignorance of coding standards.

Characteristics of Bad Code:

 Ambiguous Naming: Variables and functions have unclear names (e.g., x, temp,
doSomething()).
 Large Functions: Functions perform too many tasks, making the code complex and
error-prone.
 Hard to Understand: Developers need to spend extra time figuring out the logic.
 Error Handling is Poor: The code does not properly handle exceptions or errors.

Example of Bad Code:

python
Copy code
def f(l):
for i in range(len(l)):
if l[i] % 2 == 0:
print(l[i])

1.2 What is Clean Code?

Clean code, on the other hand, is code that is easy to read, maintain, and extend. It follows a set
of principles that make it readable and simple for others to understand and work with.

Characteristics of Clean Code:

 Meaningful Names: Variables and functions are named clearly to indicate their purpose.
 Small Functions: Functions are focused on one task, making them easier to maintain and
test.
 Consistent Structure: The code follows a logical structure and consistent indentation.
 Error Handling: Proper error handling and separation of concerns are implemented.

Example of Clean Code:


python
Copy code
def print_even_numbers(numbers):
"""Prints even numbers from a list."""
for number in numbers:
if number % 2 == 0:
print(number)

1.3 Purpose of Clean Code

The purpose of clean code is to:

 Improve Readability: The code should be self-explanatory and easy to follow.


 Increase Maintainability: Clean code can be easily modified or extended without
introducing bugs.
 Reduce Complexity: Avoid unnecessary complexity in functions and structures.

Thoughts of Experienced Programmers:

 "Code is more often read than written." – Robert C. Martin


o Code should be optimized for reading, as it will be read many times during
debugging and maintenance.
 "Leave the campground cleaner than you found it." – Robert C. Martin
o When modifying code, make sure to leave it in a better state than before,
improving clarity and structure where possible.

1.4 Meaningful Names

Meaningful names are essential for writing clean code. Every variable, function, and class should
have a name that clearly indicates its purpose. This avoids confusion and reduces the need for
comments.

Rules for Meaningful Names:

 Descriptive: The name should reflect the entity’s purpose.


 Unambiguous: Names should not be vague or misleading.
 Consistent: Follow naming conventions, such as using verbs for function names.

Example:

python
Copy code
# Bad Example:
def c(n):
return n * n
# Good Example:
def calculate_square(number):
return number * number

1.5 Intention-Revealing Names

Names should reveal the intention behind the code. The reader should be able to understand the
purpose of the variable or function by simply looking at its name.

Example:

python
Copy code
# Bad Example:
def calc(d):
return d * 2

# Good Example:
def calculate_double_value(distance):
return distance * 2

In the good example, the function name and argument are descriptive, clearly showing the
function's intention.

1.6 Make Meaningful Distinctions

Avoid using names that are too similar or indistinguishable from one another. Each name should
highlight a unique concept or role in the program.

Example:

python
Copy code
# Bad Example:
get_value() and get_val()

# Good Example:
get_user_id() and get_user_profile()

In the good example, the functions are clearly distinguished by their purpose, avoiding
confusion.

1.7 Use Pronounceable Names


Names should be easy to read and pronounce, especially in a team environment where
developers discuss the code verbally.

Example:

python
Copy code
# Bad Example:
def calc_xyzlmn(pqr):

# Good Example:
def calculate_distance_in_miles(kilometers):

Pronounceable names facilitate discussions and code reviews.

1.8 Avoid Encodings and Mental Mappings

Avoid the use of encodings or abbreviations that require developers to map them mentally. This
practice adds unnecessary cognitive load.

Example:

python
Copy code
# Bad Example:
p = 3.14

# Good Example:
PI = 3.14

In the bad example, p requires mental mapping, whereas PI is self-explanatory.

1.9 Difference Between a Smart and Professional Programmer

 Smart Programmers: Write complex code that may be clever but hard to understand.
 Professional Programmers: Write simple, clear code that solves problems efficiently
and is easy to maintain.

The difference lies in the approach: professional programmers prioritize readability and
simplicity over showing off cleverness.

1.10 Class and Method Names


Class and method names should follow standard naming conventions. Class names are typically
nouns, while method names are verbs.

Example:

python
Copy code
# Class names as nouns:
class Car:
...

# Method names as verbs:


def start_engine(self):
...

1.11 Functions: Function Size Matters

Functions should be small, focused, and do only one thing. A small function is easier to test,
debug, and modify.

Guidelines for Function Size:

 Single Responsibility: The function should perform one task only.


 Keep It Short: Aim for functions that fit within 10-20 lines of code.

Example:

python
Copy code
# Bad Example:
def process_data(data):
# Does fetching, validating, and processing data in one function.

# Good Example:
def fetch_data():
...
def validate_data(data):
...
def process_data(data):
...

1.12 Blocks and Indenting

Indentation is crucial in Python, where code structure is defined by indentation levels. Proper
indenting makes the code more readable and helps to avoid errors.

Example:

python
Copy code
def example_function():
if condition:
print("Properly indented code.")

1.13 Function Arguments

Function arguments should be limited to a reasonable number (ideally no more than 3 or 4).
When functions require many arguments, consider grouping them into objects or lists.

Example:

python
Copy code
# Too many arguments:
def create_user(name, age, address, phone, email):
...

# Grouping arguments into an object:


def create_user(user):
...

1.14 Command-Query Separation

A function should either perform a command (i.e., change something) or return a query (i.e.,
retrieve information), but not both.

Example:

python
Copy code
# Violates command-query separation:
def check_and_print_even(number):
if number % 2 == 0:
print(f"{number} is even")
return True

# Follows command-query separation:


def is_even(number):
return number % 2 == 0

def print_even(number):
if is_even(number):
print(f"{number} is even")

1.15 Prefer Exceptions to Returning Error Codes

Instead of returning error codes to signal failure, it is better to raise exceptions, which are more
informative and easier to handle.
Example:

python
Copy code
# Returning error codes (bad):
def divide(a, b):
if b == 0:
return -1
return a / b

# Using exceptions (good):


def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b

1.16 Extract Try/Catch Blocks

Move error-handling code out of the core logic to keep the main functionality clear.

Example:

python
Copy code
# Bad Example:
def read_file(filename):
try:
file = open(filename, 'r')
content = file.read()
file.close()
except Exception as e:
print(f"Error: {e}")

# Good Example:
def read_file(filename):
return open(filename, 'r').read()

def handle_error(error):
print(f"Error: {error}")

try:
content = read_file("file.txt")
except Exception as e:
handle_error(e)

1.17 Error Handling Is One Thing

Error handling should be treated as a separate responsibility from the core logic. This keeps
functions focused on their primary purpose and makes error handling more modular.

Example:
python
Copy code
def fetch_data_from_api():
try:
# Core logic
except Exception as error:
# Handle error separately

You might also like