Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
361 changes: 361 additions & 0 deletions website.en/MarkDown/appendix-a.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,361 @@
# Appendix A The Seven Commandments for Beautiful Source Code

![Appendix A Banner](../Images/banner-appendix-a.svg)

![The Seven Commandments Overview](../Images/app_a.seven_overview.png)

## A.1 Detailed Edition and Practical Guide

This appendix provides a comprehensive practical guide for applying the Seven Commandments for Beautiful Source Code introduced in Chapter 1. Each commandment is explored in depth with detailed examples, common pitfalls, and actionable guidance.

## A.2 The First Commandment: Express Intent

### A.2.1 Core Principle

**Code should clearly express what it does and why, not just how it does it.**

The most fundamental principle of beautiful code is that it should communicate the programmer's intent clearly to human readers.

#### Before: How-focused (unclear intent)
```csharp
for (int i = 0; i < employees.Count; i++)
{
if (employees[i].Department == "Sales" && employees[i].Salary > 50000)
{
Console.WriteLine(employees[i].Name);
}
}
```

#### After: What-focused (clear intent)
```csharp
var highEarningSalesEmployees = employees
.Where(emp => emp.Department == "Sales" && emp.Salary > 50000);

foreach (var employee in highEarningSalesEmployees)
{
Console.WriteLine(employee.Name);
}
```

### A.2.2 Practical Implementation

- Use descriptive variable names that explain the purpose
- Choose method names that describe the outcome, not the process
- Write comments that explain "why," not "what"
- Prefer declarative programming over imperative when possible

## A.3 The Second Commandment: Single Responsibility Principle

### A.3.1 Core Principle

**Each class, method, or module should have one reason to change.**

This principle, popularized by Robert C. Martin, ensures that code units are focused and cohesive.

#### Violation Example
```csharp
public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }

// Responsibility 1: Calculate pay
public decimal CalculatePay() { return Salary * 1.1m; }

// Responsibility 2: Save to database
public void Save() { /* database logic */ }

// Responsibility 3: Generate reports
public string GetReport() { return $"Employee: {Name}"; }
}
```

#### Corrected Example
```csharp
public class Employee
{
public string Name { get; set; }
public decimal Salary { get; set; }
}

public class PayrollCalculator
{
public decimal CalculatePay(Employee employee) { return employee.Salary * 1.1m; }
}

public class EmployeeRepository
{
public void Save(Employee employee) { /* database logic */ }
}

public class EmployeeReportGenerator
{
public string GetReport(Employee employee) { return $"Employee: {employee.Name}"; }
}
```

## A.4 The Third Commandment: Accurate Naming

### A.4.1 Core Principle

**Names should precisely describe what they represent.**

Good naming is perhaps the most important aspect of code clarity.

#### Naming Guidelines
- Use searchable names
- Avoid mental mapping
- Use pronounceable names
- Use names from the solution domain
- Be consistent across the codebase

#### Poor Naming Examples
```csharp
var d = 30; // days? dollars? distance?
var lst = GetData(); // what kind of list?
var mgr = new UserMgr(); // manager? what does it manage?
```

#### Good Naming Examples
```csharp
var maxRetryAttempts = 30;
var activeCustomers = GetActiveCustomers();
var userAccountManager = new UserAccountManager();
```

## A.5 The Fourth Commandment: Once And Only Once (DRY)

### A.5.1 Core Principle

**Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.**

Duplication is the root of many maintenance problems.

#### Before: Duplication
```csharp
public void ProcessPremiumCustomer(Customer customer)
{
if (customer.Type == "Premium" && customer.IsActive && customer.Balance > 1000)
{
// Premium processing logic
}
}

public void SendPremiumNewsletter(Customer customer)
{
if (customer.Type == "Premium" && customer.IsActive && customer.Balance > 1000)
{
// Newsletter logic
}
}
```

#### After: Single Source of Truth
```csharp
public bool IsPremiumCustomer(Customer customer)
{
return customer.Type == "Premium" &&
customer.IsActive &&
customer.Balance > 1000;
}

public void ProcessPremiumCustomer(Customer customer)
{
if (IsPremiumCustomer(customer))
{
// Premium processing logic
}
}

public void SendPremiumNewsletter(Customer customer)
{
if (IsPremiumCustomer(customer))
{
// Newsletter logic
}
}
```

## A.6 The Fifth Commandment: Well-Described Methods

### A.6.1 Core Principle

**Methods should be small, focused, and operate at a single level of abstraction.**

