Saturday, January 23, 2016

ANGULARJS - clean code patterns from John Papa

Tools:
WebStorm (prefered), Sublime, Visual Studio, Brackets, Atom

Repository:
https://github.com/johnpapa/ng-demos

Principles:
Separation of Concerns: 1 Component, 1 Role, 1 File
LIFT:
Locating our code is easy
Identifying code at a glance
Flat structure as long as we can
Try to stay DRY

Advance JavaScript by Kyle Simpson (my notes)

Kyle Simpson
https://www.patreon.com/getify?ty=h

https://developer.mozilla.org/en-US/docs/Web/JavaScript
http://www.ecma-international.org/ecma-262/6.0/index.html
https://github.com/rwaldron/idiomatic.js

https://en.wikipedia.org/wiki/Just-in-time_compilation
JIT compilation - just-in-time (JIT) compilation, also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution.

Compiler terminology:
LHS - left hand side for an assignment
RHS - right hand side for an assignment
var foo = 'bar'
var foo here is LHS reference an it is TARGET
'bar' is RHS reference and it is a SOURCE

Scope
function baz(foo) {
     foo = 'bam';
     bam = 'yay'
}

foo here would be the local scope variable created in compile time
bam in NO STRICT mode will be created as a global variable during run time, cause in local scope it will not be founded.
bam in STRICT mode will produce error because bam never was created either in local or global scope. 
This happen because declaration in JS goes only with VAR or FUNCTION words
Undeclared variable means we unable to find proper LHS reference in any of the scopes that we have access to. 

In JS undeclared and undefined are totally different words.

Undefined variable - variable that was declared, but has special empty value that was mistakenly named in JS as undefined (should be named with better word). 
Undefined is an actual real value for empty value, it is a type. (e.g. there cannot be a vacuum where value exist)

bar(); it is RHS because... it is not LHS :) (it has not '=' sign)


function baz(foo) {
     var foo = 'bam';
     bam = 'yay'

     finction bam() {
        var baz = 'bla';
     }

     bam();
}

bam(); if this function would be called from global scope it will produce reference error

FUN http://my-fly.ru/blog/43082783722/Retsept-schastlivoy-zhizni-po-odesski 

There could be only two cases: 
OR Function Declaration: (if the 'function' word is the the very first word in the statement)
function bar() {

OR Function Expression: (the 'function' word is NOT the first word in the statement)
var bla = function bar() {
}
bar(); //will result in ERROR if it is called outside of local scope

ALWAYS use Named Function Expression instead of Anonymous. 
It results in 3 advantages:
- it gives self reference inside the local scope
- it allows debugging the function
- its name gives description for what it is doing

EVAL keyword is a way of cheating compiler, making it think that parameter of eval was created before. For instance:

var bar = 'bar';
 
function foo(str) {
    eval(str); //cheating
    console.log(bar); //it will print 42, not 'bar'
}

foo('var bar = 42;');

NEVER use 'eval' as well as 'with' statement (even if the strict mode does create for it new scope)

I I F E pattern
The IIFE term was invented by Ben Alman ('Cowboy') http://benalman.com/
IIFE sometimes rendered as “self-executing anonymous function” (or self-invoked anonymous function) 
I I F E - Immediately Invoked Function Expression 
The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

CLOSURE (First-class functions)
Closure is when a function 'remembers' and access its lexical scope even when the function is executed outside that lexical scope.


http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
https://en.wikipedia.org/wiki/Closure_%28computer_programming%29
https://en.wikipedia.org/wiki/First-class_citizen

Any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure)
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
A closure is a function called in one context that remembers variables defined in another context – the context in which it was defined.
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/



SCOPE
Lexical scope - has author scope (JavaScript)
Dynamic scope -  has run time (Bash)
Scope can be created by:
- Functions
- Curly braces and keyword let
- Try and catch block


Cheating scope by eval and with keywords.

HOISTING
It is invented terme to explain how JS works.
Function hoisted first, before variables.
Keyword let is not hoisted.

THIS
Every function, while executing, has a reference to its current execution context, called THIS

4 Binding Rules of THIS by order. Rules of precedence by Call Side:
- Default binding rule:
In strict mode of current function this = Undefined value, else = global object

- Implicit binding rule:
function foo() { console.log(this.bar) } 
var bar = 'bar';
var o2 = { bar: 'bar2', foo: foo};
foo(); //bar
o2.foo(); //bar2 it is implicit binding

- Explicit binding rule: use of call or apply in call side with object in its parameter.
bar.call(obj) - use this of passed in param obj.
Hard explicit binding is encapsulate bar.call(obj) in IIFE

By NEW binding
- Create new object
- Link this new object with other object
- New object bound to THIS for the purposes of the function call
- Implicitly insert at the end of function return this; if no other return is provided.

Classic Module Pattern
- It must be executed in the outer wrapper function (not necessary IIFE)
- One or more function that get returned from that function call

Principle of Least Privilege, or Least Exposure (make everything private and only expouse what needs to be public e.g. executing foo.bar(); // bar)
The object of return is public API of module. Inside is its private encapsulated data.
var foo = (function () {
    var o = { bar: 'bar' };  
    return {
         bar: function() {
              console.log(o.bar);
         }
   }
})();
foo.bar(); //bar 


Modified Module Pattern (much more organized)
It is better use object variable instead of anonymous function. It can be updated in run time.
var foo = (function () {
    var publicAPI = {
      bar: function() {
           publicAPI.baz();
      },
      baz: function() {
           console.log('baz');
      }
    }
   return publicAPI;
})();
foo.bar(); //baz 

Module Pattern in ES6
It is better use object variable instead of anonymous function. It can be updated in run time.
E.g. module goes in separate foo.js file:
var o = { bar: 'bar' };
export function bar() {
    return o.bar;
}

From other test.js file:
import bar from 'foo'; //will import just one function from that module 
bar(); //bar 

module foo from 'foo';
foo.bar(); //bar 


Object Orienting
A constructor makes an object linked to (not to be 'based on') its own prototype.

PROTOTYPE
__proto__ is a public link to the internal property of [[ prototype ]] . It is pronounced as kind of 'donedoproto', It was invented by Mozilla and supported for all other browsers except... IE till the version 11 (Edge).
__proto__ became standard only since ES6.
[[ prototype ]] . Is a linkage from one object to another.





var a1 = new Foo('a1');
a1.__proto__ //even in IE
a1.__proto__ === Object.getPrototypeOf(a1); //prior to IE 11
a1.__proto__ === a1.constructor.prototype; //always available, but it is writable function

Using polymorphism avoid shadowing of properties names of object and its prototype.

Objects Linked

function Foo(who) {
    this.me = who;
}

function Bar(who) {
    Foo.call(this, who); //way 1
}

Bar.prototype = Object.create(Foo.prototype); //way 2

Inheritance vs. Behavior delegation
var a1 = new Foo();
Foo.prototype.speak = function....
a1.speak() //this is Behavior delegation from object to its prototype (it is not by copying)

OLOO pattern
Object Linked Other Object



Async callbacks

Generators in ES6
It is a new kind of function: function*
It can stop on keyword yield
It can return kind of iterator
yield null - its a kind of way to send messages to the generator.
Its a two way passing messages mechanism.
It should eliminate Promises and callbacks.



This example shows how generators could work asynchronous way, 
even if it looks like synchronous.


Combination of Generators and Promises is the future!

No Threads just Shared Memory with Events Loop