Monday, November 30, 2009

Structured (procedural) VS Non-Structured Programing

Here are a couple wikipedia links to start off.

Most people learn to program the "Non-Structured" way. It's more simple to implement, easier to understand, and a great starting point for new programmers. However, the simplicity is often it's downfall. And more complicated tasks will likely be hindered by the lack of modularity and ridiculous looping or duplicated code.

Take, for instance, the Fibonacci sequence. Imagine trying to implement that without any procedures (functions). It might look something like this:

#include 

int main()
{
int y=0,z=0;
for(int i=0; i < 10; ++i)
{
if (i == 0)
y = 0;
if (i == 1)
y = 1;
z = z + y;
y = z - y;
std::cout << z << std::endl;
}
return 0;
}


I shudder to think of how that would look if I didn't make use of the for loop. And even with it, there are needless variables. When looking at the alternative which uses procedural programming...

#include 

int fib(int);

int main()
{
int y=0,z=0;
for(int i=0; i < 10; ++i)
{
std::cout << fib(i) << std::endl;
}
return 0;
}


int fib(int number)
{
if (number == 0)
return 0;
if (number == 1)
return 1;
return fib(number - 1) + fib(number - 2);
}

Though it may not be immediately obvious, this is a better solution. The fib function allows you to pick any number in the sequence. Also, it off loads the bulk of the work to a separate entity, which makes it easier to change. If I wanted to make it faster, I could simply add a static vector to hold the previously calculated numbers. If I wanted to allow for larger Fibonacci numbers, I could change the return type to an unsigned int, or a long long, or an unsigned long long. The possibilities for expansion are only limited by your needs.

However, structured programs can sometimes add more complexity than is necessary. For instance, what if all you wanted to do was write a short hello to whoever in the world may be running your program? This seems like a great way to do it:

#include 

void output(string);

int main()
{
output("Hello World!");
return 0;
}

void output(string message)
{
std::cout << message << std::endl;
}


Yeah no. Why do you need another function to do what is already part of the output library? And if you only wanted to print "Hello World!" it would be much simpler to do this:

#include 

int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}


In short, the style of programing you use for any given project should depend on the goals. If you want to get a small program done quickly and or statically, there is no reason to use structured programming. But if you have a large project that changes requirements and flow, the more structured styles will suit it better.

0 Comments:

Post a Comment

<< Home