Sample midterm 2 - Question 2

49 views
Skip to first unread message

cs 210

unread,
Apr 26, 2011, 12:59:22 AM4/26/11
to UBC CPSC 210
Shouldn't there be a department parameter in the constructor of
Employee? due to Department 1 ------ n Employee

When a class should have a collections field such as a set suggested
by the UML diagram is it also necessary to include a remove, get
methods as well in the implementation for questions such as Question
2? In the solutions provided I realized that only an add method is
usually provided.

Thank you.

Paul Carter

unread,
Apr 26, 2011, 2:51:42 AM4/26/11
to ubc-cp...@googlegroups.com

> Shouldn't there be a department parameter in the constructor of
> Employee? due to Department 1 ------ n Employee
>

You can certainly take that approach - this would guarantee that each Employee is associated with a Department from the time that the Employee object is instantiated. In the case of 1-to-many associations, if the many end of the association is 1..*, then you would certainly want to ensure that there is at least one item in the collection at all times.

> When a class should have a collections field such as a set suggested
> by the UML diagram is it also necessary to include a remove, get
> methods as well in the implementation for questions such as Question
> 2? In the solutions provided I realized that only an add method is
> usually provided.

I omitted the getter methods as they are fairly trivial. That said, they would likely be included in the final implementation of these classes assuming that such functionality is required. An alternative to providing a getter method for the Department class would be to provide an iterator so that a client can iterate over the collection of Employee objects.

You would include remove methods only if this was a requirement of the system. With bi-directional associations you have to be careful when implementing remove methods - if you remove an Employee from a Department you must also be sure to set the Department for that Employee to null or to the new Department to which that Employee is assigned.

Paul

cs 210

unread,
Apr 26, 2011, 3:10:45 AM4/26/11
to UBC CPSC 210
Makes sense. Thank you :)
Reply all
Reply to author
Forward
0 new messages