Thursday, September 5, 2013

From Asotiation to Composition & More.

Association, Aggregation, Composition, Inheritance - what are those?
(OOP, UML)


Either association and aggregation  topic terms are both concepts of software design. They are considered in terms of relation between two classifiers, such as classes (but also use cases), that describe the relation reasons and rules  that governs it.
In this article we assume readers basic knowledge of UML class diagrams.


A relationship is a general term covering the specific types of logical connections found on class and object diagrams in UML.
Below we will try to focus on gathering information about a relationship between classes of objects:


Inheritance > Composition > Aggregation > Association > Link


Link

The most general relationship is Link. It simply only gives a notion of a relation not describing its particular properties. A link is a relationship between objects or instances of the classifiers. In general Link is an instance of an association, while an association is a relationship between two classifiers.
  

Association: uses a

Ex:a Class Man uses a Class Pen
It is the weakest of all relations. An association represents a structural relationship that connects two classifiers. Like attributes, associations record the properties of classifiers.


For example, in relationships between classes, you can use associations to show the design decisions that you made about classes in your application that contain data, and to show which of those classes need to share data. You can use an association's navigability feature, to show how an object of one class gains access to an object of another class or, in a reflexive association, to an object of the same class.    The name of an association describes the nature of the relationship between two classifiers and should be a verb or phrase. In the diagram editor, an association appears as a solid line between two classifiers.

In General:

  • temporal relation between objects
  • objects associated are independent (deleting one does not mean delete second)
  • associated objects contain reference to the other object
  • In Java equal to field

Example:

Passenger knows about his ticket reservations and reservation knows about who is its owner. In case reservation does not have reference to passenger when the association is unidirectional type (with an arrow in UML). With bidirectional association there are no arrows and both objects have references to each other


    • In Java


The association relationship is a way of describing that a class knows about and holds a reference to another class. This can be described as a "has-a" relationship because the typical implementation in Java is through the use of an instance field. The relationship can be bi-directional with each class holding a reference to the other. Below there is a bi-directional association implemented many-to-one in Java using fields:

public class Department {

private Set staff = new HashSet();
...
}

public class Employee {

private Department department;
...
}

To make it uni-directional, one of the classes would not have its relation field.

What is the problem with a bi-directional association?

Unlike a relation in a RDBMS, a bi-directional association is stored on two ends. Lets illustrate it with example. We want to add a new employee to a department:

Department sales     = DepartmentsStore.getDepartment(...);
Department it        = DepartmentsStore.getDepartment(...);

Employee john = Employees.getEmployee(“john_id”);

john.getDepartment(); //  Lets say JOHN works in “IT” dept.

john.setDepartment(sales); //!? 


This would not work. We would still had to add “john” to “sales” and remove him from “it”:
sales.getStaff().add(john);
it.getStaff().remove(john);
So we have to take care of all this maintenance. Otherwise the application would collapse. And you can imagine in how many places this would have to be repeated in enterprise application.
Lets make it more OOP in terms of behaviour and responsibilities. We would have to consider business logic. Thats why we assume that the hire/fire is responsibility of Department.

public void hire(Employee employee)throws HumanResourceException {
staff.add(employee);
}

public void fire(Employee employee) throws HumanResourceException {

if (!staff.contains(employee)) throw new HumanResourceException("Employee does not work at this department");

staff.remove(employee);

}
But this is only the Department part not the Employee state needs to be modified:
void _changeDepartment(Departmentdepartment) {
    assert this.department == null;

    this.department = department;
}

void _removeFromItsDepartment() {
    assert this.department != null;
    this.department = null;

}


But still those methods should be used only by Department and there is no way to limit the scope of a method to one other class. You can only put it to the same package and follow convention of underscore meaning “used internally”.

This is still ugly and do it at home or work by yourself.


Aggregation: has a

Ex:a Class Man has a Class Car ( Car is still there when Man die )
Aggregation (white diamond) has no semantics beyond that of a regular association. It is, as Jim Rumbaugh puts it, a modeling placebo. People can, and do, use it - but there are no standard meanings for it. So if you see it, you should inquire as to what the author means by it. I would advise not using it yourself without some form of explanation.       
- Martin Fowler


