SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
JavaScript for ABAP Programmers
Imperative vs. Functional Programming
Chris Whealy / The RIG
ABAP
Strongly typed
Syntax similar to COBOL
Block Scope
No equivalent concept
OO using class based inheritance
Imperative programming

JavaScript
Weakly typed
Syntax derived from Java
Lexical Scope
Functions are 1st class citizens
OO using referential inheritance
Imperative or Functional programming
Different Schools of Thought
Programming in General 1/2
In broad terms, the world of computer programming is split into various, overlapping schools of
thought. These schools of thought differ primarily on the approach used to design and build a
computer program.
The (very incomplete) diagram below shows two of the main schools of thought in programming and
some of their more widely known subdivisions.
Imperative

Procedural/
Structured

Pascal

C

Declarative

Fortran

© 2013 SAP AG. All rights reserved.

Assembler

Functional

Object
Oriented

Unstructured

Java

JavaScript C++

ABAP

Haskell

Erlang

JavaScript

Logic

Prolog

4
Programming in General 2/3
The divisions between these categories are not hard and fast, and some languages (like JavaScript)
can belong to multiple categories.
Here we will be looking at using JavaScript in both the Imperative and Functional styles.

Imperative

Procedural/
Structured

Pascal

C

Declarative

Fortran

© 2013 SAP AG. All rights reserved.

Assembler

Functional

Object
Oriented

Unstructured

Java

JavaScript C++

ABAP

Haskell

Erlang

JavaScript

Logic

Prolog

5
Programming in General 3/3
No matter which programming style or language you use, all statements in any computer program can
be grouped together in some combination of three basic control structures:*
Sequence
The instruction flow is a simple sequence of “do this, then this, followed by that
”
Selection
Alters the instruction flow based on the outcome of a condition
Iteration**
Performs a task multiple times until some termination condition is reached

The major differences between imperative and functional programming lie in how you define these
three control structures.

* Known as the Böhm-Jacopini theorem
© 2013 SAP AG. All rights reserved.

** From the Latin “ite” meaning “go”
6
The Differences Between Imperative
and Functional Programming
Imperative Programming: Do exactly this and do it now!
The “imperative programming” school of thought is by far the most widely used style of coding and is
implicitly assumed to be the “normal” way to program a computer.
This style of programming arose from the computer architecture defined by John von Neumann in
1945 and is best suited to situations in which a known computation must be performed on a
predictable dataset.
In this style of coding, the programmer is focused primarily on:
‱ Transforming the computer’s state (I.E. the data in memory) by means of a precisely defined set of
instructions.
‱ Making explicit use of beneficial side-effects to achieve the desired result:
‱ The use of global or shared memory as the repository for the evolving state of the data
‱ Interacting with persistent storage (E.G a database)
‱ Interacting with peripheral devices (printer, network, camera, accelerometer etc)

© 2013 SAP AG. All rights reserved.

8
Imperative Programming: Focusing on the “when”
In spite of the fact that “Imperative programming” is a broad term that encompasses many other styles
of coding (E.G. procedural, modular, object oriented etc), the programmer’s job is essentially
concerned with defining the explicit timeline of when statements should be executed. In other words:
An imperative program is a set of instructions that define
exactly when the computer’s state should be modified
Yes
Do this

Do that

Is this true?

Stop
No

© 2013 SAP AG. All rights reserved.

Do this

Do that

9
Imperative Programming: Summary
Imperative programming languages give the programmer the necessary tools for defining the three
fundamental control structures explicitly
Sequence
A set of instructions whose execution order is explicitly defined
Selection
Implemented using statements such as if or switch or case that modify the
instruction flow based on the outcome of an explicitly defined condition
Iteration
Implemented using statements such as do/while or for loops

Since imperative programming is strongly focused on the timeline of when the computer’s state should
be modified, these languages necessarily must provide the programmer with keywords that explicitly
control the instruction flow (such as if and case and do/while).

© 2013 SAP AG. All rights reserved.

10
Functional Programming: Focusing on the “How”
In functional programming however, there is a very different focus. As much as possible, functional
programming languages avoid (or even prohibit) the alteration of the computer’s state, and instead
define the required computation solely in terms of:
‱ The relationship between a set of functions, such that the return value from the last function
corresponds to the desired output of the computation
‱ Each function:
‱ Receives one or more parameters
‱ Acts only upon the values received as parameters (no use of shared or global memory)
‱ Returns a result to the calling function
‱ The result returned from a function is used either as the final result of the computation, or as a
parameter value passed to another function.

© 2013 SAP AG. All rights reserved.

11
Functional Programming: Summary
Functional programming languages are still required to arrange their statements according to the three
fundamental control structures seen before, but the tools they provide perform this task implicitly
Sequence
A set of instructions whose execution order is explicitly defined
Selection
Implemented by the language runtime using pattern matching, rather than by an
explicitly coded condition such as if or switch or case.
Iteration

Implemented by means of recursion.

Functional programming is strongly focused on creating a solution that avoids side-effects (the
manipulation of global or shared memory is considered to be a side-effect).
Therefore, this style of programming focuses on the relationship between the input data and the output
data, then defines a set of functions that perform the required transformation. This results in a greatly
reduced focus on writing code to test explicit conditions or to repeat blocks of code some predefined
number of times.
Instead, these aspects of modifying the instruction flow are delegated to the language runtime.
© 2013 SAP AG. All rights reserved.

