Java OOPS Design Principles

1) Composition Vs Aggregation

When studying UML , one of the most important questions which comes to mid of a programmer is , What is the difference between Aggregation and Composition ?

Composition implies that the child objects share a lifespan with the parent. Aggregation doesn't. For example, a chess board is composed of chess squares - the chess squares don't really exist without the board. However, a car is an aggregation of parts - a car exhaust is still a car exhaust if it's not part of a car at the time.



Composition and Aggregation are types of associations. They are very closely related and in terms of programming there does not appear much difference.  I will try to explain the difference between these two by java code examples
Aggregation: the object exists outside the other, is created outside, so it is passed as an argument (for example) to the construtor. Ex: People – car. The car is create in a different context and than becomes a person property.
Composition: the object only exists, or only makes sense inside the other, as a part of the other. Ex: People – heart. You don’t create a heart and than passes it to a person.
Code example for aggregation:
// WebServer is aggregated of a HttpListener and a RequestProcessor
public class WebServer {
private HttpListener listener;
private RequestProcessor processor;
public WebServer(HttpListener listener, RequestProcessor processor) {
   this.listener = listener;
   this.processor = processor;
  }
}
Code example for composition
// WebServer is an composition of HttpListener and RequestProcessor and controls  //their lifecycle
public class WebServer {
private HttpListener listener;
private RequestProcessor processor;
public WebServer() {
   this.listener = new HttpListener(80);
   this.processor = new RequestProcessor(“/www/root”);
  }
}
In composition, whole has responsibility of preventing garbage collection of part.

2) Composition over Inheritance

composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type.. So the goose is more or less cooked once you derive from Class A.
My acid test for the above is:
  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
  • Does TypeB only want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.
Inheritance
This encourages the use of classes. Inheritance is one of the three tenets of OO design (inheritance, polymorphism, encapsulation).
class Person {
   String Title;
   String Name;
   Int Age
}

class Employee : Person {
   Int Salary;
   String Title;
}
This is inheritance at work. The Employee "is a" Person or inherits from Person. All inheritance relationships are "is-a" relationships. Employee also shadows the Title property from Person, meaning Employee.Title will return the Title for the Employee not the Person.

Composition

Composition is favoured over inheritance. To put it very simply you would have:
class Person {
   String Title;
   String Name;
   Int Age;

   public Person(String title, String name, String age) {
      this.Title = title;
      this.Name = name;
      this.Age = age;
   }
}
class Employee {
   Int Salary;
   private Person person;

   public Employee(Person p, Int salary) {
       this.person = p;
       this.Salary = salary;
   }
}

Person johnny = new Person ("Mr.", "John", 25);
Employee john = new Employee (johnny, 50000);
Composition is typically "has a" or "uses a" relationship. Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it "has a" Person.

Composition over Inheritance

Now say you want to create a Manager type so you end up with:
class Manager : Person, Employee {
   ...
}
This example will work fine, however, what if Person and Employee both declared Title? Should Manager.Title return "Manager of Operations" or "Mr."? Under composition this ambiguity is better handled:
Class Manager {
   public Title;
   public Manager(Person p, Employee e)
   {
      this.Title = e.Title;
   }
}
The Manager object is composed as an Employee and a Person. The Title behaviour is taken from employee. This explicit composition removes ambiguity among other things and you'll encounter fewer bugs.

3) Association Vs Aggregation Vs Composition

Association represents the ability of one instance to send a message to another instance. This is typically implemented with a reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.

Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).

Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

