I am writing a custom container class. A constituent object is created independently of the container, and can be a member of no container or multiple containers. The container’s public API should support three operations:
- iteration over all objects
- insertion of a new object
- removal of an existing object
The container does some additional work, and its precise implementation may change.
How can I write the public API to this class so that it remains stable as I change the implementation?
If the container is list-like, efficient removal requires the knowledge of the object’s index; knowing the object itself is no good (I don’t want to search the whole container for the element).
If the container is set-like, there’s nothing equivalent to the index, and I need the object itself.
If the container is like a singly linked list, I need some kind of a reference to the object preceding the object being removed.
If the container is like a doubly linked list, I need a reference to the object itself.
I am thinking to have the removal method take a single argument reference, which has no meaning or use outside of the removal method. The iteration would yield a pair of (object, reference).
Is there any problem with this design? Is there an example or design pattern I can look up?
Ideally, I would rather have the iteration yield a complex object that contains both the original object and the reference, and exhibits the interface of both. But I don’t suppose this is doable?
Here’s what I’ll do unless someone else helps by finding a better solution:
If I then decide to change the implementation from
listto some other data structure, the public interface can remain unchanged:Or…