Wednesday, November 20, 2019

JavaScript - My Misc Notes

This blog is managed in 'JS - my notes.md' file

JavaScript - My Misc Notes

Scope

  • Lexical scope: function written within function can access all of the parent's vars and parms.
  • Function can be called before it is defined - before in the text.
  • You can define a regular function anywhere in the code.
  • Pronoun this is calculated when the code is executed. If we call a method that uses this outside of the object it belongs to, this will be undefined.

Modules

  • IIFE way
  • More common: define( [array], object); It comes from CommonJS and RequireJS more or less (see this). If object is a function, its parms are 1 to 1 with elements of the array, each of which specifies a dependency module e.g. 'rs/form/abstract/invoice.controller'. It is guaranted that the function will run only once even if more than one module list this module as their dependency.

Saturday, October 19, 2019

JavaScript ES6 / ES2015 - My Notes

JavaScript ES6 / ES2015 - My Notes

Using ES6 in Prod

  • Supported by modern but not by older browsers
  • So, ES6 needs to be transpiled or multipiled in prod

The let and const

  • const - generates an error when attempted to change value
  • both - block-scoped while var was function scoped (a block is just {...})
  • Now, instead of using IIFE, we can use a block. Variables (and function expressions assigned to variables) marked const or let will be private. While those marked with var will be public.

Strings

  • Template liters (note back-ticks): His name is ${firstName} ${lastName}.

Arrow Functions

  • If we have an array arr1, then arr1.map(el => 2 * el) will return an array of doubled numbers.
  • In fuller format:
    arr1.map((elem, index) => {
      ....
      return ...
    })
  • Arrow functions don't have their own this. They use the this of the function they written in - it's called lexical this.

Sunday, July 21, 2019

Ubuntu - Useful Tricks


  • In Files, to jump to another folder directly, press Ctrl-L and type the path.   Also, it's useful to bookmark the root folder (go to it and bookmark it from the menu)

Friday, July 5, 2019

JavaScript (ES5) - Long-time Java Developer Notes on Differences and Important Features

This highlighting is used code quoted in the text.  All of the below is all EcmaScript5 or earlier versions.


Basics:

  • Strings
    • Single and double quotes - no diff
    • A quote inside: \' or \"

Variables:

  • var names: start with a letter, $ or _.  Can't start with a digit.  Can't be a reserved word.
  • declare a var : var varName;
    This var will be of type undefined without any type.
    Note: a variable used without first defining it, defines and uses a global variable which is equivalent to the code: window.myVar = ...
  • But this one : var varName2 = '234';
    will be of type string
  • And after this : varName2 = 234; (this is variable mutation i.e. it gets a new value)
    The varName2 became a variable of type numeric (dynamic typing)
  • types: string, numeric, xxx or yyy .  No int type.

