There is a technique called programming by intention. I came across this term for the first time from netobjectives.com. I'm not sure it is a well-known term or not. But, the idea about this technique is pretty strong and effective. There are many benefits you can get by doing this. I'll mention about these benefits later.
My understanding of this technique is to lay out the steps or process first and finish implementation later. This keeps your thinking process and coding staying on track. It is like writing a pseudo code, but it is writing actual codes. I guess the best way to explain this technique is using example.
Let's say you are writing a function called 'whatTypeOfTriangleIsThis(int a, int b, int c)' and this will return some numeric value representing certain type of triangle. If you write this in one function, you will have to use a lot of if statements. And you will keep thinking about cases to cover. But soon yon can figure out how to group them and handle them in each group, that's the idea. Let me lay out the steps
1. Are inputs valid? If not -1
2. Can inputs make triangle? If not -1
3. Is this equilateral? If yes 1
4. Is this isosceles? If yes 2
5. Is this scalene? If yes 3
I could write this function like
public int whatTypeOfTriangleIsThis(int a, int b, int c){
if(!areInputsValid(a,b,c) || !canInputsMakeTriangle(a,b,c))
return -1;
if(isThisEquilateral(a,b,c))
return 1;
else if(isThisIsosceles(a,b,c,))
return 2;
else return 3;
}
Now I go back to each private method and implement the rest.
I'll comeback for more explanation.
Bye.
No comments:
Post a Comment