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.
'Essay > Software' 카테고리의 다른 글
[Essay] SW 엔지니어 역량 측정 - 02 (0) | 2011.06.01 |
---|---|
[Essay] SW 엔지니어 역량 측정 – 01 (0) | 2011.05.31 |
[Essay] SW 엔지니어 역량 측정 - 00 (0) | 2011.04.22 |
[Essay] 기술면접에서의 질문방법에 대한 단상 (0) | 2011.03.25 |
[Essay] SW영역에서 Role and Responsibility를 정의하는 두 가지 방법에 대한 비교/단상... (0) | 2011.03.02 |