white paper - cybage.com · functional programming has to offer. the paper is backed up with...

9
White Paper This document and all its contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. Any unauthorized disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. © Cybage Software Pvt. Ltd Functional Programming – Pure Cure for Side Effects A Cybage perspective Abstract In this paper, we will look at how fundamental concepts of funconal programming can help to reduce development cost, and improve soware quality and performance. The paper will define problems being faced in soware development and then share the soluons that funconal programming has to oer. The paper is backed up with observaons and ndings based on our experiences in funconal programming, primarily in F#, a funconal programming language by Microsoon .NET framework.

Upload: others

Post on 15-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper

This document and all its contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. Any unauthorized disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. © Cybage Software Pvt. Ltd

Functional Programming – Pure Cure for Side Effects A Cybage perspective

Abstract In this paper, we will look at how fundamental concepts of functional programming can help to reduce development cost, and improve software quality and performance. The paper will define problems being faced in software development and then share the solutions that

functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily in F#, a functional programming language by Microsoft on .NET framework.

Page 2: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 2 of 9

Table of Contents 1. Understanding the Title ........................................................................................................................ 3

2. Problem Defin on ................................................................................................................................ 4

3. How Func onal Programming Solves ................................................................................................... 4

Purity ..................................................................................................................................................... 4

High Order Fun ons ............................................................................................................................ 4

Recursion .............................................................................................................................................. 5

Currying ................................................................................................................................................. 5

Closures ................................................................................................................................................. 5

Pa ern Matching .................................................................................................................................. 5

Lazy Evaluation ...................................................................................................................................... 6

Type Inference and Strongly-typed Languages .................................................................................... 6

Monads, Impure Cos, and IO ................................................................................................................ 6

4. The Big Picture: A View of the Solu on ................................................................................................ 6

Delays in Time to Market ...................................................................................................................... 6

Inconsistent So ware Quality ............................................................................................................... 7

Slow So ware Performance ................................................................................................................. 7

Higher Development Cost ..................................................................................................................... 7

5. Conclusion ............................................................................................................................................. 7

6. References ............................................................................................................................................ 8

Page 3: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 3 of 9

1. Understanding the Title

The title of this document appears to be borrowed from the pharmaceutical industry, but it is not. Rather, this paper details the issues concerning imperative programming and how they could be addressed with pure functional programming. Historically, functional programming finds its roots in the German word ‘Entscheidungsproblem’ (loosely translated into ‘decision problem’), even before the computer, in its modern sense, could take shape. However, the practical limitations of hardware and memory made imperative programming more popular. While functional programming proscribes modification of data, imperative programming imposes no such rules. Nevertheless, software languages have been designed to be modular and all the programming paradigms support a modular approach to writing code (either as functions or subroutines). A function, by definition, is expected to work, act or process inputs using some logic, and produce consistent results.

A function might depend upon other data (global or static), while other modules or data may be dependent on this function. Because of the external environment (external files, database) the results of such a function may not be consistent. It is then called as a function with side effect(s). To understand a piece of code with side effects, one needs to go through all lines to uncover hidden dependencies and to understand different contexts related to the given code.

On the other hand, a function which is not dependent on anything other than its arguments can be used in any environment and any context. In functional programming, side effects are rarely used and it is customary for programmers to avoid them. Functions are supposed to return the same result for the same set of input parameters. This means that the functions are dependent only on their input parameters. Such functions are called pure functions. In the preceding title, the word ‘pure’ symbolizes features of functional programming, while ‘side-effects’ symbolizes issues with imperative programming. Let’s see how functional programming offers cures to these issues. In the following sections, we will define the problem and briefly visit the features of functional programming for cures!

‘Pure’ symbolizes features of functional programming while ‘side effects’ symbolizes issues with imperative programming.

Page 4: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 4 of 9

2. Problem De�inition Today, most often than not, software projects get delayed and we invariably notice that teams with similar capabilities deliver inconsistently. One of the main reasons for this is that software development mostly happens in an imperative programming paradigm. Imperative programming tends to be more error prone and its complexity increases as multiple people modify the code over time. It is no secret that sampling of studies and surveys reveals that:

• Fifty percent of projects spent their time on coding and fixing bugs. • Forty-seven percent higher than expected maintenance costs.

