Paradigms: An innovative avenue to coding

St. Petersburg College has certificates and degrees to prepare you for a career in Computer Programming. Believe it or not, there are different ways of writing programs. We often refer to them as paradigms.

Generally, we will classify them as imperative (Procedural and Object-Oriented) and functional. Most of the programming languages that are familiar to many, are mainly imperative, I.e. Java, C#, and Python. However, the functional features are being increasingly added to these languages.

An imperative language is characterized by code that changes the values of variables as the program executes. We refer to the variable values as the state of the program. Essentially, the goal of an imperative program is to manipulate the state of variables until some desirable outcome is reached.

On the other hand, functional programming eliminates the concept of state. Instead, we think in terms of functions and evaluations of those functions. We write programs by composing functions and making larger functions from them. Let’s look at an example of procedural code. Consider the problem of summing all the even numbers between 1 and 10. We would write the following procedural code:

total=0

for n in range (1,11):

if n % 2 =0:

total +=n

print (total)

Here our goal is the total and we constantly manipulate the state of the total variable until we reach our goal. Notice that we didn’t use any objects as a part of our code. Now, we can rewrite our code and make use of the object oriented features of Python.

evens=list()

for n in range (1,11):

if n % 2 =0:

evens.append(n)

print(sum(evens))

In this snippet, we create a list object to store our even numbers and then we reiterate over the range, by adding the even numbers to the list as we find them. At the end, we pass the entire list to the sum function.

The two code examples both produce the same result. However, instead of changing the value of the variables directly, the second version manipulates the state of the list object. WE could take it a step further and enclose the code in a class that inherits from the list and add a sum method to that class.

Without going too much in-depth into functional programming in this blog entry, I just want to give you a quick taste. We could write the same code using Python list comprehensions like the following:

Sum(n for n in range (1,11) if n% 2 =0})

Now, we are no longer manipulating any state. This version of our code is also more readable. We eliminated all the boilerplate code associated with the loop. This allows us to express our program in terms of what we want more so than in terms of how to do it.

I hope this has peaked your interest in functional programming. This is one in a series of blogs about coding. Stay tuned for more!

Leave a Reply

Your email address will not be published. Required fields are marked *