wasnt nate

Programming Is Easy, Accept the Pattern

No matter what the programming problem is there is a very consist pattern that will nearly every time.

-       A data set and zero or more flags will be provided by something
-       The code will enumerate the data set
-       If something is true, do something else do another thing
-       Return and exit

First you are always given a data set. This will always be one or more objects to act on along with a collection of flags to tweak behavior. The object represents “something” such as a Person. These objects will then have properties such as Name and Age.

In coding terms we would represent this
For C as
typedef struct
char* Name;
int Age;
} Person, *PPerson;

Or Java/C# with
class Person
public String Name;
public int Age;

Next the code will need to enumerate the data set; this is done typically in a “for-loop.” For example assume that our program is to act on a collection of People. We may end up with the following-

Person[] people = DoSomethingThatFindsPeople();
for(int index=0; index<people.length; index++){
// look at me, I’m walking the list
Person duder = people[index];

Console.WriteLine(“The person is named “+ duder.Name);

In the above snippet we find an enumerable called people that consists of zero or more people. The code then creates a variable called “index” which holds the present index. We will increase index until it reaches the same value as end of list. It will step at a rate of +1 each iteration.

For each step it is going to create a variable called “duder.” This is going to be set equal to the item in the people collect at index “index”. Once this is created just write to the screen the person’s name. Once it is out of items to process we will move on to the next part.

If the dataset had been given to us instead of querying the setup would be the nearly the same pattern.

void WriteTheNameOfEveryone(Person[] people)
for(int index=0; index<people.length; index++){ …

Next the coder needs to add logic in the “for-loop body” to handle if then do this otherwise do that. These are typically expressed as some form of if-else branch construct.

Continuing with the Person example; let’s say the goal is to make a function that verifies someone is old enough to make a purchase.

void CardThem(Person[] people){
foreach(Person duder in people) { // another variant of for-loop, in many languages not all
if(duder.Age >= 21){
Console.WriteLine(duder.Name + “ is old enough to buy booze”);
} else if( duder.Age >= 18){
Console.WriteLine(duder.Name + “ can buy smokes”);
} else {
Console.WriteLine(duder.Name + “ should goto Disney land”);

This snippet would be passed the data set people, then enumerate then one “duder” at a time. If that “duder” was 21+ sell him booze. If he’s not then check if he’s at least 18 and sell him smokes. If he’s not not 18 then kick him out before the cops come.

Leave a Reply