Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Interfaces / Abstract class - ensure event is raised on method

I have an interface defined as IStore, with two methods:

public interface IStore<TEntity>
{
    TEntity Get(object identifier);
    void Put(TEntity entity);
}

I want an event to be raised on the success of Put (for reference, Put could store a row in a db, or file on the file system etc...)

So, a class implementing Istore for type of Product would look a bit like this:

class MyStore : IStore<Product>
{
    public Product Get(object identifier)
    {
        //whatever
    }

    public void Put(Product entity)
    {
        //Store the product in db
        //RAISE EVENT ON SUCCESS
    }
}

What i'm after, is a way of ensuring that every implementation of IStore raises the event - should i have an abstract class instead, or as well as, the interface?

like image 309
Alex Avatar asked Jul 07 '10 12:07

Alex


2 Answers

my suggestion:

public abstract class Store<TEntity>
{
    public abstract TEntity Get(object identifier);
    public void Put(TEntity entity)
    {
        //Do actions before call
        InternalPut(entity);
        //Raise event or other postprocessing
    }

    protected abstract void InternalPut(TEntity entity);
}

then override InternalPut in your class

like image 135
Andrey Avatar answered Nov 15 '22 16:11

Andrey


There is really no way of ensuring that every implementation of IStore raises an event. You could have an abstract class that has the put method, but that still doesn't mean that you could have a put method in a subclass of the abstract class that totally ignores the abstract class's method.

In the end, the best way to encourage the raising of the event is to write the method the developer should use, by way of an abstract class. That way, they have to go out of their way not to use it

like image 29
Dan McClain Avatar answered Nov 15 '22 17:11

Dan McClain