This relationship is described as a “has-a” or “whole/part” relation between two classes. It is more strict relation than association. One of the classes - so called aggregate class - contains reference to the second class and is therefore said to have ownership of that second class. The class that is being referenced from within aggregate class is considered to be part-of the aggregate class. Aggregation is a stronger case of association as a directional association between objects.
You can say that you have aggregation between two objects when an object
“has-a” another object. The additional information about relation’s direction is determined by deciding which object contains the other object.

In General:

  • Stronger than association
  • there is an owner and owned connected with their time of existence
  • It is part-to-whole type of relation i.e. a part might belong to many unities therefore unity do not govern time of “part” existence
  • aggregation means enclosing


Example:

  • The university division does NOT create nor delete instance of professor it only contains it.
  • Book register at library and particular book card. The register encloses book cards.





Composition: contains/owns a (Total composition) HAS-A

Ex:a Class Man owns a Class Heart ( When Man die, Heart die )
Composition (black diamond) does carry semantics. The most particular is that an object can only be the part of one composition relationship. So even if both windows and panels can hold menu-bars, any instance of menu-bar must be only held by one whole. This isn't a constraint that you can easily express with the regular multiplicity markers.   
- Martin Fowler


The strongest from the relationships. Composition is a special case of aggregation. A restricted aggregation is called composition. Therefore, composition is when a an object contains the other object and the contained object cannot exist without the existence of container object. In ther words: composition ensure that the containing object is responsible for the lifetime of the object it holds. If Object BAR is contained within Object FOO, then Object FOO is responsible for the creation and destruction of Object BAR. Unlike aggregation, Object BAR cannot exist without Object FOO.

In General:

  • Just like aggregation relationship of part-whole
  • The Whole object is the only owner, creator and administrator of the Part object.
  • Part and Whole cannot exist without each other ie. their time of existence is connected
    • deleting the Whole object removes all its Part objects
  • Referred as “has-a


Example:

  • Encyklopedia has many toms.
  • University has a Department



REMEMBER:

Both Composition and Aggregation are Associations.
Composition IS-A strong Association.
Aggregation IS-A weak Association.

Inheritance/Generalization: IS-A

Ex:a Class Man is a Class Human ( Man is a Human )


As the name inheritance suggests an object is able to inherit characteristics from another object. In more concrete terms, an object is able to pass on its state and behaviors to its children. For inheritance to work the objects need to have characteristics in common with each other. Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order. When we talk about inheritance, the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.


  • Java
There is a quite complex explanation of how to consider inheritance in java at Java1 and Java2



General Example 1:


And the code:


public abstract class Item {

        int positionInList;
        String fullName;
}

public class MenuItem extends Item{

        Currency price;
        String description;

void changePrice (Currency newPrice){
             this.price = newPrice;
      }
}


/* AGGREGATION
* In Menu we can change MenuItem price, but the mItem is not only internal consern of Menu.
* It can be swapped, or even completely removed.
*/

public final class Menu {

      private List<MenuItem> mItem;


void addMenuItem(MenuItem mi){
            mItem.add(mi);
}

void changePrice(Currency newPrice, int position){

    if (mItem.get(position) != null){
      mItem..get(position).changePrice(newPrice);
    }
 }
}

public class Order {

private final List<OrderItem> oItems;

Order(List<OrderItem> items){
   this.oItems = new ArrayList<OrderItem>();
   this.oItems.addAll(items);
}

void modifyItem(String wish, int position){
    oIitems.get(pos).addNote(wish);
  }
}

public final class OrderItem extends Item{

String guestNotes;
List<int> positionInMenu;

private final addNote(String wish){
   this.guestNotes = wish;
}
}


General Example 2:





And the code:

public class University {

private List<Department> departments;

public void destroy(){
//it's composition, when i destroy a university I also destroy the departments. they cant live outside my university instance
    if(departments!=null)
    for(Department d : departments)
       d.destroy();
    departments.clean();
    departments = null;
  }
}

public class Department {

private List<Professor> professors;
private University university;

Department(University univ){
    this.university = univ;
}

public void destroy(){
//It's aggregation here, we just tell the professor they are fired but they can still keep living
   for(Professor p:professors)
     p.fire(this);
   professors.clean();
   professors = null;
   }
}

public class Professor extends Person{

private String fullTitle;
private List<Department> attachedDepartments;

public void destroy(){
}

public void fire(Department d){
    attachedDepartments.remove(d);
    }
}


public class Student extends Person{
}

public abstract class Person{
  
   String name;
   String surname;
}



There is more explanation of differences between inheritance and composition in following article.

No comments :

Post a Comment

Social Buttons End POst