Clean Code: Definition and Principles - Part 1
Tags: programming, tutorial, python, beginners
Published: 2024-04-14 10:20:00


Clean code refers to well-organized, easily understandable, and maintainable code that allows developers, beyond the original coder, to comprehend and contribute efficiently.

**Principles:**
1. Readability: Code should be straightforward and easily comprehensible.
2. Changeability: Code should be easily modifiable without affecting its overall structure.
3. Extensibility: Code should be designed to allow easy additions or extensions.
4. Maintainability: Code should be structured for straightforward maintenance.

**General Rules (A):**
1. Implement universally accepted coding approaches.
2. Strive for simplicity, avoiding complex structures.
3. Leave the code cleaner than you found it; avoid unnecessary complexity

Scenario: Consider a function that calculates the area of a rectangle.

```
# Bad Code
def area(r_length, r_width):
    res = r_length * r_width
    return res

# Good Code
def calculate_rectangle_area(length, width):
    area_result = length * width
    return area_result
```

Explanation:

- Universally Accepted Approaches: Follow Python conventions and naming standards.
- Strive for Simplicity: Use clear function names and avoid unnecessary abbreviations.
- Leave Code Cleaner: Provide meaningful names and use spaces for readability.

**Design Rules (B):**
1. Store configured data in easily accessible and modifiable sections.
2. Prefer polymorphism over if/else or switch/case conditions.
3. Isolate multi-threading code for clarity.
4. Avoid making every code structure configurable and dynamic.
5. Utilize Dependency Injection for managing dependencies.
6. Follow the Single Responsibility Principle; a class should know only its dependencies.

Scenario: Imagine a class handling various configurations in an application.

```
# Bad Code
class AppConfig:
    config = {}

    def set_config(self, key, value):
        self.config[key] = value

    def get_config(self, key):
        return self.config.get(key, None)
# Good Code
class AppConfig:
    def __init__(self):
        self.configurations = {}

    def set_configuration(self, key, value):
        self.configurations[key] = value

    def get_configuration(self, key):
        return self.configurations.get(key, None)
```
Explanation:

- Store Configured Data: Use clear variable and method names.
- Prefer Polymorphism: Simplify with separate methods for setting and getting configurations.
- Isolate Multi-Threading Code: Handle threading concerns separately.
- Avoid Configurable Dynamism: Keep class configurations straightforward.
- Utilize Dependency Injection: Consider dependencies in the class constructor.

**Tips for Understandability ( C ):**

1. Maintain consistency in methods and structures.
2. Use descriptive variable names.
3. Encapsulate variables and logic comprehensively to avert scattered implementations.
4. Favor primitive types over object types (Immutable).
5. Minimize logical dependencies, preventing unrelated method dependencies within the same class.
6. Minimize the use of negative conditions.

Scenario: Consider a function that calculates the interest on a loan.

```
# Bad Code
def calculate_interest(principal, rate, time):
    i = (principal * rate * time) / 100
    return i
# Good Code
def calculate_loan_interest(principal_amount, interest_rate, time_period):
    interest_amount = (principal_amount * interest_rate * time_period) / 100
    return interest_amount
```
Explanation:

- Maintain Consistency: Use consistent naming conventions.
- Use Descriptive Variable Names: Clearly express the purpose of each variable.
- Encapsulate Variables and Logic: Organize code blocks cohesively.
- Favor Primitive Types: Use basic types for simplicity.
- Minimize Logical Dependencies: Keep the logic focused on the task.
- Minimize Negative Conditions: Use positive conditionals for clarity.

Examples illustrates how a professional programmer applies clean code principles in different aspects of code development, making the codebase readable, maintainable, and extendable.

If you need further information or have specific questions, feel free to ask! Tahsin Soyak tahsinsoyakk@gmail.com