0 day streak
csharp / intermediate
Snippet

Decoupling Logic for Testability

Using interfaces allows for dependency injection, which is critical for unit testing. By depending on IEmailService rather than a concrete class, you can easily inject a mock implementation during tests to verify behavior without sending real emails.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface IEmailService
{
void Send(string message);
}
public class NotificationManager
{
private readonly IEmailService _service;
public NotificationManager(IEmailService service) => _service = service;
public void Notify(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
_service.Send(msg);
}
}
Breakdown
1
public interface IEmailService
Defines a contract that can be swapped with a mock during testing.
2
public NotificationManager(IEmailService service)
The constructor receives the implementation, enabling loose coupling.