[Prog] Separating mechanism from policy (microscopical view) – function implementation.

Separating mechanism from policy is very important issue of SW design.
This is also true for microscopic area – implementing function.
Here is one of simplest example – function that calculates area of rectangle.

int rect_area(int left, int top, int right, int bottom) {
        return (right - left) * (bottom - top);
}

Simple, isn’t it?
But, this function doesn’t have any exception/error handling.
Let’s add some of them.

int rect_area(int left, int top, int right, int bottom) {
        if (left >= right)
                left = right;
        if (top >= bottom)
                top = bottom;
        return (right - left) * (bottom - top);
}

It’s seems good.
Soon after, another function that calculates area of rectangle is needed.
But, this function should return error value if input rectangle is invalid.
I think quick solution is

int rect_area2(int left, int top, int right, int bottom) {
        if (left > right || top > bottom)
                return -1;
        return (right - left) * (bottom - top);
}

But, in this solution, code for calculating area of rectangle is duplicated.
At above example, this is just one-line code. So, duplicating is not a big deal.
But, it’s not good in terms of code structure.
Why did this happen?
Calculating rectangle area is ‘Mechanism’.
But, exception/error handling is ‘Policy’ at this example.
So, above example should be implemented like below.

static inline int _rect_area(int left, int top, int right, int bottom) {
        return (right - left) * (bottom - top);
}

int rect_area(int left, int top, int right, int bottom) {
        if (left >= right)
                left = right;
        if (top >= bottom)
                top = bottom;
        return _rect_area(left, top, right, bottom);
}
int rect_area2(int left, int top, int right, int bottom) {
        if (left > right || top > bottom)
                return -1;        
        return _rect_area(left, top, right, bottom);
}

Can you know the difference?
‘_rect_area’ is implementation of pure ‘Mechanism’.
And policy is implemented at each interface function.
Even for simple function, developer should consider CONCEPT of separating Mechanism from Policy.