Programming Thoughtsart 1

Strategy to Expand Reach

Define the problem

Many times programmers just start coding. They'll figure out where they're going on the fly. That only works with rather narrow solutions. If your task has a lot of branching or options, the setup is all important. You best have a plan.

Example of a Thought Process

Let's say you have a cost that has a percentage tax encluded and you want to find the origianl price. The first step is to analyze the givens and find some sort of algorithm that gives you a truth. The final cost is the sum of the original price plus the original price times the tax rate. Let's use $56 and a tax rate of 4%. Then x + .4x = 56 satisfies our algorithm. 1.4x = 56, x = 40. That's it. Forty was the original price. Let's check. $40 + ($40 x 4%) is 40 + 16 = 56. Our algorithm was true. Now we can program a function to back-out the price.

Branching and Options

Options can best be approached with a switch statement. Branching can get complicated from contional statements to determine when to branch. While statements are usually the answer but what do you use for the condition? The problem is the program's polling interval that will repeat. The same while loop will run again and you've already branched and don't need to do that again. You want to stay at the branched location and do something else. You can return later into the main branch.

Semaphores and Gates

Semaphores or flags and gates are variables that are modified inside your while loop to keep the while loop from repeating with a new polling interval, therefore, they have to be global in scope or outside the scope of the controlling while loop. Flags can be defined globally and match the while loop condition so the while loop runs. The first time the while loop is reached, the flag is true. Then during the loop, this flag is set so it's untrue when the while loop tries to run again. This can be as easy as:

let flag=1;
while(flag){ ...do something, flag=0;}

Or you could branch through options that only run once:

let flag;
let gate1 = 1;
let gate2 = 1; // boolean true
switch(flag) {
   case 1:
     while(gate1) {...do something, gate1=0; break;} // gate could be: while(gate1 < 3), then gate1++; to loop 3 times.
   case 2:
     while(gate2) {...do something, gate2=0; break;}    break;
   default: break;
}

Now the controlling code can manipulate the flags and control the branching and the times the while statements run.

Get a Plan of Action

The main point here is to plan out when and where your program needs to go to accomplish a task with options and times thing need to only run once, or need be, run muliple times within a given polling cycle before you start coding.