In my developments I am slowly moving from an object-oriented approach to interface-based-programming approach. More precisely:

  • in the past I was already satisfied if I could group logic in a class
  • now I tend to put more logic behind an interface and let a factory create the implementation

A simple example clarifies this.

In the past I wrote these classes:

  • Library
  • Book

Now I write these classes:

  • ILibrary
  • Library
  • LibraryFactory
  • IBook
  • Book
  • BookFactory

This approach allows me to easily implement mocking classes for each of my interfaces, and to switch between old, slower implementations and new, faster implementations, and compare them both within the same application.

For most cases this works very good, but it becomes a problem if I want to use iterators to loop over collections.

Suppose my Library has a collection of books and I want to iterator over them. In the past this wasn't a problem: Library::begin() and Library::end() returned an iterator (Library::iterator) on which I could easily write a loop, like this:

for (Library::iterator it=myLibrary.begin();it!=mylibrary.end();++it) ...

Problem is that in the interface-based approach, there is no guarantee that different implementations of ILibrary use the same kind of iterator. If e.g. OldLibrary and NewLibrary both inherit from ILibrary, then:

  • OldLibrary could use an std::vector to store its books, and return std::vector::const_iterator in its begin and end methods
  • NewLibrary could use an std::list to store its books, and return std::list::const_iterator in its begin and end methods

Requiring both ILibrary implementations to return the same kind of iterator isn't a solution either, since in practice the increment operation (++it) needs to be implemented differently i

Edit
Report