Coding Standards and Best Practices

Intermediate 20 min read Lesson 4 of 5

Why Coding Standards Matter

  • Readable and maintainable code
  • Consistent codebase
  • Easier code reviews
  • Reduced bugs
  • Faster onboarding of new developers

Naming Conventions

C# Naming Rules

// PascalCase for classes and methods
public class UserService
{
    public User GetUserById(int id) { }
}

// camelCase for parameters and local variables
public void ProcessUser(User user)
{
    string userName = user.Name;
}

// _camelCase for private fields
private readonly ILogger _logger;

// UPPER_CASE for constants
private const int MAX_RETRY_COUNT = 3;

// I + PascalCase for interfaces
public interface IUserService { }

Best Practices

1. Clean Code Principles

// Bad
public void ProcessData(List data) { ... }

// Good - Descriptive names
public void ProcessUserOrders(List orders) { ... }

2. SOLID Principles

  • Single Responsibility: One class, one responsibility
  • Open/Closed: Open for extension, closed for modification
  • Liskov Substitution: Subtypes must be substitutable
  • Interface Segregation: Many specific interfaces
  • Dependency Inversion: Depend on abstractions

3. Error Handling

// Good - Specific exceptions
try
{
    var result = await GetDataAsync();
}
catch (HttpRequestException ex)
{
    logger.LogError(ex, "API call failed");
    throw new ServiceException("Failed to fetch data", ex);
}

// Good - Guard clauses
public void ProcessOrder(Order order)
{
    if (order == null)
        throw new ArgumentNullException(nameof(order));
        
    if (order.Items.Count == 0)
        throw new InvalidOperationException("Order has no items");
}

4. Async/Await

// Good - Async all the way
public async Task GetUserAsync(int id)
{
    return await _userRepository.GetByIdAsync(id);
}

Code Review Guidelines

What to Review

  • Functionality matches requirements
  • Code follows standards
  • No security vulnerabilities
  • Performance considerations
  • Test coverage
  • Documentation
Key Takeaway

Consistent coding standards and best practices lead to maintainable, high-quality code.

Exercise
  1. Review a piece of code for standards compliance
  2. Refactor code following best practices
  3. Add XML documentation to methods
  4. Create a code review checklist
Test Your Knowledge - Take Quiz