Aggregation vs. composition

R

Rick Osborn

I got asked at an interview lately if I knew the difference between
aggregation and composition. We were discussing possible changes to
a struts application, and how I would modify the code. He then made the
parallel to A vs C. If I would deisn go to either paradigm.

Not knowing this off the top of my head, he and the team looked
at me in disgust and walked me out.

I looked this up when I got home, and could do this in design
discussions, or over iterative revisions. But at moment, off the top
of my head?

Am I missing the boat, or were they setting the bar a tad high?
 
S

Sudsy

Rick said:
I got asked at an interview lately if I knew the difference between
aggregation and composition. We were discussing possible changes to
a struts application, and how I would modify the code. He then made the
parallel to A vs C. If I would deisn go to either paradigm.

Not knowing this off the top of my head, he and the team looked
at me in disgust and walked me out.

Sounds like the one about "which pattern would you choose in
this scenario?"
It also sounds like a bunch of people so wedded to buzzwords
that you (or at least I) wouldn't be happy there anyway.
Give me a real problem, along with a few minutes to consider
the possibilities, and I'll tell you what approach I'd use.
Ask me to name a pattern from a book? Please!
As to this particular question, I'm not sure that I know the
definition of either off the top of my head. Isn't an essay
a form of composition? Or a symphony? Isn't an aggregate
something you use to make concrete?
Just for laughs, enter the following string into your favorite
search engine:
+aggregate +concrete +composition
Kind of puts a different spin on things, eh?
 
M

Marc Dzaebel

Rick Osborn said:
... he and the team looked at me in disgust and walked me out.
... Am I missing the boat, or were they setting the bar a tad high?

I don't know the exact conditions of the interview, however, IT is too
complex to know everything. UML is getting a standard so the question is
rather a basic one if the team works e.g. on web architectures. I'd guess
the most IT experts don't know it and this kind of "knowledge" is certainly
not the only think. The team shows at least a human evidence of incapacity.
 
I

Ike

I agree with sudsy, it's pure nomenclature, and wont solve real problems,
which, to me anyways, there is never a shortage of. However, in answer to
your question, this should help:


Composition
Writing a class that contains objects as other members, like 'Birthday'
which is a Date object, say, in class Employee.

Composition and Inheritiance imply different relationships:

Composition - One class has another class.

Aggregation - One class is a kind of another class.

Oftentimes, it is not so clear cut.



-Ike
 
M

Michael Borgwardt

Ike said:
I agree with sudsy, it's pure nomenclature, and wont solve real problems,

Having a common nomenclature *does* make solving problems easier.
Composition
Writing a class that contains objects as other members, like 'Birthday'
which is a Date object, say, in class Employee.

Composition and Inheritiance imply different relationships:

Composition - One class has another class.

Aggregation - One class is a kind of another class.

Aggregation has NOTHING to do with inheritance! In fact, Composition
is merely a special case of aggregation in which the life cycle of
the "part" is controlled by the whole.

This difference is indeed quite academic, and using it as the deciding
question in an interview indicates that the interviewer has wrong
priorities.
 
M

Marc Dzaebel

I completely agree with your comments. However, Rick already "looked it up"
so *he* don't need an explanation ;-)
 
R

Rick Osborn

No, I'd say you're all basically in line with what I was thinking.
In my nearly 8 yrs (it sounds some of you even more) yes, I got home and
found the "answer" in my trusty UML Distilled book.

But thanks to you all, you did confirm my suspicions. These guys
are focused my on terms than solutions.
 
B

BarryNL

Rick said:
I got asked at an interview lately if I knew the difference between
aggregation and composition. We were discussing possible changes to
a struts application, and how I would modify the code. He then made the
parallel to A vs C. If I would deisn go to either paradigm.

Not knowing this off the top of my head, he and the team looked
at me in disgust and walked me out.

I looked this up when I got home, and could do this in design
discussions, or over iterative revisions. But at moment, off the top
of my head?