These days, thanks to advancements in hardware, multi-core systems are de facto. Thus, software should use the multi-core capabilities of hardware. However, developing parallel software using imperative languages is very complicated. As a result, often native hardware capabilities are not fully utilized.

3. How Functional Programming Solves… Let us visit the features of functional programming and try to understand what issues they solve.

Purity

In functional programming, purity is not only restricted to functions, but it also extends to variables as well—everything is immutable. Purity is characterized by the absence of variables. Pure functions also imply that a piece of code has local effect; and that helps in understanding the code by someone who may not have authored it, thereby making code modification easier. It makes sense to cache results of pure functions, with very little efforts needed to cache. Furthermore, since everything is immutable, with almost zero efforts, pure logic can be executed in parallel without worrying about race conditions, synchronization, and deadlocks. Higher Order Functions Higher order functions are functions that take other functions as argument(s). These functions are very useful for defining and achieving abstractions, and reducing

repetition. Examples of high order functions are ‘map and reduce’. Map and reduce provide abstractions for ‘for’ and ‘while’ loops respectively. As a result, they can be easily replaced with parallel implementations. Another advantage of high order functions is that they help to write combinatory libraries, which in turn, help to combine different functions. Code developed using combinatory libraries can be very close to a language used in business domain, thus reducing the

Functional Programming addressed many issues with Imperative Programming by means of Purity, Higher Order Functions, Recursion, Lazy Evaluation, Currying, Pattern Matching etc.

Page 5: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 5 of 9

semantic gap between business logic and software code. As a result, it is easy to write embedded, domain-specific languages. Recursion Recursion is extensively used in functional programming languages. Recursive calls use stack and as a result, those calls with deep recursions can result in stack overflows. Functional programming language compilers often include ‘tail call optimization’. This ensures the amount of stack space is maintained at a constant, regardless of how deep the recursive call may be. Programmers need to employ a technique called ‘tail recursion’ while defining recursion so that the compiler won’t have to use stack for recursion needs. This feature frees the programmer from writing unnatural code for recursive logic, and it is common knowledge that recursive code is always more concise than non-recursive code. Currying Currying is the process of transforming a function that accepts multiple parameters in to a sequence of nested functions such that each function takes a single parameter—the next parameter in argument list. Currying makes it easy to differentiate specialized forms of functions from the more abstract ones. Let’s suppose that we have multiplication function,

let mult x y = x * y then defining function for multiplicative 34th table is as easy as let table34 = mult 34

Now table34 is a new function that returns any factor of 34 based on the parameter passed. Currying encourages code reuse, which results in shortening of the code. Closures Closure is a mechanism by which a function can access a state outside its local scope. Without requiring additional code, closures, along with currying, can be used to implement caching, memorization or indexing logic.

Pattern Matching

Patterns are like defining piece-wise function of mathematics. You can define various function bodies for various arguments by using patterns. When you call a function, the appropriate body is chosen, depending upon the argument that is passed to it. For example, the Fibonacci function can be expressed as

let rec fib = function | 0 -> 0

Page 6: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 6 of 9

| 1 -> 1 | n - > fib n-1 + fib n-2

Pattern matching helps you to code logic succinctly.

Lazy Evaluation Lazy evaluation means that expressions are not evaluated when they are bound to variables, but their evaluation is deferred until their results are needed by computation. Lazy evaluation thus makes optimizations easy, and allows one to define infinite data structures, while giving a good abstraction.

Type Inference and Strongly-typed Languages

Type inference is normally characteristic of functional programming language, but is not limited to this paradigm. It refers to a mechanism used by the compiler to automatically deduce the type of expression. It frees the programmer from specifying type at most places, thus removing unnecessary noise from the code. To top this, all functional programming languages are strongly typed, eliminating a huge class of ‘easy-to-make’ errors at compile time. In essence, strong typing means no run-time errors. The possibility of treating an integer as a pointer, or following a null pointer is zero. Lightweight type system, along with immutability, makes it possible to use types in the design process. Thoughtful use of algebraic sum type can make a design more transparent, represent the domain accurately, and thus empower the compiler to ensure precision.

Monads, Impure Cos, and IO

Functional programming languages need to make provision for side effects to interact with external world or for IO. Some functional languages extend their pure core with side effects. Another way of introducing side effects is through monads. The objective is to separate pure and impure code by making impure code or side effects explicit through method signatures. Pure code needs very less maintenance and the source of most bugs is impure code. Essentially, the usage of code in the impure part should be minimal, and it should be restricted up to ‘service’ boundaries.

