C#C
C#3y ago
20 replies
lukkasz323

❔ How can I reuse code without inheritance?

public interface IEntity
    {
        int Size { get; }
        Vector2 Position { get; }
    }

public class Player : IEntity
{
    public int Size { get; } = 32;
    public Vector2 Position { get; private set; }

    public Player(Scene scene)
    {
        var spawnOffset = new Vector2(0, -3);

        Position = new Vector2(
            spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
            spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
    }
}

public class Enemy : IEntity
{
    public int Size { get; } = 32;
    public Vector2 Position { get; private set; }

    public Enemy(Scene scene)
    {
        var spawnOffset = new Vector2(0, 0);

        Position = new Vector2(
            spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
            spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
    }
}

I'm trying to learn composition over inheritance, and so far so good, but the problem is that quickly there is a lot of complex code reuse, just take a look at both of these constructors, so much things I have to keep consistent between two classes.

In case of inheritance I would just call the base class constructor, but what are my other possibilities here? The more of them, the better. Thanks.
Was this page helpful?