Specifying a Bag

In this lesson, we will explore the purpose of each method in the class BagOfStrings.

Methods of the class BagOfStrings

The previous lesson chose the behaviors, or responsibilities, for the class BagOfStrings. Each of these responsibilities will be carried out by a method of our class. Before we implement the class, we need to specify exactly—and in detail—what each of the methods that correspond to the bag’s behaviors will do.

We’ll name the methods, choose their parameters, decide their return types, and write comments to fully describe their behaviors. Our goal, of course, is to write a Java header and comments for each method, but first, we will express the methods in pseudocode.

Bag capacity and size

The first two behaviors on our CRC card give rise to two methods that return either the bag’s capacity or a count of its current contents. Each of these methods has no parameters and returns an integer. In pseudocode, we have the following specifications:

// Returns the capacity of this bag.

// Returns the current number of strings in this bag.

We can write the following Java headers for these methods:

/** Gets the capacity of this bag.
    @return the integer number of strings that this bag can hold. */
public int getCapacity()

/** Gets the current number of strings in this bag.
    @return the integer number of strings currently in this bag. */
public int getCurrentSize()

Get hands-on with 1200+ tech skills courses.