12
Functional Programming
A Simple Example
Functional Programming: A Worked Example
This shift of emphasis from when to how is far more than an academic detail; it fundamentally alters
the way you think about software design!
A programmer familiar with the architecture of coding used in imperative languages such as ABAP or
Java is strongly focused on when instructions should be performed.
However in functional programming, the emphasis is on defining how the software should respond to a
given pattern of data, and is far less concerned with exactly when the various functions may or may
not be called.
This is best illustrated with a small JavaScript program written in both the imperative and functional
styles.

© 2013 SAP AG. All rights reserved.

14
Calculating Fibonacci Numbers: Imperative Style 1/4
Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using
the formula fibn = fibn-2 + fibn-1)
// Calculate nth Fibonacci number: imperative style
function fib_imperative(n) {
var a = 0, b = 1, sum = 0;
while
sum
a =
b =
n =
}

(n>1) {
= a + b;
b;
sum;
n - 1;

return sum;
}
fib_imperative(8); //  21

© 2013 SAP AG. All rights reserved.

15
Calculating Fibonacci Numbers: Imperative Style 2/4
Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using
the formula fibn = fibn-2 + fibn-1)
// Calculate nth Fibonacci number: imperative style
function fib_imperative(n) {
var a = 0, b = 1, sum = 0;
while
sum
a =
b =
n =
}

(n>1) {
= a + b;
b;
sum;
n - 1;

Function fib_imperative() receives a single
parameter n and uses this value to control a simple
while loop.
Inside the loop, three variables (a, b and sum) are
used to maintain the state of the calculation.

return sum;
}
fib_imperative(8); //  21

© 2013 SAP AG. All rights reserved.

16
Calculating Fibonacci Numbers: Imperative Style 3/4
Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using
the formula fibn = fibn-2 + fibn-1)
// Calculate nth Fibonacci number: imperative style
function fib_imperative(n) {
var a = 0, b = 1, sum = 0;
while
sum
a =
b =
n =
}

(n>1) {
= a + b;
b;
sum;
n - 1;

return sum;
}
fib_imperative(8); //  21

© 2013 SAP AG. All rights reserved.

Function fib_imperative() receives a single
parameter n and uses this value to control a simple
while loop.
Inside the loop, three variables (a, b and sum) are
used to maintain the state of the calculation.
The final value is accumulated in variable sum which
then becomes the return value.
Notice that as the loop progresses, the value of
variable sum continually changes. This is a classic
example of the imperative coding style in which the
computer’s state evolves towards the desired result.

17
Calculating Fibonacci Numbers: Imperative Style 4/4
Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using
the formula fibn = fibn-2 + fibn-1)
// Calculate nth Fibonacci number: imperative style
function fib_imperative(n) {
var a = 0, b = 1, sum = 0;
while
sum
a =
b =
n =
}

(n>1) {
= a + b;
b;
sum;
n - 1;

return sum;
}
fib_imperative(8); //  21

Function fib_imperative() receives a single
parameter n and uses this value to control a simple
while loop.
Inside the loop, three variables (a, b and sum) are
used to maintain the state of the calculation.
The final value is accumulated in variable sum which
then becomes the return value.
Notice that as the loop progresses, the value of
variable sum continually changes. This is a classic
example of the imperative coding style in which the
computer’s state evolves towards the desired result.

Because we are all familiar with the imperative coding style, this program is quite understandable.
Now let’s see exactly the same functionality written in the functional style.
© 2013 SAP AG. All rights reserved.

18
Calculating Fibonacci Numbers: Functional Style
Not only is this program much more compact, but familiar statements such as if and while are
missing. This solution will require some explanation

// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
})(0,1,n);
}
fib_functional(8); //  21

© 2013 SAP AG. All rights reserved.

19
Calculating Fibonacci Numbers: Explanation of Functional Style 1/5
At the centre, we have a function called do_fib() that takes 3 parameters.
Parameter a is fibn-2, b is fibn-1 and n is the required number in the Fibonacci series.
// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
} )(0,1,n);
}
fib_functional(8); //  21

© 2013 SAP AG. All rights reserved.

20
Calculating Fibonacci Numbers: Explanation of Functional Style 2/5
There are several important differences about the coding style here:
// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
} )(0,1,n);
}
fib_functional(8); //  21

1.

The ternary operator is used to create an inline condition.
Had we used an explicit if statement, then this would draw your attention to the loop counter variable n and
make you think this value should somehow be the focus of our attention; when in reality, it is merely a means
to an end.
The use of the ternary operator ensures that the focus of attention remains on the function’s return value which will either be the value held in parameter b, or the result of a recursive call to do_fib().

© 2013 SAP AG. All rights reserved.

21
Calculating Fibonacci Numbers: Explanation of Functional Style 3/5
There are several important differences about the coding style here:
// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
} )(0,1,n);
}
fib_functional(8); //  21

2.

Notice that no internal variables are declared within function do_fib().
The actual calculation of the next number in the Fibonacci sequence is performed at the time the parameters
are passed to the recursive do_fib() call.

3.

Use of the while keyword is no longer required because iteration is now controlled by recursion.

© 2013 SAP AG. All rights reserved.

