DEV Community

Cover image for Clean Code: Definition and Principles - Part 3 (Last Part)
tahsinsoyak
tahsinsoyak

Posted on

Clean Code: Definition and Principles - Part 3 (Last Part)

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)

  1. Separate concepts vertically.
  2. Vertically dense displays for related code.
  3. Define variables close to their usage.
  4. Define closely related functions near each other.
  5. Functions performing similar tasks should be in close proximity.
  6. Arrange functions in a downward flow.
  7. Keep code lines short.
  8. Avoid horizontal alignment (alignment with the line above or below).
  9. Use spaces to keep related things close and unrelated things distant.
  10. 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()

Enter fullscreen mode Exit fullscreen mode

Objects and Data Structures (H)

  1. Hide the internal structure of the code.
  2. Prefer ready-made collection structures provided by programming languages.
  3. Avoid hybrid structures.
  4. Be as small as possible.
  5. Do one thing.
  6. Work with a small number of variables.
  7. The base class should know nothing about its derivatives.
  8. Having several simple functions is better than shaping them based on desired behavior by passing parameters to a single function.
  9. 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
Enter fullscreen mode Exit fullscreen mode

Tests (K)

  1. Have one assert per test.
  2. Tests should be readable.
  3. Tests should run quickly.
  4. Tests should be independent.
  5. 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

Enter fullscreen mode Exit fullscreen mode

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)