4. The Big Picture: A View of the Solution Our approach towards functional programming has yielded good results. Using the functional programming paradigm has some obvious advantages, and it should be evaluated to find out if it fits the situation and addresses the aforementioned concerns. Based on our experiences, we will illustrate how functional programming helps to attain business objectives.

Delays in Time to Market High order functions, recursion, currying, pattern matching, and type inference features help to reduce lines of code by five to six times. The productivity rates in terms of lines of code are similar to that of other languages. This results in reduction of development time and acceleration in the time to market.

Page 7: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 7 of 9

Inconsistent Software Quality Source code is classified into two sections: pure and impure code. Defects are rarely found in pure code, and the source of most defects is impure code. We have experienced that the amount of impure code comes in a range of 15 to 20 percent of the total source code. The lesser the amount of impure code, more drastic would be the reduction in debugging and rework. Functional programming reduces the semantic gap between logic and source code, and as a result, a set of bugs—caused by a larger semantic gap—is eliminated. Lazy evaluation helps in avoiding a class of errors such as the infinite loop. Strong type checking helps to develop very high quality software consistently.

Slow Software Performance Lazy evaluation helps to avoid the execution of a code that does not have an impact on the final result, thus increasing performance. The ability to easily cache and execute pure functions on multi-core processors helps in developing high-performing software.

Higher Development Cost Lesser development time and fewer bugs help to fix the issue of high development costs. Also, without additional costs and complexities, the software can capitalize on advanced hardware.

5. Conclusion Cybage faced the aforementioned challenges in some of its projects. To address these challenges, the team of architects decided to use the functional programming paradigm using F# as programming language. Our observations and results are as follows. Category Before F# F# Improvement

Lines of code 65169 23470 Difference of 2.78 times

Execution time 7 hours 45 minutes 2 hours 25 minutes Difference of 3.2 times

Post conversion, only four production defects were found. Moreover, the release tackled many high-complexity issues that were evidently delaying its implementation. All this was achieved in a matter of months, including learning and training time. The team had apprehensions about the readability of the functional code, due to abstractions and short size. However, we now realize that it is just a matter of familiarity, and with time, reading functional code becomes easier.

Page 8: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

© Cybage Software Pvt. Ltd Page 8 of 9

Functional programming definitely helps in accelerating time to market, reducing development costs, increasing software quality, and improving performance.

6. References

[1] http://en.wikipedia.org/wiki/Side_effect_(computer_science) [2] http://www.haskell.org/haskellwiki/Functional_programming [3] http://www.haskell.org/haskellwiki/Introduction [4] http://fsharpforfunandprofit.com/posts/designing-with-types-intro/ [5] http://fsharp.org/

Page 9: White Paper - cybage.com · functional programming has to offer. The paper is backed up with observations and findings based on our experiences in functional programming, primarily

White Paper: Functional Programming – Pure Cure for Side Effects

Page 9 of 9

About Cybage So ware Pvt. Ltd. Founded in 1995, Cybage So ware is a leading offshore so ware services company offering solu ons that accelerate, simplify, and enrich business processes to give its clients an edge over compe on. We are an SEI CMMI Level 5 version 1.3 and ISO 27001 appraised company based in Pune, India. Our success is built on a pool of 4,500 so ware professionals. Based on a remarkable record of quality, consistency, and outstanding technological prowess, we have partnered with more than 200 global so ware houses of fine repute. Our array of services includes Product Engineering (OPD), Enterprise Business Solu ons, and Value Added Services. Cybage specializes in the implementa on of the Offshore Development model.

Cybage domain exper spans across several business v s such as Media and Entertainment, Travel and Hospitality, Healthcare and Life Sciences, Retail and Distribu on, and Hi-Tech. Cybage has eight technology-focused Centers of Excellence (CoEs)—Enterprise Mobility, eCommerce, Customer Rela onship Management, Business Intelligence, Enterprise Content Management, Cloud Compu g, Educa on & Learning, and Supply Chain Management. Our unique model of opera onal efficiency, ExcelShore®, helps de-risk our approach and provide the best value per unit cost.

To know more about us, visit us at www.cybage.com or write to us at [email protected].

© 2019. Cybage Software Pvt. Ltd. All rights reserved.