#### Guidelines for Method Design
- Keep methods short (ideally under 20 lines)
- Do one thing well
- Use descriptive names
- Minimize parameters (fewer than 5)
- Avoid side effects

#### Method Abstraction Levels
```csharp
// High-level method (orchestration)
public void ProcessCustomerOrder(Order order)
{
ValidateOrder(order);
CalculateTotal(order);
ProcessPayment(order);
ShipOrder(order);
NotifyCustomer(order);
}

// Mid-level methods (specific operations)
private void ValidateOrder(Order order)
{
ValidateCustomerInfo(order.Customer);
ValidateItems(order.Items);
ValidateShippingAddress(order.ShippingAddress);
}

// Low-level methods (detailed implementation)
private void ValidateCustomerInfo(Customer customer)
{
if (string.IsNullOrEmpty(customer.Email))
throw new ValidationException("Customer email is required");
}
```

## A.7 The Sixth Commandment: Unified Rules

### A.7.1 Core Principle

**Consistency in coding style, naming conventions, and architectural patterns across the entire codebase.**

#### Areas for Unification
- Naming conventions
- Code formatting
- Error handling patterns
- Logging approaches
- Documentation style

#### Example: Unified Error Handling
```csharp
public class ApiResponse<T>
{
public bool Success { get; set; }
public T Data { get; set; }
public string ErrorMessage { get; set; }
public string ErrorCode { get; set; }
}

// Consistent usage across all API endpoints
public ApiResponse<Customer> GetCustomer(int id)
{
try
{
var customer = customerRepository.GetById(id);
return new ApiResponse<Customer> { Success = true, Data = customer };
}
catch (Exception ex)
{
return new ApiResponse<Customer>
{
Success = false,
ErrorMessage = ex.Message,
ErrorCode = "CUSTOMER_NOT_FOUND"
};
}
}
```

## A.8 The Seventh Commandment: Testable

### A.8.1 Core Principle

**Code should be designed to be easily and thoroughly testable.**

#### Design for Testability
- Use dependency injection
- Avoid static dependencies
- Keep methods pure when possible
- Separate concerns clearly
- Make side effects explicit

#### Before: Hard to Test
```csharp
public class OrderProcessor
{
public void ProcessOrder(Order order)
{
var customer = Database.GetCustomer(order.CustomerId);
var total = CalculateTotal(order.Items);

EmailService.SendConfirmation(customer.Email, order.Id);
Logger.Log($"Order {order.Id} processed");
}
}
```

#### After: Easy to Test
```csharp
public class OrderProcessor
{
private readonly ICustomerRepository customerRepository;
private readonly IEmailService emailService;
private readonly ILogger logger;

public OrderProcessor(
ICustomerRepository customerRepository,
IEmailService emailService,
ILogger logger)
{
this.customerRepository = customerRepository;
this.emailService = emailService;
this.logger = logger;
}

public void ProcessOrder(Order order)
{
var customer = customerRepository.GetById(order.CustomerId);
var total = CalculateTotal(order.Items);

emailService.SendConfirmation(customer.Email, order.Id);
logger.Log($"Order {order.Id} processed");
}

// Pure function - easy to test
private decimal CalculateTotal(IEnumerable<OrderItem> items)
{
return items.Sum(item => item.Price * item.Quantity);
}
}
```

## A.9 Practical Implementation Checklist

### A.9.1 Daily Practice Guidelines

- [ ] Every method expresses a clear intent
- [ ] Each class has a single, well-defined responsibility
- [ ] All names are descriptive and meaningful
- [ ] No code duplication exists
- [ ] Methods are short and focused
- [ ] Coding style is consistent
- [ ] All code is easily testable

### A.9.2 Implementation Guidelines

#### When Implementing New Features
1. **Understand Requirements**: Clarify what you want to achieve
2. **Design**: Design according to the Seven Commandments
3. **Implement**: Implement carefully, one piece at a time
4. **Test**: Verify that each commandment is satisfied
5. **Review**: Confirm with team members

#### When Refactoring
1. **Identify Problems**: Analyze which commandments are violated
2. **Prioritize**: Address problems with the greatest impact first
3. **Gradual Improvement**: Don't change everything at once, improve step by step
4. **Test**: Verify that existing functionality is not broken
5. **Continue**: Continue improvement continuously

---

*The Seven Commandments for Beautiful Source Code are not just technical guidelines, but a philosophy for writing code that communicates clearly with future readers and maintainers. By following these principles consistently, you'll create software that is not only functional but also a pleasure to work with.*

---

**[← Return to Table of Contents](table-of-contents.md)**
Loading