Let's look at why the functional style of programming helps us be more productive than the imperative alternative.
Nearly all computer hardware is designed to execute machine code, which is native to the computer, written in the imperative style. The program state is defined by the contents of memory, and the statements are instructions in the machine language where each statement advances the state of computation forward, toward a final outcome. Imperative programs change their state over time, step by step. High-level imperative languages, such as C and Go, use variables and more complex statements, but they still follow the same paradigm. Since the basic ideas in imperative programming are both conceptually similar to low-level code that operates directly on computer hardware, most computer languages--such as Go, also known as C of the 21st century--are largely imperative.
Imperative programming is a programming paradigm that uses statements that change a program's state. It focuses on the step-by-step mechanics of how a program operates.
The term is often used in contrast to declarative programming. In declarative programming, we declare what we want the results to be. We describe what we want, not detailed instructions of how to get it.
Here's a typical, imperative way to find Blazer in a slice of cars:
var found bool
carToLookFor := "Blazer"
cars := []string{"Accord", "IS250", "Blazer" }
for _, car := range cars {
if car == carToLookFor {
found = true; // set flag
}
}
fmt.Printf("Found? %v", found)
Here's a functional way of accomplishing the same task:
cars := []string{"Accord", "IS250", "Blazer" }
fmt.Printf("Found? %v", cars.contains("Blazer"))
That's nine lines of imperative code, compared to two lines in the functional programming (FP) style.
Functional constructs often express our intent more clearly than for loops in such cases and are especially useful when we want to filter, transform, or aggregate the elements in a dataset.
In the imperative example, we must code the how. We must:
- Declare a Boolean flag
- Declare and set a variable value
- Create a looping structure
- Compare each iterated value
- Set the flag
In the functional example, we declare what we want to do. We are able to focus on what we want to accomplish, rather than bloating our code with the mechanics of looping structures, setting variable values, and so on.
In FP, iteration is implemented by the library function contains(). Leveraging library functions means that we code less and allow library developers to focus on highly efficient implementations, which have been typically vetted and performance enhanced by seasoned professionals. We don't have to write, debug, or test such high-quality code for repetitive logic.
Now, let's look at how we could look for Blazer using the object-oriented programming paradigm:
type Car struct {
Model string
}
accord := &Car{"Accord"}; is250 := &Car{"IS250"}; blazer := &Car{"Blazer"}
cars := []*Car{is250, accord, blazer}
var found bool
carToLookFor := is250
for _, car := range cars {
if car == carToLookFor {
found = true;
}
}
fmt.Printf("Found? %v", found)
First, we declare our object types:
type Car struct {
Model string
}
type Cars []Car
Next, we add our methods:
func (cars *Cars) Add(car Car) {
myCars = append(myCars, car)
}
func (cars *Cars) Find(model string) (*Car, error) {
for _, car := range *cars {
if car.Model == model {
return &car, nil
}
}
return nil, errors.New("car not found")
}
Here, we declare a global variable, namely myCars, where we will persist the state, that is, the list of cars that we will build:
var myCars Cars
Add three cars to the list. The Car object encapsulates the data for each object, and the cars object encapsulates our list of cars:
func main() {
myCars.Add(Car{"IS250"})
myCars.Add(Car{"Blazer"})
myCars.Add(Car{"Highlander"})
Look for Highlander and print the results:
car, err := myCars.Find("Highlander")
if err != nil {
fmt.Printf("ERROR: %v", car)
} else {
fmt.Printf("Found %v", car)
}
}
We are using car objects, but we are essentially doing the same operations as we were in the simple imperative code example. We do have objects that have state and to which we could add methods, but the underlying mechanisms are the same. We assign a state to object properties, modify the internal state by making method calls, and advance the state of execution until we arrive at the desired outcome. That's imperative programming.