# Clean Code Series: Writing Self-Documenting Code


When reading code, the *what* should be obvious, the *how* should be discoverable, and the *why* should be rare but justified.

In this post, we explore the concept of self-documenting code: code that clearly communicates its purpose without relying on excessive or outdated comments. This is a foundational principle of clean, maintainable software.

## 1. What is Self-Documenting Code?

Self-documenting code **communicates intent through structure, naming, and clarity**, eliminating the need for most comments.

It relies on:

- **Descriptive names** for variables, functions, and types  
- **Clear logic flow** and readable control structures  
- **Well-structured abstractions** that group behavior meaningfully

If someone can understand what your code does without reading a comment, that’s self-documenting.

### Example:

```go
// Bad: requires comment to clarify intent
// Check if user is an admin
if u.Role == 1 {
    // ...
}

// Better: self-documenting
if u.IsAdmin() {
    // ...
}
```

## 2. The Problem with Excessive or Misleading Comments

Comments aren’t inherently bad—but **most are unnecessary, and many are harmful** when they fall out of sync with the code.

### Common issues:

- **Outdated comments**:  
  > "This uses AES-128 encryption" → but the code now uses AES-256.

- **Obvious comments**:  
  ```python
  i += 1  # Increment i by one  ❌
  ```

- **Noise**: comments that clutter rather than clarify.

The more your code *relies* on comments, the more fragile your understanding becomes over time.

## 3. When Comments Are Acceptable

Use comments **only when the code cannot express something clearly** on its own—especially when explaining *why*, not *what*.

✅ **Acceptable comment use cases:**

- **Justifying a non-obvious decision**
  ```go
  // Using polling due to webhook unreliability (see issue #123)
  ```
- **Linking to external specifications**
  ```go
  // Follows RFC 7519 for JWT validation
  ```
- **Clarifying complex business rules that can't be modeled directly**

In short: *comment the why, not the what.*

## 4. How to Make Code Self-Explaining

Achieving self-documenting code is a discipline. These are key strategies:

### ✅ Use Meaningful Names

Bad:
```python
def calc(d, f): ...
```

Good:
```python
def calculate_final_price(discount, fees): ...
```

### ✅ Keep Functions Small and Focused

Small functions are easier to name and understand.

Bad:
```go
func Process(data []byte) error {
    // parsing, validating, persisting, logging...
}
```

Good:
```go
func Process(data []byte) error {
    parsed := parseData(data)
    if err := validate(parsed); err != nil { return err }
    return persist(parsed)
}
```

### ✅ Use Clear Abstractions

Group related behavior meaningfully.

Instead of:

```go
user.SetRole(1)
```

Use:

```go
user.PromoteToAdmin()
```

## 5. Before and After Example

### ❌ Before (with unnecessary comment):

```python
# Check if the order total is greater than the discount threshold
if order.total > 100:
    apply_discount(order)
```

### ✅ After (self-documenting):

```python
if order.qualifies_for_discount():
    order.apply_discount()
```

This version is cleaner, more readable, and the comment becomes unnecessary.

## 6. Key Takeaways

- Comments should be a **last resort**, not a first instinct.
- Aim to write code that **explains itself** through naming, structure, and abstraction.
- Use comments **only to document intent, non-obvious decisions, or external context**.
- Self-documenting code leads to **cleaner diffs, easier reviews, and fewer bugs**.

---

## Final Thoughts

Writing self-documenting code isn’t just about style—it’s a communication skill that separates good developers from great ones.

Next time you write a comment, ask yourself: _“Could I improve the code instead?”_  
Your future self—and your team—will thank you.

---

**📣 Keep the Conversation Going!**

What are your challenges or strategies with self-documenting code? Share your thoughts in the comments!

👉 Follow me on Hashnode and connect on [LinkedIn](https://www.linkedin.com/in/phelipe-rodovalho) for more insights on Clean Code, and Cloud.

🔖 If you found this article useful, share it with your team or fellow developers who value clean, maintainable code!

🔗 Previous article: [Clean Code Series: The Principle of Small Functions](https://byrodovalho.com/clean-code-series-the-principle-of-small-functions)






