Composition1 min read

What is Composition?

It’s a relationship between two classes that allows one to contain the other. When one class is subset of the other, “has-a” relationship.

I.E. Person has Leg

What are benefits of using composition?

  • code re-use
  • way of achieving loose coupling
  • flexibility

Code

public class Hand {
    private readonly Logger _logger;

    public Hand(Logger _logger){
        _logger = Logger;
    }

    public void Grab(){
        _logger.Log("Grabbing something")
    }
}


public class Leg {
    private readonly Logger _logger;

    public Leg(Logger _logger){
        _logger = Logger;
    }

    public void Walk(){
        _logger.Log("Walking");
    }
}

public class Logger {
    public void Log(string message){
        Console.WriteLine(message);
    }
}

public class Program {
    static void Main(string args[]) {

        var leg = new Leg(new Logger());

        leg.Walk(); //outputs "Walking" to logger class

        var hand = new Hand(new Logger());
        hand.Grab(); // outputs "Grabbing something" to logger class

    }
}

SUMMARY

As you can see, we got code reuse with Logger class to two other classes using composition. This way code becomes more flexible with higher degree of code reusing and achieving loose coupling.

Leave a Reply

Your email address will not be published. Required fields are marked *