ibalgin orbit
ibalgin orbit

Reputation: 11

Interface and overloading

I have a question about best practice.

I have an interface used for sending messages. First I was set only to sms text and now I have decided to also implement emails however I still need to use only one interface. Now my interface contains two methods and I am taking as parameter Message which is fine for the sms however not ok for the email because my email needs to have different properties such as subject.

Can you please advise me how to use only one interface or what should I change?

public interface IMessageSender
{
    Task<MessageResult> SendAsync(Message message);

    MessageResult Send(Message message);
}

public class Message
{
    public string Sender { get; set; }

    public string Reciever { get; set; }

    public string Body { get; set; }
}

public class EmailMessage : Message
{
    public string Subject { get; set; }
}

Upvotes: 0

Views: 227

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

Traditionally, the base Message type includes a virtual method named Send(). You then have types for SMSMessage and EMailMessage which override the Send() method so polymorphism can decide which one to call.

Newer paradigms don't like this as much, because it can be harder to unit test. You can test the individual Send() methods, but not that the right one will be called in the moment. So we have things like Inversion of Control, stubbing/mocking, etc, which generally want to you write and implement extra interfaces like IMessageSender, to add a layer of abstraction where you can verify this happens correctly.

This gives us a new problem: how to know the correct MessageSender is used? And so now we add another pattern: MessageSenderFactory(), which accepts a Message and returns an instance of the correct sender type.

And just like that you're writing Java.


The point is to look carefully at just how far down this rabbit hole you want to go. Right now, this situation can be solved with a simple if() conditional for what kind of message you want to send, but patterns from various programming disciplines will ask you to add several layers on top of this. And they're not wrong. The additional layers and conventions do add meaningful value in terms of testing, flexibility, adaptability, reliability, and recognizable patterns. Much of the time they are the way to go. But they also add complexity, code, and cognitive load to your software. So some awareness of this is valuable, too.

Upvotes: 1

Related Questions