Skip to main content

Best Practices and Clean Code

Standardization Conventions

Following coding conventions helps maintain clean, readable, and easily maintainable code.
In C#, it is recommended to follow the guidelines established by Microsoft.

Class Names

  • Use PascalCase.
  • They should be nouns representing entities or concepts.
public class UserManager { }
public class Order { }

Method Names

  • Use PascalCase.
  • They should be verbs or verb phrases.
public void CalculateTotal() { }
public async Task GetDataAsync() { }

Property Names

  • Use PascalCase.
  • They represent characteristics of an object.
public string Name { get; set; }
public int Age { get; set; }

Local Variable and Parameter Names

  • Use camelCase.
  • They should be descriptive and clear.
string userName = "Carlos";
int orderCount = 5;

Private Field Names

  • Use camelCase prefixed with an underscore _.
private int _counter;
private string _message;

Interface Names

  • Use PascalCase prefixed with I.
public interface IRepository { }
public interface IService { }

Constant Names

  • Use PascalCase or SCREAMING_CASE depending on the team's convention.
public const double Pi = 3.1416;
public const int MAX_ATTEMPTS = 5;

Enumeration Names

  • Use PascalCase for the enumeration and its values.
public enum OrderStatus
{
Pending,
Processed,
Completed,
Canceled
}

Applying Clean and Readable Code Standards

  • Short methods with a single responsibility (SRP - Single Responsibility Principle).
  • Avoid code duplication (DRY - Don't Repeat Yourself).
  • Maintain class cohesion (high cohesion, low coupling).
  • Use comments only when the code is not self-explanatory.
  • Prefer name expressiveness over unnecessary comments.
  • Apply SOLID principles.
  • Maintain consistency with the project style.

Example of bad code:

public void H(int x, int y)
{
var z = x + y;
Console.WriteLine(z);
}

Example of good code:

public void PrintSum(int number1, int number2)
{
int result = number1 + number2;
Console.WriteLine(result);
}

🔹 Practical Project to Apply Conventions

Description

Create a C# console application that manages users and orders applying Clean Code conventions.

Requirements

  1. Define User and Order classes with clear, well-named properties.
  2. Implement an IRepositorio<T> interface with Add, Remove, GetAll methods.
  3. Apply standardization principles for class, method, and variable names.
  4. Create a main flow that allows registering users and orders in a clear and readable way.

Base Example

public class User
{
public int Id { get; set; }
public string Name { get; set; }
}

public class Order
{
public int Id { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
}

public interface IRepository<T>
{
void Add(T entity);
void Remove(int id);
IEnumerable<T> GetAll();
}