Skip to main content

Section 12.14 Step 3: Crafting Examples

Having understood the specification (Step 0), defined our internal data representation (Step 1), and established the class structure (Step 2), we now arrive at Design Recipe Step 3: Examples & Tests. The core idea of this step is to solidify our understanding of exactly how each method should behave by creating concrete examples before we write the implementation code. These examples serve multiple purposes:
  • They force us to think through specific scenarios, including typical usage, edge cases, and error conditions.
  • They clarify any remaining ambiguities in the specification.
  • They provide precise targets for our implementation logic (Step 5).
  • They form the basis for the automated unit tests (discussed in the next section) that verify our code.
As recommended in the Design Recipe guide (See SectionΒ 1.7), using a structured format helps ensure thoroughness. For each key operation, we should consider: Case Type, State Before, Action, and Expected Result (State After / Return Value / Exception), based on the ListADT Javadoc. We’ll structure each example clearly below using lists and paragraphs for readability.

Note 12.14.1. State Representation.

We’ll represent the conceptual list state like this: [A, B, C] (size=3). When thinking about the internal array, we might visualize it as array=[A|B|C|null] (size=3, cap=4).

Subsection 12.14.1 1. Examples for Adding Elements

Subsubsection 12.14.1.1 add(int index, T item)

Examples for addFirst and addLast follow directly from the index 0 and index size cases above.

Subsection 12.14.2 2. Examples for Removing Elements

Subsubsection 12.14.2.1 remove(int index)

Subsubsection 12.14.2.2 removeFirst() / removeLast()

Subsubsection 12.14.2.3 remove(T item)

Subsubsection 12.14.2.4 clear()

Subsection 12.14.3 3. Examples for Other Operations

We must create similar detailed examples for the remaining methods (get, set, first, last, indexOf, contains, isEmpty, size), always considering:
  • Empty list cases
  • Single-element list cases
  • Multi-element list cases (typical usage)
  • Boundary indices (0 and size()-1)
  • Error conditions specified in the Javadoc (invalid indices, empty lists, null arguments).
  • Specific scenarios for search methods (item present, absent, null).
Thinking through these examples systematically is crucial for ensuring our implementation will be correct and robust.
Example for first() Error Case:
Example for get() Error Case:
These concrete examples define the target behavior for our ArrayList<T>. They specify precisely what should happen for various inputs and states. In the next section, we’ll discuss how the provided unit tests automate the process of checking whether our eventual implementation meets these behavioral examples.
You have attempted of activities on this page.