Am I missing the boat, or were they setting the bar a tad high?

Well, it depends what you said you knew before the interview. If you
told them you knew UML, for example, then you should certainly be able
to explain the difference between Agg. & Comp. It's not really standard
Java stuff though. In Java Agg., Comp. and normal 1-M assocs would
probably all be implemented as a Vector or ArrayList, for example.
 
B

BarryNL

Ike said:
I agree with sudsy, it's pure nomenclature, and wont solve real problems,
which, to me anyways, there is never a shortage of. However, in answer to
your question, this should help:


Composition
Writing a class that contains objects as other members, like 'Birthday'
which is a Date object, say, in class Employee.

Composition and Inheritiance imply different relationships:

Composition - One class has another class.

Aggregation - One class is a kind of another class.

Composition indicates that the child objects are conceptually a part of
the parent and make no sense on their own. A typical example might be
objects 'Invoice' and 'InvoiceLines', where invoice lines are clearly a
part of an invoice and would never exist without being part of (and thus
linked to) an invoice. Composition indicates that the child objects are
wholly dependent on the parent for their existance and indicate to a
developer that they should code the parent in such a way that, for
example, if the parent is deleted it ensures all children are also deleted.

Composition is far more strict than a simple 'HASA' relationship.
 
N

nos

BarryNL said:
Well, it depends what you said you knew before the interview. If you
told them you knew UML, for example, then you should certainly be able
to explain the difference between Agg. & Comp. It's not really standard
Java stuff though. In Java Agg., Comp. and normal 1-M assocs would
probably all be implemented as a Vector or ArrayList, for example.

--
sun tutorial has aggregation and composition here

http://onesearch.sun.com/ClickThru?qt=aggregation&url=http://developer
s.sun.com%2Fevents%2Ftechdays%2Fpresentations%2Fseattle%2FJ2EEandAdvancedFea
tures.pdf&pathInfo=%2Fsearch%2Fdevelopers%2Findex.jsp&hitNum=8&col=javatecha
rticles&col=javatutorials&col=devall&col=devarchive&col=javadoc
 
Joined
Aug 30, 2009
Messages
1
Reaction score
0
Composition - has a relationship - one class has another class's object which is created itself inside the class method, constructor, or as a instance of that class.
Ex.
Code:
class A{ }
class B {  //class B has A.
    A a=new A(); /* this is composition. [COLOR=red]A[/COLOR] has no  
                        life after [COLOR=red]B[/COLOR] class's instance is 
                       set to null(Of course you have to create [COLOR=red]B[/COLOR] class's 
                       instance first.) */
}
Aggregation - has a relationship(same as composition but with little difference) - one class has another class's object but through pass by value of reference of object.
Ex.
Code:
class A{ }
class B{
A a=null; // class B has A.
B(A a){ // this is aggregation. Object [COLOR=red]A[/COLOR] can have a life even after 
// [COLOR=red]B[/COLOR] class's instance is set to null. ( of course here also you 
// have to create [COLOR=red]B[/COLOR] class's instance first )
this.a = a;
}
public String getObject(A a){ // this is aggregation. 
return a.toString();
}
}
 
