Hi, this is an IBM sample test question: 16) In design #1, the Catalog object has a getProducts() method, which returns a collection object, such as a Dictionary or array, containing all the Products the company sells. In design #2, the Catalog object has a getProductNumbered(anIdentifier) method, which returns the Product with the specified unique identifier. Considering the objects returned, which of the following BEST characterizes the two designs? a) Both designs maintain the objects' encapsulation and reduce coupling by accessing state data via methods only and not directly. b) Both designs break the objects' encapsulation, adding brittle coupling. c) Design #1 breaks the encapsulation of the Catalog, adding brittle coupling. Design #2 maintains the encapsulation of the Catalog, making future design changes easier. Why is the answer C. Why not B. How can we improve this design?
Ram Dhan Yadav (SCJP, SCWCD, SCJA-I, IBM EC(483))
"We are what we repeatedly do. Excellence, then, is not an act, but a habit."
(a) is not correct. Accessing state data via methods only does not gurantee encapsulation. If the object being returned is not immutable (read-only); then the client program calling those methods may be able to modify the state of Catalog. Now we're left with (b) & (c). (b) came out second BEST because the statement doesn't say which object's encapsulation was broken. In (c), it clearly said it wanted to know which design broke the encapsulation of Catalog. Under that context, design #1 is the culprit as it lost control of its aggregates by returning them to client. e.g. The client has to write its own code to traverse the collection looking for a particular product when searching for products is clearly a responsibility of catalog. Looking at the design issues from a bigger picture; it doesn't really mean that design #1 is to be avoided. Just look at javax.servlet.http.HttpServletRequest which has these methods:
Pho [ March 08, 2002: Message edited by: Pho Tek ]