August 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Working With Design Patterns: Iterator

  • July 9, 2008
  • By Jeff Langr
  • Send Email »
  • More Articles »

Listing 2: SequenceTest

import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;

public class SequenceTest {
   private List<Integer> ints;

   @Before
   public void createCollection() {
      ints = new ArrayList<Integer>();
   }

   @Test
   public void singleEntry() {
      verifySequence(new Sequence(0, 0), 0);
   }

   @Test
   public void twoEntries() {
      verifySequence(new Sequence(1, 2), 1, 2);
   }

   @Test
   public void multipleEntries() {
      verifySequence(new Sequence(5, 10), 5, 6, 7, 8, 9, 10);
   }

   @Test
   public void negativeNumbers() {
      verifySequence(new Sequence(-2, 2), -2, -1, 0, 1, 2);
   }

   @Test
   public void increment() {
      verifySequence(new Sequence(0, 5, 2), 0, 2, 4);
   }

   @Test
   public void incrementIncludesLimit() {
      verifySequence(new Sequence(0, 6, 2), 0, 2, 4, 6);
   }

   private void verifySequence(Sequence sequence,
      int... expectedValues) {
      for (int i: sequence)
         ints.add(i);
      assertEquals(expectedValues.length, ints.size());
      for (int i: expectedValues)
         assertTrue(ints.contains(i));
   }
}

What's the value? It affords more concise code, and there are benefits of Sequence being an object. You can pass around a sequence (and persist it), as opposed to having to pass around discrete numbers representing the range and other information, such as the step value. You also could extend its capabilities without altering code that uses a sequence. For example, you could provide the ability to suspend a sequence, and later have it resume where it left off.

Iteration is one of the more prevalent operations in computing. It's fitting that you find as concise, consistent, and expressive a manner to accomplish it. Sun has produced three Java collection iteration mechanisms to date, improving the solution each time. No doubt, you'll see another mechanism in the not-too-distant future.

About the Author

Jeff Langr is a veteran software developer with over a quarter century of professional software development experience. He's written two books, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. Jeff has contributed a couple chapters to Uncle Bob Martin's upcoming book, Clean Code. Jeff has written over 75 articles on software development, with over thirty appearing at Developer.com. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft dot com.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel