Solution Manual
Solution Manual
1
1 Chapter 1
Question 1.
Answer The players would be users who actually use the system, analysts, designers, implemen-
tors, testers, etc. The users would worry about the interface, speed, and correctness. The analysts
would be concerned about the requirements and the designers would consider the environment
(hardware, software) in which the system will be implemented and come up with the approach for
realizing the required functionality. The implementors would be focused on translating the speci-
fications into correct code. The testers will check the correctness of the code at unit, subsystem,
and system levels.
Question 3.
Answer A class is an ADT. By appropriately specifying the access specifiers, one can encapsulate
the data.
Question 5.
Answer There would be no coupling, but the code would not be cohesive.
2 Chapter 2
Question 1.
Answer
Question 3.
2
Answer The use case is given below.
3 Chapter 3
Question 2.
Answer This assumes that Rectangle has a constructor that takes the length and width as
paramaters of type double.
4 Chapter 4
Question 2.
2. The objects would be made available in the order in which they were stored. Thus, the system
would first deliver the instance of C1 and then the instance of C2.
3. The code throws exceptions. They need to be caught or shown as thrown from main.
A revised code is given below. There are obviously different ways to handle the exceptions.
import java.io.Serializable;
public class C1 implements Serializable {
}
import java.io.Serializable;
public class C2 implements Serializable {
}
import java.io.*;
public class C3 {
public static void main(String[] s) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream("f1");
oos = new ObjectOutputStream(fos);
} catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
C1 c1 = new C1();
C2 c2 = new C2();
try {
oos.writeObject(c1);
oos.writeObject(c2);
} catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
try {
FileInputStream fis = new FileInputStream("f1");
ObjectInputStream ois = new ObjectInputStream(fis);
C1 anotherC1 = (C1) ois.readObject();
C2 anotherC2 = (C2) ois.readObject();
} catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(0);
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
System.exit(0);
4
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
}
}
The following code embellishes C1 and C2 to verify that the code works.
import java.io.Serializable;
public class C1 implements Serializable {
String s1;
public C1() {
s1 = "Hello";
}
public String toString() {
return s1;
}
}
import java.io.Serializable;
public class C2 implements Serializable {
String s1;
public C2() {
s1 = "Bye";
}
public String toString() {
return s1;
}
}
import java.io.*;
public class C3 {
public static void main(String[] s) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream("f1");
oos = new ObjectOutputStream(fos);
} catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
C1 c1 = new C1();
C2 c2 = new C2();
try {
oos.writeObject(c1);
oos.writeObject(c2);
5
} catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
try {
FileInputStream fis = new FileInputStream("f1");
ObjectInputStream ois = new ObjectInputStream(fis);
C1 anotherC1 = (C1) ois.readObject();
C2 anotherC2 = (C2) ois.readObject();
System.out.println(anotherC1);
System.out.println(anotherC2);
} catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(0);
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
System.exit(0);
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
}
}
Question 4.
Answer Suppose you need to accept numbers from the keyboard. The user may type in, by
mistake or intent, non-numeric characters. If this is not caught, the program will crash. See the
code below.
import javax.swing.*;
public class ExampleChapter4Problem5 {
public static void main(String[] s) {
int value = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
Run the above program and type in non-numeric input. The program will crash. The following fix
would catch bad input values.
import javax.swing.*;
public class ExampleChapter4Problem5 {
public static void main(String[] s) {
String input = null;
try {
input = JOptionPane.showInputDialog("Enter a number");
6
int value = Integer.parseInt(input);
} catch(NumberFormatException nfe) {
System.out.println("Bad input " + input);
System.exit(0);
}
}
}
5 Chapter 5
Question 2.
Answer The following class implements the interface and has some code to do some basic testing.
import java.util.*;
public class MyListImplementation implements MyList {
private LinkedList list = new LinkedList();
// add at the tail
public void add(Object object) {
list.add(object);
}
// add at the given position
public void add(Object object, int index) {
list.add(index, object);
}
// delete and return the element at the given position;
// return null if no such element exists
public Object delete(int index) {
return list.remove(index);
}
// return the number of elements in the list.
public int size() {
return list.size();
}
// return an object of type java.util.ListIterator
public ListIterator listIterator() {
return list.listIterator();
}
public static void main(String[] s) {
MyList aList = new MyListImplementation();
aList.add("El");
aList.add("E3");
aList.add("E5");
aList.add("E2", 1);
7
aList.add("E4", 3);
aList.add("E0", 0);
ListIterator iterator = aList.listIterator();
while (iterator.hasNext()) {
Object o = iterator.next();
System.out.println(o);
}
System.out.println(aList.size());
System.out.println(aList.delete(2));
iterator = aList.listIterator();
while (iterator.hasNext()) {
Object o = iterator.next();
System.out.println(o);
}
}
}
Question 5.
Answer The following class shows how to implement a list of Student objects. Other lists are
similar.
import java.util.*;
public class StudentList {
private static List studentList = new LinkedList();
public static void add(Object object) {
studentList.add(object);
}
public static void add(Object object, int index) {
studentList.add(index, object);
}
public static Object delete(int index) {
return studentList.remove(index);
}
public static int size() {
return studentList.size();
}
}
Question 7.
Answer Suppose that f is a method in the adaptee that needs to be hidden. Java does not
provide a direct way of making an implementation of any method of the adaptee unavailable. But
we could do the following in the class adapter.
8
public class ClassAdpater extends Adaptee {
public void f() {
}
// other methods not shown
}
The code simply does nothing, so in effect the implementation of the adaptee is unavailable.
It is more tricky if f returns something. If it returns an object, the adapter’s implementation could
simply return null. Otherwise, an arbitrary primitive value could be returned.
6 Chapter 6
Question 1.
Answer In Table 6.4, remove the phrase “It then displays the book’s title and due date” from
Item 7. In Item 9, replace the phrase “otherwise it exits” by “otherwise it displays the title and
due-date of all the books checked out, and exits.”
Question 2.
Answer Examples of these would be: get a list of overdue books; get a list of members who have
more than, say, eight books; get a list of members who have not checked out any book in the last
year, etc.
Question 3.
Answer We would, among others, need use-cases to (i) add a room; (ii) view properties of a
room; (iii) change properties of a room;
Use case for (iii) would have the following steps: 1. User makes a request.
2. System asks for the ID of the room
3. User inputs ID.
4. If no such room exists, system prints an error mesg and exits. Otherwise it displays a list of
properties of the room and asks the user to select one that needs changing.
5. User responds appropriately.
6. System displays a list of options for that property and asks the user to select one.
7. User responds appropriately.
8. System applies relevant Business Rules to determine if the change is acceptable. If so, it prints
a confirmation and exits. If not, it shows the error mesg and asks the user if they would like to try
another option. 9. User responds appropriately. 10. System goes to Step 6.
9
Question 4
Answer
1. In what format would dates be entered? Also, the user may enter invalid data such as
wrongly-formatted date. What happens then?
2. Consider all situations where errors may occur and decide what to do in each case.
3. List the nouns: request, expenditure item, description, date, amount, data, income item, and
user. Using the approach for eliminating nouns, we are left with expenditure item and income
item as two possible classes. These will have description, amount, and date as fields.
Question 5
Answer Obviously, there are many possibilities for each of the scenarios.
1. While creating a new policy, the system may ask at first receive the user’s name, address, and
other contact details. After receiving this, the system prompts for the details of each driver:
name, driver’s license number, etc. That requires a loop. A second loop is then needed to
input the details of each vehicle that requires insurance. For each of the vehicles, the make,
model, year, deductible, etc. must be input. Finally, the system computes the premium and
outputs that and the policy number.
2. The system could ask for the policy number and then the details of the new driver who should
be added to the policy. The revised premium is the final output.
4. The system may ask for the policy number and then the details of the accident. Sometimes
the amount the user may claim would not be computed at this time.
Question 6.
Answer (a) No; supermarkets typically do not keep track of information about customers
(b) No; vegetable is a broad category, not an individual item.
(c) Yes. Assuming there is only one kind of milk; otherwise each kind of milk would constitute a
different class and there would be no class for milk in general.
(d) No. As a noun, stock would refer to the amount in stock for a particular product; this would
be an attribute of a class.
(e) No. This is a general category.
(f) No; this would be an attribute.
Question 9.
10
Answer (a) Functional; the business needs a system that does this.
(b) Non-functional; typically such requirements exist across all systems.
(c) Non-functional; the choice of a language does not affect system behavior.
(d) Functional;the business needs a system that does this.
(e) Functional; this is not a business requirement but something needed for ease of use and therefore
a function asked for by the client.
Question 10.
Answer This will require a use-case “Search external collections”. The system will ask for infor-
mation about the book (title, author) and may also provide a selection of external collections from
which to search. When completed, the system will report the name of a collection, if any, where
the book was found. There will be multiple instances of the Catalog class needed to facilitate this.
Question 11.
Answer Yes. Supermarkets typically need to keep track of how the payment was made.
Question 12.
Answer No. Our assumption here is that the clerk is just a proxy for the person interacting with
the system. We have only one kind of user.
Question 13.
Answer One advantage is that the choice of implementation be deferred. This can reduce costs
of the analysis if we later choose not to implement a feature. Another advantage is that when the
implementation is changed, the analysis need not be repeated, enabling reuse.
7 Chapter 7
Question 2.
Answer UI handles the look and feel, whereas business logic deals with the underlying imple-
mentation.see section 7.1.1.
Question 3.
11
Answer In the Member class, because all the data needed for the computation is stored there.
Question 4.
Answer As an example, consider Book Checkout. Member would return the ID; the method
in Library will invoke search on MemberList to get a ref to the member object, etc. Such an
implementation will give us safer code which is more stable for the long run, but will be slower.
Question 5.
Answer Hold needs the memberID and the bookID. This will have similar consequences to what
we saw in Question 4.
Question 6.
Answer The way to construct this is to combine a Class Adapter with an Object Adapter Define
the class SafeMember that extends Member. Member also has the following method:
private SafeMember makeSafeMember(){
return(new SafeMember(this));}
The class SafeMember redefines all the modifiers of Member to do nothing, and returns null references
for all accessors that return references to other objects in the system.
8 Chapter 8
Question 4.
Answer The key type would have to be fixed. If, say, the key type is String, the interface would
be:
public interface Matchable{
public Boolean matches(String other)
}
Such an arrangement has the drawback that interface cannot be reused. If we had two classes, one
of which has a key of type String and other has a key of type Integer, we would have to define two
interfaces.
Question 6.
Answer This would be used in a situation where we are using a set of named constants to repre-
sent a set of discrete entities. This would not be applicable if these constants represent numerical
12
values that are used in computations. The process would involve the following steps:
(a) Identify the named constants that can be grouped into a single class
(b) Identify an ordering that could be useful.
(c) Define an enum class to contain all the named constants in the preferred order.
(d) Locate all occurrences of the named constants when they appear as actual parameters in a
method call. Modify the formal parameter list to reflect the new enum class.
(e) Locate all occurrences of the named constants when they appear in a return statement of a
method. Change the return type of the method. Locate all places in the code where a call to the
method occurs and appropriately modify the type of the variable that receives the result of the
method call.
Question 7.
Answer This would require modifying the use case described in Table 6.4. One approach would
be simply disallow checkouts when there are outstanding fines; in that case we will need another
use case for paying fines.
Step 5: If the ID is not valid, the system prints an appropriate error and exits the use case. If the
user has unpaid fines, the system prints a message displaying the amount of fine and exits the use
case; otherwise the system asks for the ID of the book.
An alternate approach would be one where the system allows the clerk to collect the fine, and
records the receipt of the fine before proceeding with the checkout.
9 Chapter 9
Question 1.
Answer Under the circumstances it would be inappropriate to create a common superclass for
CDs and DVDs. The only polymorphism that system needs to support is for LoanableItem. If, for
some reason, we need to treat the collection of CDs and DVDs separately from all the others, such
a superclass may be appropriate.
Question 2.
Answer If the subclass threw exceptions that the superclass did not, then it would not be possible
to substitute a subclass instance for a superclass instance. This would therefore violate LSP.
Question 3.
13
Answer Note that a student could move back and forth between being a Weakstudent and a
Student when their GPA fluctuates. This suggests that creating a subclass to model this behavior
is not a good idea. There are two possible patterns that could be applied in such a situation. The
Decorator Pattern is the best approach to handling this; this requires an abstractStudent which
could be configured with a decorator that enforces the weakness property. The State Pattern (see
Chapter 10) could also be used to model the Student as a Finite State Machine with two states:
Regular and Weak.
Question 4
Answer Let Ellipse have methods setFoci(Point a, Point b), setMajorAxis(float a) and
float getEccentricity(). (The eccentricity of an ellipse, is the ratio of the distance between the
two foci, to the length of the major axis.) The function distance(Point x, Point y) returns the
euclidean distance. Consider the client method:
float f(Ellipse e)
{
Point a(-1,0);
Point b(1,0);
e.SetFoci(a,b);
e.setMajorAxis(6.0)
float d = distance(a,b);
return d/e.getEccentricity();
}
Regardless of how we implement, the eccentricity of the circle is zero. The above method will
therefore throw an ArithmeticException if we pass a Circle as the parameter. On the other hand,
the an Ellipse will never trigger this exception.
Question 6.
Answer The program as written does not generate any output; if we replace the Rectangle
constructor by a Square constructor the program will always print “Error”. Thus we have an LSP
violation.
10 Chapter 10
Question 3.
...
If door is greater than zero and doorClosed is true, action corresponding to door opening is taken;
likewise, if door equals zero and doorClosed is false, action corresponding to door opening is taken.
Otherwise ChangeEvent is ignored.
The GUI handles these exactly as it would have handled the corresponding button clicks. In the
initial design, the GUI will simply call the processDoorOpen or processDoorClosed methods. In
the second approach, the handleEvent method is invoked with the appropriate parameter. If we
have event objects, then the constructor is invoked and the object is passed to the event manager.
Question 4.
Answer One option is that the context could be completely unaware of the states. In such a
situation, each state would be aware of all the possible next states that the system could transition
to, and context would only serve as a repository of shared information.
The third approach is where the context keeps track of all the states and the transitions. The state
makes a call to the run method of the current state; when the state completes execution, it returns
an exit code to the context. The context then decides the next state based on the current state
and the exit code.
Question 6.
Answer (a) This will require the addition of a new event that will be handled only by the
cookingState.
(b) The clear button introduces a new event. Remembering the remaining time could be handled
in one of two ways:
(1) By storing the remaining time in the context. CookingState would first get the remaining time;
if this was zero it would set it to 60.
(2) By adding new states: InterruptedDoorOpen, InterrutedDoorClosed and ResumeCooking.
15
(c) This would be implemented by having a method in the GUI that is invoked from the appropriate
state.
11 Chapter 11
Question 2.
Answer The View does not know the type of the Item. In order to invoke the correct draw
method on the UIcontext, View would have to determine the type of the Item and downcast it.
This would involve having some RTTI in View. Such an approach would hurt reuse since any
modifications to the Item hierarchy would require modifying the code in View. In addition, there
would be a long conditional statement in View to deal with each object in the Item hierarchy.
The View would also have to distinguish between complete and incomplete versions of items which
would cause very tight coupling between View and Model.
Question 4.
Answer The View should provide some mechanism for the user to choose the line thickness. The
thickness would be stored as a field in the line object and the draw method would have to be
modified to draw lines of varying thickness.
Question 7.
Answer The Item hierarchy is extended so that Line has a subclass EquationLine. The View
allows the user to specify a line by the equation. Based on the coordinates of the origin and
coefficients of the equation, the View computes the coordinates of two points that lie on the line.
The View then notifies the controller, which adds an EquationLine object to the Model. The draw
method of EquationLine gets the dimensions of the drawing panel from the UIcontext and draws
the required line.
Question 10.
Answer The View receives the command to draw the curve, and the mouseclicks that define
the points. The View remembers the coordinates of the first mouseclick. The controller adds an
IncompleteBspline item to the Model and adds points to this object as they are received. Let
P0 , P1 , . . . Pk be the points added so far. The draw method of the incomplete item draws the B-
spline curve segments associated with the following k − 2 sequences of points:
P0 , P1 , P2 , P3
P1 , P2 , P3 , P4
...
16
Pk−3 , Pk−2 , Pk−1 , Pk
When the user clicks again on the first point, the View informs the controller that the item has
been completed. The Controller accordingly replaces the IncompleteBspline item with a Bspline
item. If a total of k points were clicked, the draw method of the Bspline will draw the following 3
additional curve segments:
Pk−2 , Pk−1 , Pk , P0
Pk−1 , Pk , P0 , P1
Pk , P0 , P1 , P2
12 Chapter 12
Question 1.
Answer Sketch Since UserInterface makes calls to methods in Library, it is better to make
the Library methods remote and leave the other classes unchanged. To handle concurrency, one
could have each remote method of Library be synchronized. Then, only one site will be able to
do a library operation at any given point in time.
Question 3.
Answer Sketch Suppose each line in the screen represents one book and let us assume that there
are n books displayed. For each line, have an extra field, which the user can fill with a letter (say,
Y) to indicate that that book is to be placed on hold. The code can then look at each of these
entries in turn to decide whether it should be processed. This would also require that the server
remember the books on display.
17
http://www.springer.com/978-1-84996-521-7