Search code examples
javadesign-patternsiteratorextractorreader

Design pattern for consecutive object value extractor


Consider an object that extracts object values from a source on a "pull" basis, until a special value (e.g., null) is encountered.

In Java, the API could be something like

  public interface ValueExtractor<T> {
    public T extractNext();
  }

Operationally, this is an Iterator but it only has a (sort of) "next()" method and is not a Reader since it does not read from the source byte-by-byte. It also resembles a database cursor in the sense that it "scrolls" over all data values (records), until they are exhausted.

Is there a design pattern other than "iterator" for this use case?

What would be the best name to call such a simple object?


Solution

  • This is an Iterator. Just because it doesn't follow the java.util.Iterator interface does not mean it doesn't follow the Iterator Design Pattern.

    The only difference is you have only a single method that combines fetching the next element and checking if there is a next object to fetch. I assume you return null if there are no more elements.

    Whether you have separate hasNext() and fetchNext() methods or if you combine them into a single method that returns null is an API decision and does not change the fact that you are following the Iterator Design Pattern.

    However, from an API naming convention point of view, if you choose to have all the Iterator methods combined into a single fetchNext() method, you should not have the word "Iterator" in your class name since that could cause confusion from users of your code that your class implements the java.util.Iterator interface.

    It doesn't really matter what you name your class otherwise so I would go with naming it based on whatever data it is iterating over.

    EDIT Since you say in your OP:

    It also resembles a database cursor in the sense that it "scrolls" over all data values (records), until they are exhausted.

    You can probably name it something like ScrollableRecords