Junior — Middle
Can you give an example of a situation where using an interface provides obvious benefits?
sobes.tech AI
Answer from AI
Interfaces are useful when you need to define a common contract for different classes, allowing for polymorphism and easing the replacement of implementations.
Example scenario:
Suppose you have different classes for sending notifications — via email, SMS, and push notifications. All of them should have a Send() method.
public interface INotifier
{
void Send(string message);
}
public class EmailNotifier : INotifier
{
public void Send(string message) {
// send email
}
}
public class SmsNotifier : INotifier
{
public void Send(string message) {
// send SMS
}
}
// Usage
void NotifyUser(INotifier notifier, string message) {
notifier.Send(message);
}
This approach makes it easy to add new notification methods without changing the code that uses them, and simplifies testing through implementation substitution.