22
Calculating Fibonacci Numbers: Explanation of Functional Style 4/5
There are several important differences about the coding style here:
// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
})(0,1,n);
}
fib_functional(8); //  21

4.
5.

Function do_fib() is invoked automatically by enclosing the function definition within parentheses and then
using the invocation operator ().
The invocation operator contains the 3 required parameters: 0 and 1 (the first two numbers in the Fibonacci
sequence) and n (the nth number in the Fibonacci sequence).

© 2013 SAP AG. All rights reserved.

23
Calculating Fibonacci Numbers: Explanation of Functional Style 5/5
There are several important differences about the coding style here:
// Calculate nth Fibonacci number: functional style
function fib_functional(n) {
return (function do_fib(a,b,n) {
return (n==1) ? b : do_fib(b,a+b,n-1);
})(0,1,n);
}
fib_functional(8); //  21

6.

The return value from the call to do_fib() becomes the return value of the enclosing function, here called
fib_functional()

7.

Function fib_functional() is a wrapper function that receives a single parameter value and then acts as a
container for the recursive calls to function do_fib().

© 2013 SAP AG. All rights reserved.

24
Functional Programming
Side-effects Are Bad!
Functional Programming – Avoid Side Effects!
When a function alters data outside its own scope, this is called a side-effect. This is generally bad because
unexpected alterations to global data can lead to erroneous program behaviour that is very hard to debug.
var num = 1;

// Global variable

// A strange way to do addition...
function add_with_side_effects(a) {
return a + num++;
}

© 2013 SAP AG. All rights reserved.

26
Functional Programming – Avoid Side Effects!
When a function alters data outside its own scope, this is called a side-effect. This is generally bad because
unexpected alterations to global data can lead to erroneous program behaviour that is very hard to debug.
var num = 1;

// Global variable

// A strange way to do addition...
function add_with_side_effects(a) {
return a + num++;
}
//
//
//
//

Each time you call this function, it not only returns a result, but also increments a
global variable. This side-effect creates the problem that the next time you call the
same function with the same parameter, it will behave differently.
This makes the function unreliable and is therefore bad program design

add_with_side_effects(1);
add_with_side_effects(1);

© 2013 SAP AG. All rights reserved.

//  2, but 'num' now equals 2
//  3 (Uh!?) and 'num' now equals 3

27
Functional Programming – Referential Transparency 1/2
Referential transparency means that a function call can safely be replaced by the function’s return value.
Here’s an example of a function that does not cause side-effects, but lacks referential transparency

var num = 1;

// Global variable

// Another strange way to do addition...
function bad_add(a) {
return a + num;
}
// Each time function bad_add() is called with the same parameter, it could potentially
// return a different result because its behaviour depends on a value that was not supplied
// as parameter. Again, this is bad design because it makes the function unreliable
var ans1 = bad_add(3); //  4

© 2013 SAP AG. All rights reserved.

28
Functional Programming – Referential Transparency 1/2
Referential transparency means that a function call can safely be replaced by the function’s return value.
Here’s an example of a function that does not cause side-effects, but lacks referential transparency

var num = 1;

// Global variable

// Another strange way to do addition...
function bad_add(a) {
return a + num;
}
// Each time function bad_add() is called with the same parameter, it could potentially
// return a different result because its behaviour depends on a value that was not supplied
// as parameter. Again, this is bad design because it makes the function unreliable
var ans1 = bad_add(3); //  4
num = 4;

// Somewhere in the coding, the global variable is then changed...

var ans2 = bad_add(3); //  7 (Uh!? Last time I called it, it returned 4)

© 2013 SAP AG. All rights reserved.

29
Functional Programming – Referential Transparency 2/2
This function does not create any side-effects and also has referential transparency.
Any function that has referential transparency is said to be idempotent.
// Add up the supplied numbers
function good_add(a,b) {
return a + b;
}
// Referential transparency means
// called, as long as we pass the
var ans1 = good_add(2,3);
// 
var ans2 = good_add(2,3);
// 

© 2013 SAP AG. All rights reserved.

that no matter how many times function good_add() is
same parameters, we'll always get back the same result
5
5

30
Functional Programming – Referential Transparency 2/2
This function does not create any side-effects and also has referential transparency.
Any function that has referential transparency is said to be idempotent.
// Add up the supplied numbers
function good_add(a,b) {
return a + b;
}
// Referential transparency means
// called, as long as we pass the
var ans1 = good_add(2,3);
// 
var ans2 = good_add(2,3);
// 

that no matter how many times function good_add() is
same parameters, we'll always get back the same result
5
5

To achieve referential transparency (or idempotency), always ensure that a function:
a) returns a value derived only from its parameters
b) never relies on the value of global variables
c) does not cause side-effects by modifying data outside its own scope
© 2013 SAP AG. All rights reserved.

31
Functional Programming
A Simple Example From SAPUI5
Functional Programming – Example from SAPUI5 1/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

© 2013 SAP AG. All rights reserved.

33
Functional Programming – Example from SAPUI5 2/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
‱ Attach the event handler function to the appropriate event of the UI element
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

// Attach event handler function to the "press" event of the button UI element
btn.attachPress(evtHandler);

Attach an event
handler function

© 2013 SAP AG. All rights reserved.

34
Functional Programming – Example from SAPUI5 3/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
‱ Attach the event handler function to the appropriate event of the UI element
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

