0

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.

  • "which has destroyed the benefits that the composition pattern was giving me." What benefits was it giving you in this case? I would avoid blindly following "prefer composition over inheritance" like it's gospel. The key word is 'prefer'. That is, when both options are viable, composition is more flexible down the line. But inheritance has its place when objects represent an "is a" relationship, which I would say is your case. See https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance – Rotem Sep 17 '20 at 15:37
  • @Rotem I realize that I don't necessarily have to use composition in this situation, but Inheritance also gives plenty of headaches when needing to change something in the base class for instance. As for the benefits of composition in this situation, my idea was to have a 'weapon' neatly separated into components that represent what it can do. Ideally with the added bonus of not reusing code. – Octavian Tocan Sep 17 '20 at 16:42
  • I understand, but it's hard to speak of the best approach to a weapon without seeing what your weapon actually needs to do, or what issues inheritance was causing. You'd need to provide an actual problem you were facing and then it's easier to discuss whether the problem is in the class design or if it's a problem that's inherent to inheritance. – Rotem Sep 17 '20 at 17:07

0 Answers0