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.

22 comments:

  1. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    Personal Installment Loans
    Title Car loan
    Cash Advance Loan

    ReplyDelete
  2. 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
  3. 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
  4. The Mobile Accessories is a largest mobile retail Chain dealing in leading international and Indian Brands of mobile phones and accessories headquartered with using special offers and low cost of the latest branded mobile phones. This is amazing offers with some of days.

    Mobile Showrooms in OMR

    ReplyDelete
  5. I’ve been browsing on-line greater than three hours today, but I never discovered any attention-grabbing article like yours. It is beautiful worth sufficient for me. Personally, if all webmasters and bloggers made good content material as you did, the net will be a lot more helpful than ever before.
    Software Testing Training in Chennai
    SEO Training in Chennai
    Informatica Training in Chennai
    Digital Marketing Training in Chennai

    ReplyDelete
  6. Good work…unique site and interesting too… keep it up…looking forward for more updates.Good luck to all of you and thanks so much for your hard-work.
    Language Interpretation Services, Voice Over Services India

    ReplyDelete
  7. This is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    Language Translation Services ,
    Subtitling Companies in Bangalore

    ReplyDelete
  8. I am very happy when read this blog post because blog post written in good manner and write on
    good topic. Thanks for sharing valuable information.

    School Information Management System,
    Online Fee Payment Integration
    College Management System

    Message

    ReplyDelete
  9. Thanks for sharing the information.Impressive and i would like to share this with my friends
    Indian Cyber Army’s most awaited internship is live now. Summer Internship 2018 on “ Ethical hacking” and book your seats before it runs out.Candidates have to get themselves registered to be a part of this Internship program. Here internship will give you on-the-job experience, help you learn whether you and Cyber security industry are a good match and can provide you with valuable connections and references. Here interns are usually exposed to a wide variety of tasks and responsibilities which allows the intern to showcase their strengths by working on projects for various managers that work on different parts of Indian Cyber Army. Becoming a high performing intern is a fantastic way to improve your employment prospects. This internship can be a great way to get your foot in the door of success with a prestigious or desirable Organization.As career in ethical hacking is most in demand.

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

    ReplyDelete
  11. 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
  12. nice post.thanks for sharing the more valuable information.
    Indian Cyber Army credibility in Ethical hacking training & Cybercrime investigation training is acknowledged across nation as we offer hands on practical knowledge and full assistance with basic as well as advanced level ethical hacking & cybercrime investigation courses. The training is conducted by subject specialist corporate professionals with wide experience in managing real-time ethical hacking/ cyber security projects. Indian Cyber Army implements a blend of academic learning and practical sessions to give the candidate optimum exposure.Ethical hacking training ,
    Ethical hacking course

    ReplyDelete
  13. Thanks for such important information.keep up the good work.Searching for partners to romance typically through dating websites, apps or even social media can lure you into scammers trap pretending to be prospective companions. They play on emotional triggers to induce you to provide money, gifts or personal details.Read More : Dating scams

    ReplyDelete
  14. I have really happy to these reading your post. This product control and maintenance of our health.The daily routine can assist you weight lose quickly and safely.My life is completely reworked once I followed this diet.I feeling nice concerning myself.

    Herbalife in Chennai
    Herbalife Nutrition Products
    Nutrition centers in Chennai
    Weight Loss in Chennai
    Weight Gain in Chennai

    ReplyDelete
  15. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  16. Great post. Needed to write simple word that Thanks for suggestions. Keep it up! best sap simple finance online training institute in hyderabad

    ReplyDelete

  17. BIG DATA Technologies provides you with a state of the art software which combines modern GPU technology (Graphic Processing Units) with the best practices in today’s Big Data platforms, providing up to 100x faster insights from data.
    Bigdata Training in Chennai OMR

    ReplyDelete
  18. myTectra Placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance

    ReplyDelete