// Attach event handler function to the "press" event of the button UI element
btn.attachPress(evtHandler);

Attach an event
handler function

© 2013 SAP AG. All rights reserved.

Wait for an unknown
period of time

35
Functional Programming – Example from SAPUI5 4/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
‱ Attach the event handler function to the appropriate event of the UI element
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

// Attach event handler function to the "press" event of the button UI element
btn.attachPress(evtHandler);

Attach an event
handler function

© 2013 SAP AG. All rights reserved.

Wait for an unknown
period of time

Browser invokes
event handler when
event is triggered

36
Functional Programming – Example from SAPUI5 5/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
‱ Attach the event handler function to the appropriate event of the UI element
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

// Attach event handler function to the "press" event of the button UI element
btn.attachPress(evtHandler);

Attach an event
handler function

© 2013 SAP AG. All rights reserved.

Wait for an unknown
period of time

Browser invokes
event handler when
event is triggered

37
Functional Programming – Example from SAPUI5 6/6
Handling user events is an example of where we need to focus the how and not the when:
‱ Define a function to handle a particular pattern of data (E.G. a button push event)
‱ Attach the event handler function to the appropriate event of the UI element
// Define an event handler function for a button UI element
var evtHandler = function() { alert("B A N G !"); }
var btn = new sap.ui.commons.Button({text:'Do not push this button'});

// Attach event handler function to the "press" event of the button UI element
btn.attachPress(evtHandler);

Attach an event
handler function

Wait for an unknown
period of time

Browser invokes
event handler when
event is triggered

This style of programming focuses entirely on how the system should respond when a pattern of data is
received (E.G. a UI event). When we respond is not important because the button might never be pushed!
© 2013 SAP AG. All rights reserved.

38
Functional Programming
Summary
Functional Programming – Summary 1/2
Functional programming is style of coding that borrows heavily from a branch of mathematics known
as Lambda Calculus.
The functional programming style imposes the following constraints:
‱
‱
‱
‱
‱

Functions interact with each other only by means of parameters and return values.
The use of internal variables to maintain program state is avoided (or in some languages prohibited).
Side-effects are not permitted. Most functional programming languages do not have the concept of shared or
global memory.
Looping is handled by means of recursion, rather than explicit loop constructs such as do...while or for.
The exact order in which functions are invoked is delegated to the language runtime on the basis of the data
available at execution time.

The appeal of the functional programming style is that if you strictly follow its design philosophy, it allows you to
write coding that is provably correct (as apposed to hopefully correct).
This feature has always had great appeal in academic circles, but with the increasing popularity of multi-core
processors and the need to analyze ever increasing quantities of data, the use of the functional programming style
is steadily increasing in the world of business programming.
© 2013 SAP AG. All rights reserved.

40
Functional Programming – Summary 2/2
Different functional programming languages implement these principles to varying degrees.
Those languages that fully implement all the principles are said to be “purely functional” languages
(such as Haskell or Miranda), with the rest being referred to as “impurely functional”.
Impure functional languages are generally easier to code in because you do not need to resort to such
deep levels of mathematical abstraction. Examples of impure functional languages include:
‱ Erlang
‱ F#
‱ Lisp
‱ R (Used internally with SAP’s HANA database)

CAUTION!
JavaScript is a multi-paradigm language! This means that both the imperative and functional styles of
coding can co-exist within the same application.
Care must be taken when designing JavaScript applications to ensure that confusion is not introduced
into the architecture by a jumbled use of these different paradigms.
© 2013 SAP AG. All rights reserved.

41

Weitere Àhnliche Inhalte

Was ist angesagt?

Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Edureka!
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New FeaturesAli BAKAN
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional WorldDebasish Ghosh
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaEdureka!
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.Bhautik Jethva
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksÄ°brahim KĂŒrce
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritanceadil raja
 
java Features
java Featuresjava Features
java FeaturesJadavsejal
 
Java
JavaJava
Javas4al_com
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Angular state Management-NgRx
Angular state Management-NgRxAngular state Management-NgRx
Angular state Management-NgRxKnoldus Inc.
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptxSameerAhmed593310
 

Was ist angesagt? (20)

Java 17
Java 17Java 17
Java 17
 
SAP Integration with Excel - Basic Guide
SAP Integration with Excel - Basic GuideSAP Integration with Excel - Basic Guide
SAP Integration with Excel - Basic Guide
 
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
JVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdfJVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdf
 
Java seminar
Java seminarJava seminar
Java seminar
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
java Features
java Featuresjava Features
java Features
 
Intern presentation based on Flutter Lawyer App.
Intern presentation based on Flutter Lawyer App.  Intern presentation based on Flutter Lawyer App.
Intern presentation based on Flutter Lawyer App.
 
Java
JavaJava
Java
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Core java
Core javaCore java
Core java
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Angular state Management-NgRx
Angular state Management-NgRxAngular state Management-NgRx
Angular state Management-NgRx
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 

Ähnlich wie JavaScript for ABAP Programmers - 7/7 Functional Programming

Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigmsAnirudh Chauhan
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingThang Mai
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
program development and paradigms
program development and paradigmsprogram development and paradigms
program development and paradigmskasenerd
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxvishnupriyapm4
 
