Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate aggregation and composition relationship using source code

Is it possible to differentiate between composition and aggregation relationship by reading the source code?

I tried to find some patterns and I have listed them below.

I am taking the example from this site just to explain what I assume to be a pattern

COMPOSITION

enter image description here

 public class Engine
{
    . . . 
}

public class Car
{
   Engine e = new Engine();
    .......
}

AGGREGATION

enter image description here

public class Address
{
. . .
}

public class Person
{
   private Address address;
   public Person(Address address)
   {
     this.address = address;
   }
   . . .
}

I find these patterns to differentiate

COMPOSITION (is a part of )

  1. Defined as a field of a class.

    • Example: [Engine e] Engine is defined as a field e of the class Car
  2. Instantiated and assigned within the class.

    • Example: [Engine e = new Engine();] Engine is instantiated inside the class

Aggregation (has a)

  1. Defined as a field of a class

    • Example: [private Address address;] Address is defined as a field address of the class Person
  2. Instatiated out side the class

    • Example: [Address address = new Address();] Address is instatiated outside Person.
  3. Assigned in the constructor by sending the instance as a argument to the constructor.

    • Example: [Person person = new Person(address);] The instance of Address is passed as an argument through the constructor and assigned in the constructor of the class Person.

CAN I CONSIDER THESE TO DIFFERENTIATE AGGREGATION AND COMPOSITION RELATION?

ARE THERE MORE CONSTRAINTS THAT ARE USED TO DIFFERENTIATE?

like image 871
Sachin Avatar asked Nov 05 '22 17:11

Sachin


1 Answers

Not really, because there's not a unique way to implement each kind of association (in fact, the problem is that we have three kinds of associations, "normal associations", "aggregations" and "compositions").

If the language has pointers then you could try to guess that if Engine is defined in Car as a pointer then the programmer that wrote that piece of code is suggesting a softer relationship (aggregation or association) between Cars and Engines since removing the Car does not imply losing the Engine object.

like image 120
Jordi Cabot Avatar answered Dec 05 '22 00:12

Jordi Cabot