Suppose I have two containers of elements:
std::vector<std::string> foo = { "aa", "bb", "cc" };
std::vector<std::string> bar = { "dd", "ee" };
I pass around indecies into foo
and bar
between many classes that operate on these two containers. However, I find that I have to be very careful not to confuse which indecies are associated with which container, and sometimes fail in this and then have a lot of trouble finding logical errors that result.
So, suppose I have two indecies:
int id_foo = 1;
int id_bar = 0;
Is there a simple design pattern which helps prevent cases where I try to call bar[id_foo]
by "binding" id_foo
to foo
.
Basically, I'm trying to figure out the simplest way to disambiguate between foo
and bar
. I could create separate classes for each and then just define iterators into those classes. But I would like to avoid creating a separate class for every container like foo
and bar
for which I want this "safety".
The question is asking for something like "index safety" (analogous to type safety). The way I'm currently accomplishing this is by naming my indecies in such a way as to indicate which container they are associated with.
There isn't really a design pattern for differentiating what an index indexes into. There are some conventions.
You could use typedefs to differentiate them. That is, typedef an int
to be a FooIndex
, and similarly for a BarIndex
. You could also use a bit of Hungarian notation for the names (I know people hate that, but this sort of thing is really what it was intended for). You already seem to be using some of it, but not in a useful way. Consider this naming convention:
int fooCurrentKey = 1;
int barCurrentKey = 0;
This lets you know that the first index is for list foo
and the second is for list bar
.