265 ge8151 problem solving and python programming - 2 marks with answers
265   ge8151 problem solving and python programming - 2 marks with answers265   ge8151 problem solving and python programming - 2 marks with answers
265 ge8151 problem solving and python programming - 2 marks with answersvithyanila
 
Training 8051Report
Training 8051ReportTraining 8051Report
Training 8051ReportKuldeep Kaushik
 
Book management system
Book management systemBook management system
Book management systemSHARDA SHARAN
 
C programming
C programmingC programming
C programmingJigarthacker
 
PCCF UNIT 2.pptx
PCCF UNIT 2.pptxPCCF UNIT 2.pptx
PCCF UNIT 2.pptxDivyaKS12
 
4 coding from algorithms
4 coding from algorithms4 coding from algorithms
4 coding from algorithmshccit
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithmmshoaib15
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptxMAHAMASADIK
 

Ähnlich wie JavaScript for ABAP Programmers - 7/7 Functional Programming (20)

Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
program development and paradigms
program development and paradigmsprogram development and paradigms
program development and paradigms
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptx
 
265 ge8151 problem solving and python programming - 2 marks with answers
265   ge8151 problem solving and python programming - 2 marks with answers265   ge8151 problem solving and python programming - 2 marks with answers
265 ge8151 problem solving and python programming - 2 marks with answers
 
session-4.pptx
session-4.pptxsession-4.pptx
session-4.pptx
 
Training 8051Report
Training 8051ReportTraining 8051Report
Training 8051Report
 
Combine in iOS - Basics
Combine in iOS - BasicsCombine in iOS - Basics
Combine in iOS - Basics
 
Tutorial
TutorialTutorial
Tutorial
 
Book management system
Book management systemBook management system
Book management system
 
Beekman5 std ppt_13
Beekman5 std ppt_13Beekman5 std ppt_13
Beekman5 std ppt_13
 
C programming
C programmingC programming
C programming
 
PCCF UNIT 2.pptx
PCCF UNIT 2.pptxPCCF UNIT 2.pptx
PCCF UNIT 2.pptx
 
Matopt
MatoptMatopt
Matopt
 
4 coding from algorithms
4 coding from algorithms4 coding from algorithms
4 coding from algorithms
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithm
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Cse
CseCse
Cse
 

KĂŒrzlich hochgeladen

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 