29 comments:

  1. I do trust all of the concepts you’ve presented on your post. They’re really convincing and will definitely work. Still, the posts are too brief for newbies. May you please extend them a little from subsequent time?Also, I’ve shared your website in my social networks.
    Industrial Architecture
    Warehouse Architect
    Civil Engineering Consultants
    Office Interiors in Chennai
    Rainwater Harvesting chennai

    ReplyDelete
  2. I think it's awesome someone is finally taking notice of our vet's and doing something to help them. I hope all goes well with these articles. More new information i will get after refer that post.
    Manufacturing ERP
    Oil and gas ERP
    ERP software companies
    Best ERP software
    ERP for the manufacturing industry

    ReplyDelete
  3. Get to know about career in Ethical Hacking. Career Overview, Salary, Key skills and Education needed. Get how to Become Ethical Hacker guidelines ...

    ReplyDelete
  4. In this age of Technology advancement, computer and information technology have not only brought convenience to citizens in modern life but also for policemen & various Government officials of the nation to fight cybercrime through various modus operandi. Indian Cyber Army has been dedicated in fighting cyber crime, striving to maintain law and order in cyberspace so as to ensure that everyone remains digitally safe.Read more:- Information Security

    ReplyDelete
  5. ExcelR Offers Business Analytics / Data Scientist Course / Data Analytics Training & Data Science Course Training In Bangalore, With 100% Placement.Data science certification in Bangalore

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Quickbooks enterprise support Get Quickbooks Enterprise Support from certified Quickbooks Technical Team (+1 (833) 400-1001). We are available 24*7 for your service. Our Professional experts will resolve all issues of Quickbooks.(+1 (833) 400-1001)

    ReplyDelete

  8. Quickbooks enterprise support Phone number Solve your Quickbooks errors.
    Contact us and get 24*7 Quickbooks Enterprise support and get fixed Quickbooks errors by our certified Quickbooks Enterprise Support team. (+1 (833) 400-1001)

    ReplyDelete
  9. Nice blog information by the provided
    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    Piping Design Course in India­

    ReplyDelete
  10. Nice blog posting information of the author provided

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
    Document Controller course
    Pressure Vessel Design Course
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  11. it is a useful article when i compared to others.thanks for this wonderful article. Artificial Intelligence Course

    ReplyDelete
  12. MGLSarees.com - Shop Best Mangalagiri Handloom Cotton and Pattu Sarees | Dress Materials - Shop for the exclusive stylish and ethnic handloom sarees online at great price. ✯Free Shipping. Select from the best range of womens Dress Materials. Buy handloom silk and pattu sarees online, buy exclusive handloom cotton saris online, purchase handloom cotton sarees online, latest designer handloom saris, attractive prices, worldwide express shipping. MGLSarees - Online Mangalagiri Handloom Cotton and Pattu Sarees | Dress Materials - Online Shopping Website, Mangalagiri
    Mangalagiri Sarees and Dress Materials
    Mangalagiri Pattu Sarees
    Mangalagiri Dress Materials

    ReplyDelete
  13. Nice information thanku for sharing.
    health care analytics
    360DigiTMG has developed the Certification Program in Healthcare Analytics. This course is meticulously designed to suit both Healthcare practitioners, IT Business Analysts and Data Scientists.
    https://360digitmg.com/india/life-sciences-and-healthcare-analytics-certification-programme

    ReplyDelete
  14. it's really cool blog. Linking is very useful thing.you have really helped
    360digitmg data science course

    ReplyDelete
  15. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites
    Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  16. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips.highly informative and professionally written and I am glad to be a visitor of this perfect blog, thank you
    selenium training in chennai

    selenium training in chennai

    selenium online training in chennai

    software testing training in chennai

    selenium training in bangalore

    selenium training in hyderabad

    selenium training in coimbatore

    selenium online training

    selenium training

    ReplyDelete
  17. Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes .

    angular js training in chennai

    angular training in chennai

    angular js online training in chennai

    angular js training in bangalore

    angular js training in hyderabad

    angular js training in coimbatore

    angular js training

    angular js online training

    ReplyDelete
  18. I think it's awesome someone is finally taking notice of our vet's and doing something to help them. I hope all goes well with these articles. More new information i will get after refer that post.


    AWS Course in Bangalore

    AWS Course in Hyderabad

    AWS Course in Coimbatore

    AWS Course

    AWS Certification Course

    AWS Certification Training

    AWS Online Training

    AWS Training

    ReplyDelete
  19. I think it's awesome someone is finally taking notice of our vet's and doing something to help them. I hope all goes well with these articles. More new information i will get after refer that post.
    acte chennai

    acte complaints

    acte reviews

    acte trainer complaints

    acte trainer reviews

    acte velachery reviews complaints

    acte tambaram reviews complaints

    acte anna nagar reviews complaints

    acte porur reviews complaints

    acte omr reviews complaints

    ReplyDelete
  20. Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.

    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training


    ReplyDelete
  21. Am Divya,Am really impressed about this blog because this blog is very easy to learn and understand clearly.This blog is very useful for the college students and researchers to take a good notes in good manner,I gained many unknown information.

    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete
  22. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    Java training in bangalore
    Java institutes in bangalore

    ReplyDelete