I want to write a class which offers two sequences of elements to its users. The first one (lets call it "primary") is the main of the class and will be use 80% of the time. The second one (lets call it "secondary") is less important, but still need to be in the same class. The question is: what interface should the class offer to its users?
By looking at STL style, a class with a single sequence of elements should offer begin() and end() functions for traversal and function like insert() and erase() for modifications.
But how should my class offer the second sequence?
For now, I have two ideas:
- Expose the two containers to the user (what about the Law of Demeter ?)
- Provide the main container with STL interface and expose only the second one.
Here is an example.
#include <vector>
class A {
public:
std::vector<int>& primary();
std::vector<char>& secondary();
private:
std::vector<int> m_primary;
std::vector<char> m_secondary;
};
class B {
public:
std::vector<int>::iterator begin();
std::vector<int>::iterator end();
std::vector<char>& secondary();
private:
std::vector<int> m_primary;
std::vector<char> m_secondary;
};
// Classes implementation
// ...
int main() {
// --------------------------------------------------
// Case 1
// --------------------------------------------------
A a;
for(auto it = a.primary().begin(); it != a.primary().end(); ++it) {
// ...
}
for(auto it = a.secondary().begin(); it != a.secondary().end(); ++it) {
// ...
}
// --------------------------------------------------
// Case 2
// --------------------------------------------------
B b;
for(auto it = b.begin(); it != b.end(); ++it) {
// ...
}
for(auto it = b.secondary().begin(); it != b.secondary().end(); ++it) {
// ...
}
}
What is the more C++ish way to do that? Is one best than the other or is there an other solution?
Context
This problem came in the context of an exercise in which I am writing a simple database access framework. Here are the classes involved in the question:
- table
- column
- row
- field
The table class consists of a sequence of columns and an other sequence of rows. The main use of the table is manipulating (access, add and remove) the rows.
Deeper in the hierarchy, a row is made of column and field so a user can ask the value (field) corresponding to a given column or column name. Each time a column is add/modify/remove from the table, every rows will need to be modify to reflect the modification.
I want the interface to be simple, extensible and combining well with existing code (like STL or Boost).