Composition over Inheritance
Assemble behavior from collaborating objects.
Introduction
Composition keeps classes focused and avoids rigid inheritance hierarchies.
Order delegates price calculation to its line items. Each object owns one clear responsibility.
Runnable C# example
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
record LineItem(string Name, decimal Price);
class Order
{
public List<LineItem> Items { get; } = new();
public decimal Total => Items.Sum(item => item.Price);
}
class Program
{
static void Main()
{
var order = new Order();
order.Items.Add(new("Book", 30m));
order.Items.Add(new("Pen", 5m));
Console.WriteLine(order.Total);
}
}
35Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.