Composition over Inheritance
Composition keeps classes focused and avoids rigid inheritance hierarchies.
How it works
Assemble behavior from collaborating objects.
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.