Using Composition Over Inheritance Leads To Duplicated Code?

353 Views Asked by At

In my quest to make the best weapon system out there (currently working in UE4) I have been moving all of my code to components.

public class Weapon
{
    public FiringComponent firing;

    ... 
}

public class FiringComponent
{
    public void Begin(){ ... }
}

public class FullAutoComponent : FiringComponent
{
    //variables

    public void Fire(){ ... }
}

public class SemiAutoComponent : FiringComponent
{
    //variables

    public void Fire(){ ... }
}

The problem with this approach is that most of the firing components end up sharing a big part of their implementation of the ‘firing’ behavior, which I understand is not great. This has lead me to moving a lot of the behavior into a base class, in this case firing component, which has destroyed the benefits that the composition pattern was giving me.

How would you guys implement a weapon system using composition that has no code duplication? What exactly am I doing wrong that is making the components share that amount of implementation code?

Also, I might not have made it clear in this post, but this is a second revision of the system, the first one was using interfaces for the components, but the duplication of code made me have to move some of it into a base class. Nonetheless, it’s bad.

0

There are 0 best solutions below