Why?
Some time ago, while I was working on a project, that was a top secret project so cannot give more details :), I realized that I've produced some sort of weird code that checks if an interval (Start, Stop integer value pair) intersects with another interval. Right after unit testing and committing the code, I felt like there is something wrong with me. Here are the details.
Nothing Fancy
Here is the code of my Interval structure. There is nothing fancy about this structure. It is used to hold two integer values and performs range checking in the constructor to guarantee that start value is always smaller or equal to stop value.
[code=cs;ln=on;]public struct Interval
{
private int _startValue;
public int StartValue
{
get { return _startValue; }
private set { _startValue = value; }
}
private int _stopValue;
public int StopValue
{
get { return _stopValue; }
private set { _stopValue = value; }
}
public Interval(int startValue, int stopValue)
{
if (startValue > stopValue)
throw new TypeInitializationException("Interval",
new Exception("Provided start value is greater than the provided stop value."));
_startValue = startValue;
_stopValue = stopValue;
}
public bool IntersectsWith(Interval interval)
{
}
}
Conventional Way
The conventional way of implementing that IntersectsWith
method is to:
- write some
if
/else
blocks or - to combine a single
return
statement to cover all of the cases illustrated in the following image:
My Problem
But somehow, I did not choose the conventional implementation and I decided, in fact by reflex, to re-model Interval objects as rectangles with 1px in height, place them on xy coordinate system and check if two rectangles intersect or are tangent to each other. Here is my weird IntersectsWith
implementation:
public bool IntersectsWith(Interval interval)
{
Rectangle r1 = new Rectangle(StartValue, 0, StopValue - StartValue, 1);
Rectangle r2 = new Rectangle(interval.StartValue, 0,
interval.StopValue - interval.StartValue, 1);
return r1.IntersectsWith(r2) || (r1.X + r1.Width == r2.X) || (r2.X + r2.Width == r1.X);
}
Questions to Myself
- Is this weird implementation a result of too much analytical thinking?
- Is this weird implementation a result of too much abstract modeling I have to do to perform my job well?
- Shall I see a therapist?
- Is this weirdness a common pattern among developers?
- Shall I ask this as an interview question? And what shall I do with people implementing this method like me and not like me?
- How will my colleagues feel when they have to read my weird
IntersectsWith
implementation? - Shall I be ashamed of myself?
CodeProject