Module Patteren and FP Intro Flashcards

1
Q

What is functional programming?

A

Това е стил на писане на код, който ни дава допълнителни patterns/структура с помощта на тези подходи решаваме често срещани проблеми в света на програмирането и прави нашия код по-лесен за разбиране и променяне.
Основната идея на функционалното програмиране е , че третира софтуера като една последователност от действия, които се изпълняват, като се продуцира резултат.
Като следваме този подход се стремим да не променяме състоянието на нашия софтуер, стойностите на променливи, обекти. Така намаляваме шанса някой да промени състоянието на програмата.
Imperative Pattern – описваме стъпка по стъпка какво искаме нашия софтуер на действа. Проблема е, че ние трябва да инвестираме много време за четене на този код.

Declarative Pattern – ние пишем какво искаме да се случи в кода ни, без да се влизаме в детайли как точно да се случи това (методи на масиви, а не for цикли).

// triple the value of every element in a given array
const triple = (arr) => {
  let results = []
  for (let i = 0; i < arr.length; i++){
    results.push(arr[i] * 3)
  }
  return results
}
// sum all the elements in a given array
const sum = (arr) => {
  let result = 0
  for (let i = 0; i < arr.length; i++){
    result += arr[i]
  }
  return result
}
// triple the value of every item in a given array
const triple = (arr) => arr.map((currentItem) => currentItem * 3)
// sum all the elements in a given array
const sum = (arr) => arr.reduce((prev, current) => prev + current, 0)
Functions are first class citizens – това означава, че можем да запазваме функциите в променливи също както в обикновена променлива. Също можем да ги подаваме като аргументи на други функции и също да ги връщаме каро резултат от други функции.
Higher order functions – това са функции които или приемат други функции като аргумент, или връщат функция като резултат.
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.
Functional programming is a programming paradigm, meaning that it is a way of thinking about software construction based on some fundamental, defining principles (listed above). Other examples of programming paradigms include object oriented programming and procedural programming.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a pure function?

A

Pure functions – това е функция, която:
• Не променя своите параметри – ако получи обект или масив, то тя не го променя когато се изпълнява
• Стойността, която те връщат не трябва да зависи на нещо друго освен параметрите, които получава
• По време на изпълнението на тази функция, тя не трябва да променя нищо извън нея, т.е. не би следвало да има side effect. По време на изпълнение на дадена функция трябва да избягваме това да боравим с данни, които не сме получили като параметър – да четем от конзолата, база данни, web
• Една функция е pure, когато при едни и същи входни данни, връща еднакъв резултат

A pure function is a function that:

  - Given the same input, will always return the same output.
  - Produces no side effects.

So, console.log( double(5) ); is the same as console.log(10);
This is true because double() is a pure function, but if double() had side-effects, such as saving the value to disk or logging to the console, you couldn’t simply replace double(5) with 10 without changing the meaning.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are side effects?

A

Side Effects

A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:

              - Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
              - Logging to the console
              - Writing to the screen
              - Writing to a file
              - Writing to the network
              - Triggering any external process
              - Calling any other functions with side-effects

Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a module and why would you use it?

A

It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope.

* It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.
* We expose certain properties and function as public and can also restrict the scope of properties and functions within the object itself, making them private.
* This means that those variables cannot be accessed outside the scope of the function.
* We can achieve data hiding an abstraction using this pattern
Immediately invoked function expression (IIFE) a standard IIFE looks like this:
(function () {
    // Code goes here
})();
The advantage of the IIFE is that any vars declared inside it are inaccessible to the outside world. So how does that help us? The key is that an IIFE can have a return value just like any other function.
var batman = (function () {
    var identity = "Bruce Wayne";
return {
    fightCrime: function () {
        console.log("Cleaning up Gotham.");
    },
        goCivilian: function () {
            console.log("Attend social events as " + identity);
        }
    };
})();
// Outputs: undefined
console.log(batman.identity);
// Outputs: "Attend social events as Bruce Wayne"
batman.goCivilian();

If you need to both enforce privacy for some of your data and provide a public interface, then the module pattern is probably a good fit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the revealing module pattern?

A

This is an updated pattern in which we could simply define all functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wish to reveal as public.
An example of how to use the Revealing Module pattern is as follows:

var myRevealingModule = function () {

        var privateVar = "Ben Cherry",
            publicVar  = "Hey there!";
        function privateFunction() {
            console.log( "Name:" + privateVar );
        }
        function publicSetName( strName ) {
            privateVar = strName;
        }
        function publicGetName() {
            privateFunction();
        }
        // Reveal public pointers to  
        // private functions and properties
        return {
            setName: publicSetName,
            greeting: publicVar,
            getName: publicGetName
        };
}();

myRevealingModule.setName( “Paul Kinlan” );

Advantages
This pattern allows the syntax of our scripts to be more consistent. It also makes it easier to tell at the end of the module which of our functions and variables may be accessed publicly, which eases readability.

Disadvantages
A disadvantage of this pattern is that if a private function refers to a public function, that public function can’t be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation, and the pattern doesn’t apply to public members, only to functions.
Public object members that refer to private variables are also subject to the no-patch rule.
As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly