Java Reference
In-Depth Information
1.6
The first behavior on our CRC card gives rise to a method that returns a count of the current num-
ber of entries in the bag. The corresponding method has no parameters and returns an integer. In
pseudocode, we have the following specification:
// Returns the current number of entries in the bag.
getCurrentSize()
We can express this method using UML as
+getCurrentSize(): integer
and add this line to a class diagram.
We can test whether the bag is full or empty by using two boolean-valued methods, again with-
out parameters. Their specifications in pseudocode and UML are
// Returns true if the bag is full.
isFull()
// Returns true if the bag is empty.
isEmpty()
and
+isFull(): boolean
+isEmpty(): boolean
We add these two lines to our class diagram.
1.7
We now want to add a given object to the bag. We can name the method add and give it a parameter
to represent the new entry. We could write the following pseudocode:
// Adds a new entry to the bag.
add(newEntry)
We might be tempted to make add a void method, but if the bag is full, we cannot add a new entry
to it. What should we do in this case?
Design Decision: What should the method add do when it cannot add a new entry?
Here are two options that we can take when add cannot complete its task:
Do nothing. We cannot add another item, so we ignore it and leave the bag unchanged.
Leave the bag unchanged, but signal the client that the addition is impossible.
The first option is easy, but it leaves the client wondering what happened. Of course, we could
state as a precondition of add that the bag must not already be full. Then the client has the responsi-
bility to avoid adding a new entry to a full bag.
The second option is the better one, and it is not too hard to specify or implement. How can we
indicate to the client whether the addition was successful? The standard Java interface Collection
specifies that an exception should occur if the addition is not successful. We will leave this
approach for later and use another way. Displaying an error message is not a good choice, as you
should let the client dictate all written output. Since the addition is either successful or not, we can
simply have the method add return a boolean value.
Thus, we can specify the method add in UML as
+add(newEntry: T): boolean
where newEntry 's data type is the generic type 1 T .
1.
Appendix C reviews generic types in Java.
 
 
Search WWH ::




Custom Search