Base classes, abstract methods or Design flaw?

62 Views Asked by At

so I have this issue and actually I don't know how to solve this. I was wondering if one of you could point me a bit in the right direction.

I'm working on some event sourcing helpers in C#. I don't think knowledge of event sourcing is required to solve this.

So I created this base class which should do some logic which every aggregateroot should do like getting track of the playhead, returning the uncommitted events.

public class AggregateRootBase: IAggregateRoot
    {
        protected List<IDomainEvent> uncommittedEvents = new List<IDomainEvent>();
        protected int playHead = -1;
        
        public Guid getAggregateRootId()
        {
            throw new NotImplementedException();
        }

        public List<IDomainEvent> getUncommittedEvents()
        {
            return uncommittedEvents;
        }

        public int getPlayHead()
        {
            return this.playHead;
        }

        public void setExpectedPlayHead(int expectedPlayHead)
        {
            this.playHead = expectedPlayHead;
        }
        
        protected void Record(IDomainEvent e)
        {
            this.uncommittedEvents.Add(e);
            this.Apply((dynamic) e);
            this.playHead++;
        }
    }

However my question will focus on this line:

this.Apply((dynamic) e);

Currently the above base class will give a compile error because it does not know how to deal with this Apply method.

A typical child class will look like this:

public class User : AggregateRootBase
{
    // some logic
    
    public void Apply(UserRegistrationInitiated e)
    {
       // set aggregate root props here
    }

    public void Apply(RegistrationConfirmed e)
    {
       // set aggregate root props here
    }

    // some more logic
}

My question is basically how should I deal with that Apply method in the base class? I tried several things but if I make it abstract then I need to supply the types. Which can be anything and I don't want to get bothered with that in future projects.

I also tried to add a method in the base class which points to the interface.

public abstract void Apply(IDomainEvent e) 

But that didn't work because that method got precedence over the methods in the child class.

So I was trying and then I came to the conclusion that I might have created a design flaw that I was not fully aware of. C# is not my primary language so a mistake is easily made.

Already many thanks in advance

0

There are 0 best solutions below