Lets break down some best practices for writing good and fast code in .NET, using simple examples and including important principles that anyone can understand.
1. Follow SOLID Principles
The SOLID principles help you write better code. Think of them as rules for building a strong house.
Single Responsibility Principle (SRP)
Each part of your code should do one job.
Example
// This class only handles user data
public class UserService
{
public void AddUser(User user)
{
// Add user to database
}
}
Open/Closed Principle (OCP)
Your code should be open to adding new features but closed to changing existing ones.
Example
public interface IShape
{
double Area();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double Area() => Math.PI * Radius * Radius;
}
public class Square : IShape
{
public double Side { get; set; }
public double Area() => Side * Side;
}
Liskov Substitution Principle (LSP)
You should be able to use a subclass wherever a parent class is expected.
Example
public class Bird
{
public virtual void Fly() { }
}
public class Sparrow : Bird
{
public override void Fly() { }
}
Interface Segregation Principle (ISP)
Don't force a class to implement methods it doesn't need.
Example
public interface IPrinter
{
void Print();
}
public interface IScanner
{
void Scan();
}
public class MultiFunctionPrinter : IPrinter, IScanner
{
public void Print() { }
public void Scan() { }
}
Dependency Inversion Principle (DIP)
Depends on abstractions, not concrete classes.
Example
public interface IMessageService
{
void SendMessage(string message);
}
public class EmailService : IMessageService
{
public void SendMessage(string message)
{
// Send email
}
}
public class Notification
{
private readonly IMessageService _messageService;
public Notification(IMessageService messageService)
{
_messageService = messageService;
}
public void Notify(string message)
{
_messageService.SendMessage(message);
}
}
2. Use Asynchronous Programming
Asynchronous programming helps your app run faster by doing multiple things at once. Imagine cooking while your rice cooker is working; you can chop vegetables at the same time.
Example
public async Task<string> GetDataAsync()
{
HttpClient client = new HttpClient();
string data = await client.GetStringAsync("https://example.com");
return data;
}
3. Optimize Data Access
Accessing data efficiently is like fetching water from a nearby well instead of a distant river. Use tools that make this easy and fast.
Example
// Using Entity Framework Core for database access
public async Task<List<Product>> GetProductsAsync()
{
using (var context = new MyDbContext())
{
return await context.Products.ToListAsync();
}
}
4. Avoid Unnecessary Work
Avoid doing extra work that slows down your app. For example, don't keep converting data types back and forth.
Example
// Avoid boxing and unboxing
List<int> numbers = new List<int> { 1, 2, 3 };
5. Handle Strings Efficiently
When you need to join many strings, use StringBuilder instead of + to avoid slowing down your app.
Example
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string result = sb.ToString();
6. Handle Errors Gracefully
Handle errors in a way that doesn't crash your app. Think of it like catching a ball before it hits the ground.
Example
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
7. Use Dependency Injection
Dependency Injection helps you manage your app's parts easily, like having a toolbox where each tool has its place.
Example
public interface IMessageService
{
void SendMessage(string message);
}
public class EmailService : IMessageService
{
public void SendMessage(string message)
{
// Send email
}
}
public class MyController
{
private readonly IMessageService _messageService;
public MyController(IMessageService messageService)
{
_messageService = messageService;
}
public void NotifyUser()
{
_messageService.SendMessage("Hello User!");
}
}
8. Profile and Optimize
Regularly check your app's performance and fix slow parts. Use tools like Visual Studio Profiler to find and fix issues.
9. Write Tests
Writing tests ensure your code works correctly. Think of it like checking your homework before submitting it.
Example
[Fact]
public void AddNumbers_ShouldReturnCorrectSum()
{
int result = AddNumbers(2, 3);
Assert.Equal(5, result);
}
By following these simple practices and principles, you can write better and faster .NET code.
😊Please consider liking and following me for more articles and if you find this content helpful.👍