I have to iterate over specific points of perimeter rectangle (in some cases I need to iterate over one line of this rectangle, In other cases I need to iterate over entire rectangle). I have an interface PointIterator.
struct Point
{
double x,y
}
class PointIteratorI
{
virtual void next() =0;
virtual void isOver() =0;
virtual Point& getPoint() = 0;
}
in case of iterating over one line
class LineIterator:public PointIterator
{
....
}
in case of iterating over rectangle's perimeter
class PerimeterIterator:public PointIterator
{
....
}
In case of LineIterator I also need the type of line (horizontal or vertical, the rectangle have 2 horizontal and 2 vertical lines). But interface like "getLineType" is wierd for LineIterator type. It seems like this method is not for this class. Because in such a case the class LineIterator will be responsible for iterating and direction. It's breaking Single-responsiblity principle.
I thought for different Interface like:
class LineObjectI
{
public:
virtual LineType getLineType() = 0;
.....
}
class LineIterator:public PointIterator, public LineObjectI
{
protected:
virtual LineType getLineType() = 0;
....
}
for hiding this interface. I want to know is there a better way to do to check type of line on LineIterator.
I am going to argue for a different solution. Throw inheritance out.
Start with
boost::any
orstd::any
. Then add in type erasure.Here are 3 operations you need for an iterator:
Now turn those operations into a proper iterator with a little fascade:
Live example.
boost
provides a similar system of type-erased iterators to a typeT
.In general, this technique has performance implications, as following all those function pointers on every increment compare and dereference adds up.
Iterating over the permiter isn't a type of iteration, it is a range of iteration.
Same for iterating over a side (line) of the figure.
There are 3 ways to iterate over the perimeter. First, iterate over the lines in the perimeter, which then iterates over the points.
Second, iterating over the points of the perimeter.
Third, iterate over a pair of (side_type, point) or (side, point) where side has a property side_type.
This results in iteration that is compatible with range-for loops and C++ algorithms, removes the requirement to use smart pointers, and lets you treat your iterators as value-types. It moves the type system out of the way: the only thing that you have a type for is the thing you are iterating over, not the details of how you are walking.