BP275: Prefer composition over inheritance

Prefer composition over inheritance in .NET Core and C#. Inheritance is a powerful tool that allows classes to inherit properties and methods from a parent class. However, it can lead to tight coupling between classes and make it difficult to change the behavior of a class without affecting its subclasses. Composition, on the other hand, allows classes to be composed of other classes, which can be easily swapped out or modified without affecting the behavior of the parent class.

Composition is achieved by creating a class that contains an instance of another class as a member variable. This allows the parent class to delegate functionality to the composed class, while still retaining control over its behavior. For example, instead of creating a subclass of a car for each type of engine, you can create an Engine class and compose it with the Car class. This allows you to easily swap out the engine without affecting the behavior of the car.

Composition also promotes code reuse and modularity. By creating small, reusable classes that can be composed together, you can build complex systems from simple building blocks. This makes it easier to maintain and test your code, as well as making it more flexible and adaptable to changing requirements.

public class Engine
{
    public void Start()
    {
        // Start the engine
    }
}

public class Car
{
    private Engine _engine;

    public Car(Engine engine)
    {
        _engine = engine;
    }

    public void Start()
    {
        _engine.Start();
        // Start the car
    }
}

// Usage
var engine = new Engine();
var car = new Car(engine);
car.Start();

Comments

No Comments Yet.
Be the first to tell us what you think.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play