Search code examples
c#umlclass-diagram

composition and aggregation example with UML class diagram


i can't seem to understand completely the difference between aggregation and composition in a code.

Client <.>---->BankAccount

(this is supposed to be Client - BankAccount composition class diagram).

So in this example, Client has a bank account, so this means, when a client object dies, his bank account object dies too. Does this mean, that we have to have a BankAccount object within Client class ?

Class Client
{

    BankAccount acc = new BankAccount();

    public void addMoneyToBankAccount(decimal amount)
    {         
        acc.AddMoney(amount);
    }

    public decimal CheckBalance()
    {
        return acc.CheckAccountBalance();
    }

}

So, is this composition in code ? What would aggregation look like in this example? Sorry for the newbie question, please correct me if the code was wrong. Thanks in advance.


Solution

  • Yes, What you do is call composition, if you want to do aggregation you to it like this:

    Class Client
    {
    
        BankAccount acc;
    
        public Client(BankAccount p_acc)
        {
          acc=p_acc;
        }
    
        public void addMoneyToBankAccount(decimal amount)
        {         
            acc.AddMoney(amount);
        }
    
        public decimal CheckBalance()
        {
            return acc.CheckAccountBalance();
        }
    
    }
    

    Aggregation:

    If inheritance gives us 'is-a' and composition gives us 'part-of', we could argue that aggregation gives us a 'has-a' relationship. Within aggregation, the lifetime of the part is not managed by the whole. To make this clearer, we need an example. For the past 12+ months I have been involved with the implementation of a CRM system, so I am going to use part of this as an example.

    The CRM system has a database of customers and a separate database that holds all addresses within a geographic area. Aggregation would make sense in this situation, as a Customer 'has-a' Address. It wouldn't make sense to say that an Address is 'part-of' the Customer, because it isn't. Consider it this way, if the customer ceases to exist, does the address? I would argue that it does not cease to exist. Aggregation is shown on a UML diagram as an unfilled diamond.

    As I said at the beginning of the answer, this is my take on composition and aggregation. Making the decision on whether to use composition or aggregation should not be a tricky. When object modelling, it should be a matter of saying is this 'part-of' or does it 'have-a'?