Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Now the title might seem like the question has been asked before but let me expl

ID: 646058 • Letter: N

Question

Now the title might seem like the question has been asked before but let me explain my situation and you'll see why I am asking this question.

Let's consider this interface :

public interface IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;
}
If someone wants to implement this interface, they would have to check if ItemAdded is null and only if it is not null, they would call it. Well, I want to simplify their job by giving an in built function which will do the same. Just calling that function will check if the corresponding event is null, and if it isn't, it'll fire its corresponding event.

The problem is, this is an interface. So I can't define a method. So I thought I might go with an abstract class. But considering the situation, it would be best suited to make this as an interface rather than an abstract class.

So do I just drop the idea of giving an in built function? Or do I make it an abstract class? Which better suits the situation? I am having a tough time deciding which one to use. Some help please?

Explanation / Answer

What would be best is to have a mixin, but unfortunately C# doesn't include this concept. In the absence of mixins, I'd pick an interface over an abstract class almost every time, and definitely in this case. Whatever functionality has to be offered to derived classes, it can be offered in form of helper objects and utility functions. Favoring composition over inheritance is my favorite design principle.

In this specific case we should be able to have it both though. I would definitely have the interface, as you defined it. The interface should be used by all consumers and other classes in your utility. For the convenience of your users (developers) I would also have a default implementation of the interface that can be used as a base class.

public interface IListChangedListener {
public event EventHandler ItemAdded;
public event EventHandler ItemRemoved;
}

public class ListChangedListener : IListChangedListener {
public event EventHandler ItemAdded;
public event EventHandler ItemRemoved;

public void FireItemAdded(...) {
if (ItemAdded != null)
ItemAdded(...)
}

public void FireItemRemoved(...) {
if (ItemRemoved != null)
ItemRemoved(...)
}
}
This way a developer can either derive from the ListChangedListener class, or implement the IListChangedListener interface directly, depending on circumstances. In the end of the day what counts is that the listener class they provide implements the IListChangedListener interface.

Would that work?