KĂŒrzlich hochgeladen (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

JavaScript for ABAP Programmers - 7/7 Functional Programming

  • 1. JavaScript for ABAP Programmers Imperative vs. Functional Programming Chris Whealy / The RIG
  • 2. ABAP Strongly typed Syntax similar to COBOL Block Scope No equivalent concept OO using class based inheritance Imperative programming JavaScript Weakly typed Syntax derived from Java Lexical Scope Functions are 1st class citizens OO using referential inheritance Imperative or Functional programming
  • 4. Programming in General 1/2 In broad terms, the world of computer programming is split into various, overlapping schools of thought. These schools of thought differ primarily on the approach used to design and build a computer program. The (very incomplete) diagram below shows two of the main schools of thought in programming and some of their more widely known subdivisions. Imperative Procedural/ Structured Pascal C Declarative Fortran © 2013 SAP AG. All rights reserved. Assembler Functional Object Oriented Unstructured Java JavaScript C++ ABAP Haskell Erlang JavaScript Logic Prolog 4
  • 5. Programming in General 2/3 The divisions between these categories are not hard and fast, and some languages (like JavaScript) can belong to multiple categories. Here we will be looking at using JavaScript in both the Imperative and Functional styles. Imperative Procedural/ Structured Pascal C Declarative Fortran © 2013 SAP AG. All rights reserved. Assembler Functional Object Oriented Unstructured Java JavaScript C++ ABAP Haskell Erlang JavaScript Logic Prolog 5
  • 6. Programming in General 3/3 No matter which programming style or language you use, all statements in any computer program can be grouped together in some combination of three basic control structures:* Sequence The instruction flow is a simple sequence of “do this, then this, followed by that
” Selection Alters the instruction flow based on the outcome of a condition Iteration** Performs a task multiple times until some termination condition is reached The major differences between imperative and functional programming lie in how you define these three control structures. * Known as the Böhm-Jacopini theorem © 2013 SAP AG. All rights reserved. ** From the Latin “ite” meaning “go” 6
  • 7. The Differences Between Imperative and Functional Programming
  • 8. Imperative Programming: Do exactly this and do it now! The “imperative programming” school of thought is by far the most widely used style of coding and is implicitly assumed to be the “normal” way to program a computer. This style of programming arose from the computer architecture defined by John von Neumann in 1945 and is best suited to situations in which a known computation must be performed on a predictable dataset. In this style of coding, the programmer is focused primarily on: ‱ Transforming the computer’s state (I.E. the data in memory) by means of a precisely defined set of instructions. ‱ Making explicit use of beneficial side-effects to achieve the desired result: ‱ The use of global or shared memory as the repository for the evolving state of the data ‱ Interacting with persistent storage (E.G a database) ‱ Interacting with peripheral devices (printer, network, camera, accelerometer etc) © 2013 SAP AG. All rights reserved. 8
  • 9. Imperative Programming: Focusing on the “when” In spite of the fact that “Imperative programming” is a broad term that encompasses many other styles of coding (E.G. procedural, modular, object oriented etc), the programmer’s job is essentially concerned with defining the explicit timeline of when statements should be executed. In other words: An imperative program is a set of instructions that define exactly when the computer’s state should be modified Yes Do this Do that Is this true? Stop No © 2013 SAP AG. All rights reserved. Do this Do that 9
  • 10. Imperative Programming: Summary Imperative programming languages give the programmer the necessary tools for defining the three fundamental control structures explicitly Sequence A set of instructions whose execution order is explicitly defined Selection Implemented using statements such as if or switch or case that modify the instruction flow based on the outcome of an explicitly defined condition Iteration Implemented using statements such as do/while or for loops Since imperative programming is strongly focused on the timeline of when the computer’s state should be modified, these languages necessarily must provide the programmer with keywords that explicitly control the instruction flow (such as if and case and do/while). © 2013 SAP AG. All rights reserved. 10
  • 11. Functional Programming: Focusing on the “How” In functional programming however, there is a very different focus. As much as possible, functional programming languages avoid (or even prohibit) the alteration of the computer’s state, and instead define the required computation solely in terms of: ‱ The relationship between a set of functions, such that the return value from the last function corresponds to the desired output of the computation ‱ Each function: ‱ Receives one or more parameters ‱ Acts only upon the values received as parameters (no use of shared or global memory) ‱ Returns a result to the calling function ‱ The result returned from a function is used either as the final result of the computation, or as a parameter value passed to another function. © 2013 SAP AG. All rights reserved. 11
  • 12. Functional Programming: Summary Functional programming languages are still required to arrange their statements according to the three fundamental control structures seen before, but the tools they provide perform this task implicitly Sequence A set of instructions whose execution order is explicitly defined Selection Implemented by the language runtime using pattern matching, rather than by an explicitly coded condition such as if or switch or case. Iteration Implemented by means of recursion. Functional programming is strongly focused on creating a solution that avoids side-effects (the manipulation of global or shared memory is considered to be a side-effect). Therefore, this style of programming focuses on the relationship between the input data and the output data, then defines a set of functions that perform the required transformation. This results in a greatly reduced focus on writing code to test explicit conditions or to repeat blocks of code some predefined number of times. Instead, these aspects of modifying the instruction flow are delegated to the language runtime. © 2013 SAP AG. All rights reserved. 12
  • 14. Functional Programming: A Worked Example This shift of emphasis from when to how is far more than an academic detail; it fundamentally alters the way you think about software design! A programmer familiar with the architecture of coding used in imperative languages such as ABAP or Java is strongly focused on when instructions should be performed. However in functional programming, the emphasis is on defining how the software should respond to a given pattern of data, and is far less concerned with exactly when the various functions may or may not be called. This is best illustrated with a small JavaScript program written in both the imperative and functional styles. © 2013 SAP AG. All rights reserved. 14
  • 15. Calculating Fibonacci Numbers: Imperative Style 1/4 Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using the formula fibn = fibn-2 + fibn-1) // Calculate nth Fibonacci number: imperative style function fib_imperative(n) { var a = 0, b = 1, sum = 0; while sum a = b = n = } (n>1) { = a + b; b; sum; n - 1; return sum; } fib_imperative(8); //  21 © 2013 SAP AG. All rights reserved. 15
  • 16. Calculating Fibonacci Numbers: Imperative Style 2/4 Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using the formula fibn = fibn-2 + fibn-1) // Calculate nth Fibonacci number: imperative style function fib_imperative(n) { var a = 0, b = 1, sum = 0; while sum a = b = n = } (n>1) { = a + b; b; sum; n - 1; Function fib_imperative() receives a single parameter n and uses this value to control a simple while loop. Inside the loop, three variables (a, b and sum) are used to maintain the state of the calculation. return sum; } fib_imperative(8); //  21 © 2013 SAP AG. All rights reserved. 16
  • 17. Calculating Fibonacci Numbers: Imperative Style 3/4 Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using the formula fibn = fibn-2 + fibn-1) // Calculate nth Fibonacci number: imperative style function fib_imperative(n) { var a = 0, b = 1, sum = 0; while sum a = b = n = } (n>1) { = a + b; b; sum; n - 1; return sum; } fib_imperative(8); //  21 © 2013 SAP AG. All rights reserved. Function fib_imperative() receives a single parameter n and uses this value to control a simple while loop. Inside the loop, three variables (a, b and sum) are used to maintain the state of the calculation. The final value is accumulated in variable sum which then becomes the return value. Notice that as the loop progresses, the value of variable sum continually changes. This is a classic example of the imperative coding style in which the computer’s state evolves towards the desired result. 17
  • 18. Calculating Fibonacci Numbers: Imperative Style 4/4 Here is a simple JavaScript function that calculates the nth number in the Fibonacci sequence (using the formula fibn = fibn-2 + fibn-1) // Calculate nth Fibonacci number: imperative style function fib_imperative(n) { var a = 0, b = 1, sum = 0; while sum a = b = n = } (n>1) { = a + b; b; sum; n - 1; return sum; } fib_imperative(8); //  21 Function fib_imperative() receives a single parameter n and uses this value to control a simple while loop. Inside the loop, three variables (a, b and sum) are used to maintain the state of the calculation. The final value is accumulated in variable sum which then becomes the return value. Notice that as the loop progresses, the value of variable sum continually changes. This is a classic example of the imperative coding style in which the computer’s state evolves towards the desired result. Because we are all familiar with the imperative coding style, this program is quite understandable. Now let’s see exactly the same functionality written in the functional style. © 2013 SAP AG. All rights reserved. 18
  • 19. Calculating Fibonacci Numbers: Functional Style Not only is this program much more compact, but familiar statements such as if and while are missing. This solution will require some explanation
 // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); })(0,1,n); } fib_functional(8); //  21 © 2013 SAP AG. All rights reserved. 19
  • 20. Calculating Fibonacci Numbers: Explanation of Functional Style 1/5 At the centre, we have a function called do_fib() that takes 3 parameters. Parameter a is fibn-2, b is fibn-1 and n is the required number in the Fibonacci series. // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); } )(0,1,n); } fib_functional(8); //  21 © 2013 SAP AG. All rights reserved. 20
  • 21. Calculating Fibonacci Numbers: Explanation of Functional Style 2/5 There are several important differences about the coding style here: // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); } )(0,1,n); } fib_functional(8); //  21 1. The ternary operator is used to create an inline condition. Had we used an explicit if statement, then this would draw your attention to the loop counter variable n and make you think this value should somehow be the focus of our attention; when in reality, it is merely a means to an end. The use of the ternary operator ensures that the focus of attention remains on the function’s return value which will either be the value held in parameter b, or the result of a recursive call to do_fib(). © 2013 SAP AG. All rights reserved. 21
  • 22. Calculating Fibonacci Numbers: Explanation of Functional Style 3/5 There are several important differences about the coding style here: // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); } )(0,1,n); } fib_functional(8); //  21 2. Notice that no internal variables are declared within function do_fib(). The actual calculation of the next number in the Fibonacci sequence is performed at the time the parameters are passed to the recursive do_fib() call. 3. Use of the while keyword is no longer required because iteration is now controlled by recursion. © 2013 SAP AG. All rights reserved. 22
  • 23. Calculating Fibonacci Numbers: Explanation of Functional Style 4/5 There are several important differences about the coding style here: // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); })(0,1,n); } fib_functional(8); //  21 4. 5. Function do_fib() is invoked automatically by enclosing the function definition within parentheses and then using the invocation operator (). The invocation operator contains the 3 required parameters: 0 and 1 (the first two numbers in the Fibonacci sequence) and n (the nth number in the Fibonacci sequence). © 2013 SAP AG. All rights reserved. 23
  • 24. Calculating Fibonacci Numbers: Explanation of Functional Style 5/5 There are several important differences about the coding style here: // Calculate nth Fibonacci number: functional style function fib_functional(n) { return (function do_fib(a,b,n) { return (n==1) ? b : do_fib(b,a+b,n-1); })(0,1,n); } fib_functional(8); //  21 6. The return value from the call to do_fib() becomes the return value of the enclosing function, here called fib_functional() 7. Function fib_functional() is a wrapper function that receives a single parameter value and then acts as a container for the recursive calls to function do_fib(). © 2013 SAP AG. All rights reserved. 24
  • 26. Functional Programming – Avoid Side Effects! When a function alters data outside its own scope, this is called a side-effect. This is generally bad because unexpected alterations to global data can lead to erroneous program behaviour that is very hard to debug. var num = 1; // Global variable // A strange way to do addition... function add_with_side_effects(a) { return a + num++; } © 2013 SAP AG. All rights reserved. 26
  • 27. Functional Programming – Avoid Side Effects! When a function alters data outside its own scope, this is called a side-effect. This is generally bad because unexpected alterations to global data can lead to erroneous program behaviour that is very hard to debug. var num = 1; // Global variable // A strange way to do addition... function add_with_side_effects(a) { return a + num++; } // // // // Each time you call this function, it not only returns a result, but also increments a global variable. This side-effect creates the problem that the next time you call the same function with the same parameter, it will behave differently. This makes the function unreliable and is therefore bad program design add_with_side_effects(1); add_with_side_effects(1); © 2013 SAP AG. All rights reserved. //  2, but 'num' now equals 2 //  3 (Uh!?) and 'num' now equals 3 27
  • 28. Functional Programming – Referential Transparency 1/2 Referential transparency means that a function call can safely be replaced by the function’s return value. Here’s an example of a function that does not cause side-effects, but lacks referential transparency
 var num = 1; // Global variable // Another strange way to do addition... function bad_add(a) { return a + num; } // Each time function bad_add() is called with the same parameter, it could potentially // return a different result because its behaviour depends on a value that was not supplied // as parameter. Again, this is bad design because it makes the function unreliable var ans1 = bad_add(3); //  4 © 2013 SAP AG. All rights reserved. 28
  • 29. Functional Programming – Referential Transparency 1/2 Referential transparency means that a function call can safely be replaced by the function’s return value. Here’s an example of a function that does not cause side-effects, but lacks referential transparency
 var num = 1; // Global variable // Another strange way to do addition... function bad_add(a) { return a + num; } // Each time function bad_add() is called with the same parameter, it could potentially // return a different result because its behaviour depends on a value that was not supplied // as parameter. Again, this is bad design because it makes the function unreliable var ans1 = bad_add(3); //  4 num = 4; // Somewhere in the coding, the global variable is then changed... var ans2 = bad_add(3); //  7 (Uh!? Last time I called it, it returned 4) © 2013 SAP AG. All rights reserved. 29
  • 30. Functional Programming – Referential Transparency 2/2 This function does not create any side-effects and also has referential transparency. Any function that has referential transparency is said to be idempotent. // Add up the supplied numbers function good_add(a,b) { return a + b; } // Referential transparency means // called, as long as we pass the var ans1 = good_add(2,3); //  var ans2 = good_add(2,3); //  © 2013 SAP AG. All rights reserved. that no matter how many times function good_add() is same parameters, we'll always get back the same result 5 5 30
  • 31. Functional Programming – Referential Transparency 2/2 This function does not create any side-effects and also has referential transparency. Any function that has referential transparency is said to be idempotent. // Add up the supplied numbers function good_add(a,b) { return a + b; } // Referential transparency means // called, as long as we pass the var ans1 = good_add(2,3); //  var ans2 = good_add(2,3); //  that no matter how many times function good_add() is same parameters, we'll always get back the same result 5 5 To achieve referential transparency (or idempotency), always ensure that a function: a) returns a value derived only from its parameters b) never relies on the value of global variables c) does not cause side-effects by modifying data outside its own scope © 2013 SAP AG. All rights reserved. 31
  • 32. Functional Programming A Simple Example From SAPUI5
  • 33. Functional Programming – Example from SAPUI5 1/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); © 2013 SAP AG. All rights reserved. 33
  • 34. Functional Programming – Example from SAPUI5 2/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) ‱ Attach the event handler function to the appropriate event of the UI element // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); // Attach event handler function to the "press" event of the button UI element btn.attachPress(evtHandler); Attach an event handler function © 2013 SAP AG. All rights reserved. 34
  • 35. Functional Programming – Example from SAPUI5 3/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) ‱ Attach the event handler function to the appropriate event of the UI element // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); // Attach event handler function to the "press" event of the button UI element btn.attachPress(evtHandler); Attach an event handler function © 2013 SAP AG. All rights reserved. Wait for an unknown period of time 35
  • 36. Functional Programming – Example from SAPUI5 4/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) ‱ Attach the event handler function to the appropriate event of the UI element // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); // Attach event handler function to the "press" event of the button UI element btn.attachPress(evtHandler); Attach an event handler function © 2013 SAP AG. All rights reserved. Wait for an unknown period of time Browser invokes event handler when event is triggered 36
  • 37. Functional Programming – Example from SAPUI5 5/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) ‱ Attach the event handler function to the appropriate event of the UI element // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); // Attach event handler function to the "press" event of the button UI element btn.attachPress(evtHandler); Attach an event handler function © 2013 SAP AG. All rights reserved. Wait for an unknown period of time Browser invokes event handler when event is triggered 37
  • 38. Functional Programming – Example from SAPUI5 6/6 Handling user events is an example of where we need to focus the how and not the when: ‱ Define a function to handle a particular pattern of data (E.G. a button push event) ‱ Attach the event handler function to the appropriate event of the UI element // Define an event handler function for a button UI element var evtHandler = function() { alert("B A N G !"); } var btn = new sap.ui.commons.Button({text:'Do not push this button'}); // Attach event handler function to the "press" event of the button UI element btn.attachPress(evtHandler); Attach an event handler function Wait for an unknown period of time Browser invokes event handler when event is triggered This style of programming focuses entirely on how the system should respond when a pattern of data is received (E.G. a UI event). When we respond is not important because the button might never be pushed! © 2013 SAP AG. All rights reserved. 38
  • 40. Functional Programming – Summary 1/2 Functional programming is style of coding that borrows heavily from a branch of mathematics known as Lambda Calculus. The functional programming style imposes the following constraints: ‱ ‱ ‱ ‱ ‱ Functions interact with each other only by means of parameters and return values. The use of internal variables to maintain program state is avoided (or in some languages prohibited). Side-effects are not permitted. Most functional programming languages do not have the concept of shared or global memory. Looping is handled by means of recursion, rather than explicit loop constructs such as do...while or for. The exact order in which functions are invoked is delegated to the language runtime on the basis of the data available at execution time. The appeal of the functional programming style is that if you strictly follow its design philosophy, it allows you to write coding that is provably correct (as apposed to hopefully correct). This feature has always had great appeal in academic circles, but with the increasing popularity of multi-core processors and the need to analyze ever increasing quantities of data, the use of the functional programming style is steadily increasing in the world of business programming. © 2013 SAP AG. All rights reserved. 40
  • 41. Functional Programming – Summary 2/2 Different functional programming languages implement these principles to varying degrees. Those languages that fully implement all the principles are said to be “purely functional” languages (such as Haskell or Miranda), with the rest being referred to as “impurely functional”. Impure functional languages are generally easier to code in because you do not need to resort to such deep levels of mathematical abstraction. Examples of impure functional languages include: ‱ Erlang ‱ F# ‱ Lisp ‱ R (Used internally with SAP’s HANA database) CAUTION! JavaScript is a multi-paradigm language! This means that both the imperative and functional styles of coding can co-exist within the same application. Care must be taken when designing JavaScript applications to ensure that confusion is not introduced into the architecture by a jumbled use of these different paradigms. © 2013 SAP AG. All rights reserved. 41