Conditional processing:
  • A structure I have never met in Java:
       switch(true) {
          case age > 21 && height > 1.65:
             aaa = 123;
          case age >= 65:
             aaa = 222;
      }
  • Falsy: 
    • undefined
    • 0
    • false
    • null
    • NaN
  • Equality operator (==) performs a type conversion (it's called type coersion in JS) so that: 23 == '23' evaluates to true.  Also console.log('he is ' + age + 'years old'); is fine even when age is numeric./
  • Strict operator === means 'the same type and the same value'
  • If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instanceif( typeof foo !== 'undefined' ) {...} but there is a function to check it, too.

Objects:

Primitive: a variable contains the value itself.
Object: the variable points to the object which is stored elsewhere.
  • Create objects (4 ways):
    • litera: var aaa = {name: "Ala", age: 53}   // it's an instance of Object() object
    • constructor methods (aka prototypes; not called classes):
      function Person(name, age) = {this.name = name, this.age = age};
      var p = new Person("Ala", 56)
        - it creates an empty objects and calls the constructor function with this set to the new object.
      • A method defined inside the constructor will not be shared among the children but separately recreated in each (memory!).  So, it's often better to Person.prototype.calcAge = function() {...}; instead.  This method will be shared by all children
    • Object.create(protoObject, { age: {value: 36}, fName: {value: 'Pawel'} }); but the 2nd parm is optional.  The value thing is not optional here.
  • Understand objects
    • An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value  can be anything including strings, integers, booleans, functions, other objects etc.
  • Create object, the minimalist version: var obj = {};
  • Always can extend an object from outside (No immutable objects?): obj['age'] = 56 or obj.age = 56
  • Or add a method
    obj.isAnAdult() { return this.age > 18; }  // the other syntax works, too
  • Functions are always objects (they're 1st class functions).  Create one, minimalist way function  foo() {}; and can add atributes or other methods the usual way: foo.age = 56
  • Summary: Practically everything is an object except primitive types (string, number and boolean), undefined and null (though null is considered an object, too).
  • If you want to know if a member exists independent but don't care what its value is:
    if ('membername' in object) // With inheritance VERIFY IF THIS ONE'S TRUE!!!
    if (object.hasOwnProperty('membername')) // Without in
    heritance
  • Clone: Object.assign(target, source)
    Watch out:  it is actually a merge of source into a target object, but Object.assign({}, source) will create a clone.  And, another warning: it's a shallow clone.
  • Inheritance is done in JS thru Prototype property which all objects have!!!  That property is used for children objects - any property or methods that we want the children objects to have access to, we put inside the Prototype property. The prototype property of object Object is null (here the protype chain stops when JS VM searches for a property or method of an object)

How does JavaScript work?

  • When method execution starts, first its execution context is created.
  • hoisting (during creation of the execution context for a method):
    • all declared functions are created before the execution for that method starts. But only declared function (not function expressions like var age = function(year) { ...}).  
    • thanks to hoisting, I can call functions that are declared later in the code.
    • all variables are created but set to undefined
  • Functions and only functions create a scope
    • Global scope is available to everyone
    • Functions written inside another function have access to the parent scope (or scopes if nested deeper)
  • Two types of functions:
    • regular (or declared) function - Just a function myFnc() {...}.
    • method - a function that is a value of an object (key, value) pair.
  • The this variable is part of the execution context and is set only at the moment when the function is called.  It's set to:
    • for regular functions, this is the Window object even if the function is defined inside of a method.
    • for method functions, the object in which the method is defined.

Interact with the Browser

  • DOM access: 
    • document.querySelector('#playerScore-' + activePlayer).textContent = score
      NOTE: querySelector finds only the first instance of a node satisfying the criteria
    • document.querySelector('.dice').style.display = 'none'
    • document.getElementById('player').classList.toggle('active')
  • Events:
    • Rule: Event gets processed only when the execution stack (where all exec contexts are placed) is empty (ie. all functions return)
    • When this happens the handler for the first of the events waiting in the event queue is called
    • doc.quSel(...).addEventListener('click', function() {....})
      arg1 - event type (see MDN for a table)
      arg2 - callback function

Console in the browser Dev Tools

  • > john - displays info about
  • > console.info(myArray) - displays more info than typing the object name directly
  • __proto__  - link to parent's prototype

Functions

  • IIFE ([ifee], Immediately invoked function expressions: (function (age) { var a = 5; ...})(5); .  The code inside the function is executed but variable a is hidden - data privacy. In JS, anything inside () is an expression.
    • Return from the function above an object with anything to be publicly available outside.
    • It's the module pattern
  • All functions in JS are closures.  Because functions have access to lexically outside scopes and (I think) scopes don't disappear.  Closures remember all vars and all parms of lexically outside functions.
  • Calling functions returned by functions: If fn1 returns a function, we can call it: fn1('John')(25);  where 'John' is an argument of fn1 and 25 is an argument of the functions that fn1 has returned.
  • Given, we have john object with a method presentation(style, timeOfDay) and emily object:
    • Function borrowing: john.presentation.call(emily, 'friendly', 'morning'); will execute the method for emily (every this will point to emily - use null if you don't need to redirect this)
    • Function borrowing with args in an array: john.presentation.apply(emily, ['friendly', 'morning']); 
    • Binding: 
      • var emilyFormal = john.presentation.bind(emily, 'formal'); will return a function with some parms preset (currying).  We can call it: emilyFormal('afternoon');.
      • Binding can also be used to set this for the function.

Friday, June 28, 2019

Building Java Applications with Gradle

Gradle wrapper:

  • In order to make sure you build the project with the same version of gradle as other developers (which can make a big difference), build the application using the wrapper: ./gradlew
    It will start with downloading the right gradle version, unless it's already there.
  • Watch out for running old gradlew for a version like 2.3 with a new java like version 11.  It quits silently without doing anything.

Useful commands:

  • gradle build -x test  -- run build but skip tests

Friday, June 7, 2019

Querying for Data in a Java Spring App - Alternatives


  1. Create a method with a name including all attributes you want to query by in your PersonRepository interface that implements CrudRepository<> (or PagingAndSortingRepository<>)
  2. Create a Specification object and use Spring findAll to find all records matching the Specification.
  3. Use @Query in the PersonRepository and define the query using JQL
  4. Use GraphQL (see for example https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.extensions.querydsl)

Monday, June 3, 2019

Unit testing with jUnit5 and Mockito

Mocking for Spring injected dependencies

import org.junit.jupiter.api.Test;

@ExtendWith(MockitoExtension.class)
class Person {
   @Mock
   DependencyA dependencyA;

   // Don't use @InjectMocks if using constructor injection with final dependencies.
   // Mockito can't set the new mocks for each test
   TestedClass target;

   @BeforeEach
   public void setup() {
      // only needed if you do Mockito.when(dependencyA.methodAbc()).thenReturn() or similar
      MockitoAnnotations.initialize(this);  
      target = new TestedClass(dependencyA);
   }

   @Test
   public void testMethodWhatsyourname() {
      // given
      ...
      
      // when
      target.whatsYourName();

      // then 
      ...
   }
}

Monday, May 20, 2019

Java Optional - Good Practice



  • orElseThrow: if personService.getAll() returns an Optional, then:
    return personService.getAll().map(converter::toResource).orElseThrow(
           () -> new NoResourceFound(...)
    );
  • orElse: if personService.getByLastName() returns an optional:
    return personService.getByLastName(lName).orElse(null);

Tuesday, April 30, 2019

Java Streams

Null elements in the stream

I thought, I saw a statement that Java streams filters out the null elements in the stream but the information must have been wrong.  So, if nulls are expected, or just in case, do:

... .filter(Objects::nonNull). ....

Monday, April 29, 2019

Java 9 - What's New In It


Modules

  • defined by file module-info.java in the module root directory
  • defines the module name, which package the module exports and
    what other modules it requires
  • if package org.sjb exports to a module, its subpackage isn't
    exported automatically; it can be exported by any module
  • each package is exported by a single module
  • jlink - packages a modules with all its required modules and the needed parts of the JRE into a standalone app which won't need Java to be installed where it runs
  • unnamed modules - all not defined stuff gets packed into a single unnamed module.  It exports all packages but only unnamed modules can call them.
  • automatic modules ...

Services


Using modules, the client code can receive all available implementations
  of an interface, and choose as one it needs (server and client are in the same JVM;
  it's not about http clients)

Monday, March 18, 2019

jUnit Fun

jUnit and Mockito Fun

More Interesting Elements of Unit Testing and Mocking


  • Verify that a method was called on a mock

    • Verify the parameters the method was called with
  • Return a custom response from a method called on a mock, response based on the parameters of the call
    Mockito.when(myMock.save(any(Person.class))).thenAnswer(i -> {
        Person person = (MyClass) i.getArguments()[0];
        return "Hello, " + person.getFirstName();
    });