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
- Define
UserandOrderclasses with clear, well-named properties. - Implement an
IRepositorio<T>interface withAdd,Remove,GetAllmethods. - Apply standardization principles for class, method, and variable names.
- 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();
}