Today I needed to implement a class for representing rectangular regions with some binary operations such as merging or intersection.
public class Region
{
// Properties, such as top-left and bottom-right corner ...
// Ctors ...
public Region Merge(Region other)
{
// ...
}
public Region Insersect(Region other)
{
// ...
}
}
Intersecting two instances of Region
unfortunately does not always have a useful result. So my next step was to implement the notion of a NullRegion
. It is no problem to implement the NullRegion
itself. However, this would require Region
to check against NullRegion
, as those binary operations are commutative and the order should not matter. (i.e. nullRegion.Intersect(nonNullRegion)
should yield the same result as nonNullRegion.Intersect(nullRegion)
, which is a NullRegion
)
The first solution I can think of is to move the implementation of those methods into a seperate class. That way, I only the new class needs to know the NullRegion
.
public class Region
{
// Properties, such as top-left and bottom-right corner ...
// Ctors ...
public virtual bool IsNull { get { return false; } }
public Region Merge(Region other)
{
return RegionMethods.Merge(this, other);
}
public Region Intersect(Region other)
{
return RegionMethods.Intersect(this, other);
}
private class NullRegion
{
public override bool IsNull { get { return true; } }
}
private static class RegionMethods
{
public static Region Merge(Region Region, Region otherRegion)
{
// ...
}
public static Region Intersect(Region Region, Region otherRegion)
{
// ...
}
}
}
Is this a good way to tackle the problem? What would be my alternatives?
NullArea
at all? Isn't the intersection of two non-overlapping rectangles just a 0x0Area
and not a "lack" of anArea
? This could mean it's just a problem ofArea
!=RectangleCoordinates
and the need for different representations of each. – Ocelot20 Dec 8 '14 at 2:08Region
. – conrad Dec 8 '14 at 2:27NullRegion
is a region not having an area and not having any coordinates. Probably the best example is the intersection of two non-intersectingRegion
s. Users of my class should always be able to check if the givenRegion
is aNullRegion
by callingregion.IsNull
. The coordinates do not really matter, possibly one should even throw anInvalidOperationException
when trying to access the coordinates of theNullRegion
, as it does not have defined coordinates. However, users should still be able to perform reasonable computations with theNullRegion
, such as merging. – conrad Dec 8 '14 at 19:43Region
s are made up of points and theNullRegion
is theRegion
containing no points at all. – conrad Dec 8 '14 at 19:47