Functional programming vs. object-oriented: the basics

0

Engaging in a programming paradigm is an important step in any application development effort. While they are hardly the only two options when it comes to overall development models, the choice between functional programming and object-oriented programming is a choice that a growing number of developers are faced with today.

Object-oriented programming is a widely accepted approach to development and often underpins the structured programs that most developers learn to write early in their careers. Many of these languages ​​include elements that are almost indistinguishable from functions, but they fall far short of the mechanisms behind a purely functional programming language such as Haskell.

In this article, we’ll go over the main differences between functional and object-oriented programming, offer a few examples of how they work, and go over the considerations that matter most when choosing between these coding paradigms.

Functional or object-oriented programming methods

In essence, functional programs behave like common mathematical functions, such as the calculations behind a conversion from Celsius to Fahrenheit. With functions, the same inputs systematically lead to the same result. A “pure” function is deterministic and will not produce side effects – in other words, it will always return the same value when called and will not change anything outside of its scope or parameters.

An incredibly powerful example of the functional method is Google’s implementation of MapReduce and its approach to returning results to certain search terms. MapReduce connects search terms as key / value pairs using a function called reduce. This process aggregates the terms and assigns each a value that will indicate what type of result it should return. With the same set of data, Google will spit out the same answer every time with no side effects.

On the other hand, object-oriented programming can contain state dependent variables, which means that objects do not necessarily maintain consistent values. For example, if you call a method that returns a salary, you can recover $ 50,000. But if you run a method that adds 10% to that total and then request the salary again, the returned value is $ 55,000. Object oriented programs can also contain things like global variables and static variables which will make the responses to queries different each time.

To add state to functional programs, use a programming language that is not purely functional, such as F #. You can also add functions to a more traditional program such as LINQ.

Code examples for functional programming versus object-oriented programming

The following is sample code for functional programming with the FizzBuzz F # coding challenge. FizzBuzz is a common coding test where developers create a program that prints a series of letters and numbers based on a set of simple rules. First, if the number is divisible by three, print the word Sparkle in its place. Then, for numbers divisible by five, replace the word Buzz. Finally, if the number is divisible by three and by five, print FizzBuzz. In a functional language, such as F #, this logic can be structured into functions. The program consists entirely of these functions, as shown in the example below.

open System

let isFizzBuzz value =
 (value % 15) = 0

let isFizz value =
 (value % 3) = 0

let isBuzz value =
 (value % 5) = 0

let output (value : int) =
 if isFizzBuzz value then
   "FizzBuzz"
 else if isFizz value then
   "Fizz"
 else if isBuzz value then
   "Buzz"
 else
   string value

[< EntryPoint >]
let main argv =
 let message =
   seq { for i in 1..100 do output i}
   |> String.concat " "
 printfn "%s" message
 printfn "Done"

Next, we’ll go over the object-oriented approach using C # as a language. Although the logic is similar, the big difference with the object-oriented approach is that it is wrapped in an object which keeps the current number of the loop as a variable.

This object-oriented approach has some advantages. First, if the application is made up of a series of logics, objects can interact through simplified interfaces. Second, to create a series of games similar to FizzBuzz, a programmer could use inheritance to add and modify logic as needed. Here is the C # implementation as a class, along with a more traditional main routine for performing the printing process.

public class Fizzer {
   private int _val;
        
   public Fizzer() {
     _val = 1;
   }
 
   public string getNewVal() {
       string answer = "";
       if (_val%5==0) answer = "Fizz";

       if (_val%3==0) answer+= "Buzz";

       if (!(_val%3==0 || _val%5==0)) answer = Convert.ToString(_val);
 
       answer+="n";
       _val+=1;
       return answer;
   }
}

class Program {
    static void Main(string[] args) {
        Fizzer f = new Fizzer();
        for (int idx=1;idx<100;idx++){
            Console.Write(f.getNewVal());
        }
    }   
}

For a higher level of abstraction, an object can iterate from start to finish and call the method. This is useful when the programmer wants to trade games at run time, or build the program using rules from a file that can change over time. To see a real object-oriented implementation of FizzBuzz, check out this C # object-oriented example from Steve Poling, former software engineer and technical consultant at Excelon Development. Note that there are more lines of code that may have a value for reuse.

Use case of functional programming versus object-oriented programming

The design of the user interface is a natural fit for the object-oriented approach. Windows that appear on a user’s screen are often constructed using buttons, text boxes, and menus. These windows have a state – for example, with the text on a page in a word processor, the state changes as the user types. Once the basic window layout is available, other programmers can inherit and reuse this code, starting with a shell and filling in objects.

Functional programming is the best option when the application will be made up of functions that build on each other. For example, in Unix it is common to tie together a large number of small programs, sending the results of a list of processes to a specific search like grep, or one page at a time with less.

Combine functional and object-oriented programming

An unfortunate downside of object-oriented programming is the risk of creating a complex code base that becomes increasingly difficult to maintain over time. Even for sophisticated development shops that use the object-oriented approach, the code often looks like the example above – a few objects scattered among a fair amount of procedural code.

It can be difficult to test or debug objects that create other objects or have links to external databases and APIs. In the event of an error, the programmer is unlikely to know the values ​​of all objects or exactly how to reproduce them, even with a complete record of the error. There are certainly design models that address these issues, but the industry adoption of these models is somewhat limited. Either way, development workshops committed to the object-oriented approach are often put to the test by code reviews and tough maintenance projects.

Functional programming, on the other hand, presents a different challenge – it can be very difficult to learn and practice. The functional approach requires a whole different form of code thinking, a considerable investment of time, and rigorous attention to detail. For these reasons, IT management may view functional programming as a risk.

However, there is a happy medium. Programmers could use the functional approach to create a small part of a major application. Any logic that takes data and produces results in batches is a good candidate for this strategy. This includes insurance quote routines, product planning, and extraction, processing, and loading. It is also possible to add state to functional programs using a programming language that is not purely functional, such as F #.

It is also possible to add functions to programs based on traditional object-oriented languages. For example, languages ​​such as C # and Java now have features that allow a functional approach. One of these features includes the ability to write F # code that interacts with C # through the Common Language Runtime.

Leave A Reply

Your email address will not be published.