Clean code refers to well-organized, easily understandable, and maintainable code. Now, let's delve into last part of specific principles that guide clean code writing:
Source Code Structure (G)
- Separate concepts vertically.
- Vertically dense displays for related code.
- Define variables close to their usage.
- Define closely related functions near each other.
- Functions performing similar tasks should be in close proximity.
- Arrange functions in a downward flow.
- Keep code lines short.
- Avoid horizontal alignment (alignment with the line above or below).
- Use spaces to keep related things close and unrelated things distant.
- Do not disrupt the indents created by the code.
# Separate concepts vertically
class User:
def __init__(self, name, email):
self.name = name
self.email = email
# Display closely related code vertically
class UserManager:
def __init__(self):
self.users = []
def add_user(self, user):
self.users.append(user)
# Define variables close to their usage
total_price = calculate_total_price(product_price, quantity) # Good
# Avoid defining variables far from their usage
total_price = 0 # Bad
# Place related functions close to each other
def process_data(data):
preprocess(data)
analyze(data)
# Similar functions should be close to each other
def calculate_area_circle(radius):
pass
def calculate_area_square(side_length):
pass
# Functions should flow downwards
def step_one():
pass
def step_two():
pass
# Keep code lines short
result = perform_complex_calculation(data) # Good
result = perform_a_very_complex_calculation_that_does_a_lot_of_things(data) # Bad
# Avoid horizontal alignment (aligning with the line above or below)
first_name = "John" # Good
last_name = "Doe" # Bad
# Use spacing to keep related things close, unrelated things distant
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def print_details(self):
print(f"Name: {self.name}, Email: {self.email}")
# Do not disrupt the indentation created by the code structure
if condition:
do_something()
do_another_thing()
Objects and Data Structures (H)
- Hide the internal structure of the code.
- Prefer ready-made collection structures provided by programming languages.
- Avoid hybrid structures.
- Be as small as possible.
- Do one thing.
- Work with a small number of variables.
- The base class should know nothing about its derivatives.
- Having several simple functions is better than shaping them based on desired behavior by passing parameters to a single function.
- Avoid static methods.
# Hide the internal structure of the code
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# Prefer language-provided collection structures for data
user_list = [] # Good
user_dict = {} # Good
# Avoid hybrid structures
# Use a clear and small structure
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Work with a small number of variables
x, y, z = 1, 2, 3 # Good
coordinate1, coordinate2, coordinate3 = 1, 2, 3 # Bad
# Basic class should not know about its derived classes
class Animal:
def make_sound(self):
pass
# Favor having many simple functions over passing parameters to shape behavior
def calculate_area_circle(radius):
pass
def calculate_area_square(side_length):
pass
# Avoid static methods
class MathOperations:
@staticmethod
def add(a, b):
return a + b # Bad
Tests (K)
- Have one assert per test.
- Tests should be readable.
- Tests should run quickly.
- Tests should be independent.
- Tests should be repeatable.
# Use one assert per test
def test_calculate_total_price():
assert calculate_total_price(10, 2) == 20
# Make tests readable
def test_user_manager_add_user():
user_manager = UserManager()
user_manager.add_user(User("John", "john@example.com"))
assert len(user_manager.users) == 1
# Ensure tests run quickly
# Ensure tests are independent
# Ensure tests are repeatable
These examples showcase how a professional programmer might adhere to the Clean Code principles related to source code structure, objects and data structures, and testing in Python. The focus is on creating code that is readable, maintainable, and follows best practices.
If you need further information or have specific questions, feel free to ask! Tahsin Soyak tahsinsoyakk@gmail.com
Top comments (0)