Over a million developers have joined DZone.

Making Mock Data Circular

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

Was writing a test today where I was doing a Command Pattern that would allow me to contain a set of repeated invocations in a timebox. In other words: call me as many times as possible in x milliseconds. So for the test, I was using random #s, but that kept going to zero after a ton of invocations. Got out my Distribution class that allows me to say 'give me random #s with x% in range between y and z.' Once I do that, though, I have to know how many #s I am going to need, and I don't really.

First, I did the usual TDD thing: write it and let it fail. Sure enough, it fails on .next() after the iterator is exhausted. Did some searches on whether there is a reset method on some specialized iterator. But then, I decided it would just make more sense to make a simple CircularIterator, like so:

/**
* Provides the ability to give a fixed sample, and this class will provide an
* {@link Iterator} that will just repeatedly loop through the collection.
*
* @author Rob
*
* @param
* @Pattern Decorator
*
*/
public class CircularIterator implements Iterator {

/**
* Just using a real iterator here, after running through the set each time.
*/
private Iterator i;

/**
* The sample we want to cycle through.
*/
private Collection collection;

public CircularIterator(Collection collection) {
this.collection = collection;
this.i = collection.iterator();
}

/**
* Will always return true, since we are just looping.
*/
public boolean hasNext() {
return i.hasNext();
}

/**
* Gets the next element. If there are no more, the iterator {@link #i} is
* recreated.
*/
public T next() {
if (!i.hasNext())
i = collection.iterator();
return i.next();
}

/**
* Just proxies call so should work as usual.
*/
public void remove() {
i.remove();
}

}

 

Of course, this means that you are going to just get the same #s over and over again, but in a lot of cases (like mine), that doesn't really matter: scores, confidence levels, donations, whatever.

This is a good example of the Decorator pattern: it implements the interface, holds an instance of the type it's extending, and proxies on the methods it doesn't need to change. The nice part is that I can just create this, using the same declarations and then call next() for as long as I like.

From http://www.jroller.com/robwilliams

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}