============End Aggregation=============================
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class Test {
 static BufferedWriter bw=null;
 static StringBuffer sb=new StringBuffer();
 private static ArrayList<String> array=new ArrayList<String>(); //testing
 
 public static void main(String[] args) {
  try {
   bw = new BufferedWriter(new FileWriter((new Long(new Date().getTime()).toString())));
   String path = "p1//InformationTechnologyEmployee.java";
   method(path);
   for(int i=0;i<array.size();i++){
    
   }
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    bw.write(sb.toString());
    bw.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 private static void method(String path) {
  if (path != null || path.length() > 0) {
   try {
    BufferedReader br = new BufferedReader(new FileReader(path));
    String eachLineReadInFile = null;
    ArrayList<String> arrayListOfInstanceVariable = new ArrayList<String>();
    HashMap<String,String> hmClassNameWithClassPath = new HashMap<String,String>(); // [class name=key] & [class path=value] 
    while ((eachLineReadInFile = br.readLine()) != null) {
     String previousLine = new String(eachLineReadInFile);
     String newline = new String(eachLineReadInFile.replaceAll("package|return|import|this|[{]|[}]|[/]|
[*]|final", ""));
     if (eachLineReadInFile.indexOf("import") > -1) {
      String filteredClassName = eachLineReadInFile.substring(eachLineReadInFile.lastIndexOf(".") + 1, eachLineReadInFile.length() - 1);
      String filteredClassPath = eachLineReadInFile.replaceAll("import|[;]","").replaceAll("[.]", "//").trim();
      hmClassNameWithClassPath.put(filteredClassName, filteredClassPath);
     }
     if (!newline.equals(eachLineReadInFile))
      continue;
     System.out.println(previousLine);
     if (previousLine.trim().replaceAll("[;]", "").length() != 0){
      String instanceVariable = previousLine.trim().replaceAll("[;]|public|static|protected|private","");
      arrayListOfInstanceVariable.add(instanceVariable.trim());
     }
    }
    System.out.println(arrayListOfInstanceVariable);
    String classs = path.substring(path.lastIndexOf("//")+2,path.lastIndexOf("."));
    String classReference = Character.toLowerCase(classs.charAt(0))+classs.substring(1);
    String createNewInstance = classs+" "+classReference+" = new "+classs+"();\r";
    array.add(classs.toLowerCase());
    sb.insert(0,createNewInstance);
    for (int nextInstance = 0; nextInstance < arrayListOfInstanceVariable.size(); nextInstance++) {
     String previousDataTypeOfInstanceVariable = (String) arrayListOfInstanceVariable.get(nextInstance);
     String newDataTypeOfInstanceVariable = new String(previousDataTypeOfInstanceVariable.replaceAll(
       "int|float|byte|long|String|boolean|double", ""));
     String methodName = Character.toUpperCase(previousDataTypeOfInstanceVariable.split(" ")[1].charAt(0))+previousDataTypeOfInstanceVariable.split(" ")[1].substring(1);
     if (newDataTypeOfInstanceVariable.equals(previousDataTypeOfInstanceVariable)) {
      String className = newDataTypeOfInstanceVariable.split(" ")[0];
      String passingReference = Character.toLowerCase(previousDataTypeOfInstanceVariable.split(" ")[0].charAt(0))+previousDataTypeOfInstanceVariable.split(" ")[0].substring(1);
      sb.append(classReference+".set"+methodName+"("+passingReference+");\r");
      if(className.indexOf("List")>-1){
       System.out.println("className before "+className);
       className = className.split("[<]|[>]")[1];
      }
      if(!hmClassNameWithClassPath.containsKey(className)){
       String pathForSamePackageVariable=path.substring(0,path.lastIndexOf("//")+2)+className;
       hmClassNameWithClassPath.put(className,pathForSamePackageVariable);
      }
      String instanceRef = (String) hmClassNameWithClassPath.get(className);
      method(instanceRef + ".java");
     }else{
      if(previousDataTypeOfInstanceVariable.indexOf("String")>-1){
       passArgument(classReference, createNewInstance, methodName,"(null)"); 
      }else{
       if(previousDataTypeOfInstanceVariable.indexOf("boolean")>-1){
        passArgument(classReference, createNewInstance, methodName,"(false)");        
       }else{
        passArgument(classReference, createNewInstance, methodName,"(0)");
       }
      }
     }
    }
   } catch (Exception e1) {
    e1.printStackTrace();
   }
  } else {
   return;
  }
 }
 private static void passArgument(String classReference, String createNewInstance, String methodName, String argument) {
  sb.insert(createNewInstance.length(),classReference+".set"+methodName+argument+";\r");
 }
}
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top