Saturday, October 24, 2015

Java - New features in Java 8 - default method

Introduction:
Java 8 introduces 'default' method declaration in interfaces. The idea behind this to make a change in the interface (adding new method signature) without affecting already implemented classes of the interface. This a nice thing to kept the old implementations intact still adding new features whoever needs it. See Example-01.


Notes:
1. Extend an interface with a default method 

  • Not mention the default method at all, which lets your extended interface inherit the default method
  • Re-declare the default method, which makes it abstract
  • Redefine the default method, which overrides it
2. Conflict with multiple interface - if a class uses multiple interfaces having same default method signature, the implementation class should explicitly specify which default method to use or define it's own one. Because the implementation class does not know which default method to use. See Example-02

Examples:

Example-01: Bird class inherits FlyInterface where the interface has a default implementation which Bird class is happy with rather than providing it's own implementation.

BehaviorInterface 
public interface BehaviorInterface {
public default void fly(){
System.out.println("Generic fly");
}
public default void sing(){
System.out.println("Generic sing");
}
public void swim();
}


Bird:
public class Bird implements BehaviorInterface{

public Bird(){
System.out.println("A bird is created");
}
@Override
public void swim(){
System.out.println("Swim by me");
}
@Override
public void sing(){
System.out.println("My own singing");
}
}

Test above implementation:
public class TestBird {
public static void main(String[] args){
Bird aBird = new Bird();
aBird.fly();
aBird.sing();
aBird.swim();
}

}
Output:
A bird is created
Generic fly
My own singing

Swim by me

Example-02: Two interface with same default method would throw compile time error 'Duplicate default methods named speed with the parameters () and () are inherited from the types SwimInterface and FlyInterface'.

FlyInterface
public interface FlyInterface {
public void fly();
public default void print(){
System.out.println("Print in FlyInterface");
}

}

SwimInterface
public interface SwimInterface {
public void swim();
public default void print(){
System.out.println("Print in SwimInterface");
}

}

NewBird
public class NewBird implements FlyInterface, SwimInterface {
public NewBird(){
System.out.println("A new bird is created");
}
@Override
public void swim() {
System.out.println("My swim implementation");
}
@Override
public void fly() {
System.out.println("My fly implementation");
}
@Override
public void print(){
System.out.println("I am forced to provide specific implementation");
FlyInterface.super.print();
SwimInterface.super.print();
}

}

Test above implementation 
public class TestNewBird {
public static void main(String[] args){
NewBird aBird = new NewBird();
aBird.fly();
aBird.swim();
aBird.print();
}

}

Output:
A new bird is created
My fly implementation
My swim implementation
I am forced to provide specific implementation
Print in FlyInterface

Print in SwimInterface

Resources:
1. https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
2. http://www.programcreek.com/2014/12/default-methods-in-java-8-and-multiple-inheritance/




Friday, October 23, 2015

Design pattern - Strategy pattern

Description:
Define a family of algorithms, encapsulate each one and make it interchangeable. Strategy lets the algorithm vary independently from the client use it.

In short - "Encapsulates an algorithm inside a class"

Problem:
Sometimes new behavior or algorithm or action on related objects are changed or new implementation needs to be provided. Using interface leaves each concrete class to have it's own implementation, no way to reuse/leverage exists implementation. Using class inheritance leaves in situation where all sub classes are forces to provide implementation of the behavior even not appropriate to that sub class.
Strategy pattern encapsulates set of behaviors/algorithms/actions in a separate hierarchy allowing client to use algorithm without knowing implementation and run time change of algorithm. Other hand behavioral implementation changes can be done without affecting client.

How to use Strategy pattern:
1. Concepts involved in Strategy pattern, 'context', 'abstract behavior', 'concrete behavior' 

2. Create an interface 'behavior' with abstract method (like execute/do). 

3. Create derived concrete class(es) from 'behavior' base class which will provide the implementation of the abstract method(s) of interface. Each concrete class will have alternative implementation detail

4. Need to create separate behavior interface and concrete class creation for each set of behaviors

5. Client will create an instance of concrete behavior and store it in abstract reference. Client class will have a entry point (a method) which will make the abstract method call on abstract reference

  • Most of the times, client side has a hierarchy where concrete classes derived from an abstract class, the abstract class holds the reference of strategy provided by concrete class and has a method to make a call to abstract strategy reference without knowing the actual concrete class.

Class diagram:























Examples:
1. Duck pond simulation game from Head First Design Pattern. The large variety of duck species can swim but in need of adding behaviors like fly, make quacking sounds on some specific kind of ducks. Fly behavior can be externalized through strategy and ducks would just use composition of fly behavior.

2. Modes of transportation to an airport is an example of a Strategy. Several options exist such as driving one's own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time. (Resources-2)

3. A car objects break behavior can be considered as strategy where regular break or ABS break can be used based on need.

Benefits:
1. Decouples the algorithm/behavior from client who would use it
2. Allows client to pick any implementation of algorithm/behavior
3. Allows algorithms/behaviors to interchange without affecting client
Notes:
1. Strategy pattern uses composition between objects rather than inheritance 
2. Follows 'Open/Closed Principle' of OO Design Principle
3. Abstract coupling - client is coupled only to an abstraction and not a particular realization of that abstraction
4. Ideally client should have a mean (mostly using setter method) to change strategy


Things to check back:
1. Coexistence with other patterns


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/strategy_pattern

Sunday, October 18, 2015

Bootstrap - concepts

About bootstrap:

  • Uses HTML, CSS and Javascript
  • front-end framework
  • Easy and faster to use and develop 
  • Responsive design 
  • Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core framework 
  • Browser compatible 


Bootstrap concepts:


  1. Application setup with bootstrap 
    1. Reference to bootstrap
      1. Download - http://getbootstrap.com
      2. CDN - 
        1. CSS - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css
        2. JavaScript - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
    2.  <!DOCTYPE html> at the beginning of the html page
    3. Mobile first settings - '' 
      1. Width is the width application should take to display
      2. initial-scale - initial zoom of the page
    4. Container - bootstrap requires a containing element to wrap site contents. There are two container classes to choose from - 
      1. .container - class provides a responsive fixed width container
      2. .container-fluid class provides a full width container
         
  2. Bootstrap Grid System - grid systems are used for creating page layouts through a series of rows and columns that host application content
    1. Rows must be placed within a .container class
    2. Content should be placed within the columns, and only columns may be the immediate children of rows
    3. Predefined grid classes
      1. .row
      2. .col-xs-<#> .col-sm-<#> .col-md-<#> .col-lg-<#> - # could be 1-12
    4. Multiple column classes can be used to support wide range of devices  
  3. Normalize - bootstrap uses Normalize to establish cross browser consistency in the default styling of HTML elements. Normalize.css is a modern, HTML5-ready alternative to CSS resets. CSS reset is to set styling to html elements to null thus avoiding cross-browser differences as much as possible
     
  4. Text emphasis - text-left text-center text-right text-muted text-primary text-success text-info text-warning text-danger.
     
  5. List - list-unstyled list-inline.
     
  6.  Bootstrap tables - 
    1. base table markup - table 
    2. Optional markups - table-striped table-bordered table-hover.(example
    3. Contextual classes - active success warning danger. (example)
    4. The .table-responsive class creates a responsive table. Put this class in a div which holds a table
       
  7. Bootstrap form layouts- 
    1. Types
      1. Vertical (default) form 
      2. In-line form 
      3. Horizontal form
    2. Rules to follow 
      1. improve accessibility - always use >form role="form"< 
      2. optimum spacing - wrap labels and form controls in >div class="form-group"< 
      3. class .form-control to all textual input, textarea and select elements
      4. For Horizontal form - 
        1. Add class .form-horizontal to the
          element 
        2. Add class .control-label to all
        3. Use grid classes to align labels and groups of form controls
    3. Example - includes all three type of forms  
  8. Alert - 
    1. Create an alert 
      1. Use .alert class in a div
      2. Followed by one of four contextual classes .alert-success, .alert-info, .alert-warning or .alert-danger.
    2. To add close functionality
      1. Add a link or button element in alert div
      2. add class="close" and data-dismiss="alert".
      3. Use × (×) HTML entity for close buttons
    3. Animated alert - add class fade in in alert div.
       
  9. Dropdown - (example)
    1. To create
      1. Mark a div with class="dropdown".
      2. Add a button or link to open dropdown menu with "class=dropdown-toggle" and data-target="dropdown".
      3. Add class="caret" in a span element to show dropdown arrow
      4. Add class="dropdown-menu".
    2. Dropdown divider - class="divider" in li element
    3. Dropdown header- class="dropdown-header" in li element
    4. Make it accessible to screen readers
      1. Add role="menu" and aria-labelledby="aName" in ul element
      2. Add role="presentation" in li element
      3. Add role="menuitem" in HTML element used inside li
  10. Panel
    1. Create with .panel class in a div
    2. need to define panel-header panel-body panel-footer
    3. Contextual classes - panel-default panel-success panel-info panel-danger panel-warning panel-primary.
    4. To group panels - panel-group.
  11. Collapsible
    1. On button or link
      1. Create a div with collapse class
      2. Create a link or button HTML element with data-toggle="collapse" and data-target="#div_id". This is to show/hide the collapsible div
    2. On a panel - (example)
      1. Add button or link in panel header (see above)
      2. Put panel body and footer in a div with classes panel-collapse collapse.
    3. Accordion - (example)
      1. Panel group div should be ided with a name
      2. Use the data-parent attribute to specify the div id - all collapsible elements under the specified parent will be closed when one of the collapsible item is shown
         
  12. Tabs
    1. Tabs are created with $gt;ul class="nav nav-tabs"<.
    2. Current page is marked using class="active" in li element
    3. Use dropdown creation structure in a li which needs to be displayed as dropdown and mark that li with class="dropdown". (example)
    4. dynamic tabs
      1. add the data-toggle="tab" attribute to each link
      2. add a .tab-pane class with a unique ID for every tab
      3. wrap them inside a div element with class .tab-content
    5. Pills - similar concept as tab. Most cases replacing tab with pill will work
  13. Modal - (example)
    1. Use a button or a link with attributes: 
      1. data-toggle="modal" opens the modal window 
      2. data-target="#id" points to the id of the modal
    2. Defining modal 
      1. The parent div of the modal must have an ID, will be used in data-target attribute and .modal class 
      2. The attribute role="dialog" to improve accessibility 
      3. The .modal-dialog class sets the proper width and margin of the modal. 
    3. Defining modal content
      1. A div with class="modal-content" 
      2. Add the modal's header .modal-header, body .modal-body, and footer .modal-footer
      3. To add close feature in header
        1. Add a button/link inside the header with data-dismiss="modal"
        2. Add .close class styles the close button
      4. Add .modal-title class styles the header with a proper line-height.
  14. Images - below classes need to use in img html element
    1. img-rounded img-thumnail img-circle img-responsive.
       
Note:
1. To learn about bootstrap elements which are not mentioned and know more in detail about the elements explained, see the resources



Resources:
1. http://www.w3schools.com/bootstrap/
2. http://www.tutorialspoint.com/bootstrap/

Saturday, October 17, 2015

JQuery - Handout - quick memory refresher

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.

About jQuery:

1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming


jQuery concepts:

  1. Pointing to jQuery
    • From local reference - ''- assuming jquery.js file is in same folder with the html
    • Content Delivery Network (CDN) based - 'src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"'
       
  2. launching code - Option-02 is prepared as that's invoked as soon as the DOM is ready rather waiting the page loaded fully (including images)
    1. Option-01: window.onload = function() { //code};
    2. Option-02: $( document ).ready(function() { //code });
    3. Option-03: is shortcut to option-02. '$(function(){ //code});'
       
  3. Callbacks and functions - A callback is a function that is passed as argument to another function and will be executed only after the function where it's passed has completed
    1. Callback without Arguments - '$.get('aPage.html', callBackFn);'
    2. Callback with Arguments - 
      1. Not possible - '$.get('aPage.html', callBackFn(param1, param2));'. This will execute the callBackFn first and return of it will be passed to get function
      2. Correct way - '$.get( "aPage.html", function() { callBackFn( param1, param2 ); });'
         
  4. $ vs $()
    1. Methods called on jQuery selections (used $()) are in the $.fn namespace, and automatically receive and return the selection as this
    2. Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments
        
  5. Ways to avoid conflict with other libraries
    1. new alias - noConflict returns a reference to jQuery function
      'var $j = jQuery.noConflict();'
    2. use self invoking function -
      'jQuery.noConflict();(function($){ //code})(jQuery);'
    3. Argument through jQuery(document).ready() function
      'jQuery(document).ready(function( $ ) { // code });'
       
  6. Selecting elements
    1. by 
      1. tag name - '$("aDOM");'
      2. ID - '$("#idToFind");'
      3. class name - '$(".className");'
    2. Pseudo selectors - :visible :enabled :checked :text :button :file (see references for complete list)
    3. comma to use to select multiple DOM objects
    4. chaining - any method call on a selection returning a jQuery object, allows to call jQuery method on the object without pausing for a semicolon.
      '("#aDiv").find("p").eq("1").html("Changed text");' - find second p in a dive called aDiv and change content
       
  7. Methods - 
    1. getter/setter - html, text, val - can be both setter (with argument) or getter (no argument) 
    2. Move, copy and remove elements
    3. Attributes - .attr() to get/set value to selector's attribute.
      1. Object of key-value pair can be passed to set multiple
         
  8. Selection traversing
    1. parents - .parent() .parents() .parentUntil() .closest()
    2. children - .children() .find().
    3. Siblings - .prev() .next() .siblings() .nextAll() .prevAll() .nextUnti() .prevUntil()
    4. Styling and dimensions
    5. CSS classes - addClass("aClass") removeClass("aClass").
    6. Dimensions - width, height - getter/setter
        
  9. Data methods - stores data to the element and manages the memory issues.
    '$("#aDiv").data("aKey", {name:"Riaz"});' '$("#aDiv").data("aKey");'
      
  10. Utility methods - 
    1. $.trim() - 
    2. $.each() - generic iterator function for looping over object/arrays/ array-like objects
      example:
      '$.each([1,2,3,4], function(idx, val){ console.log("Element "+idx + " is "+val);});'
      output:
      Element 0 is 1
      Element 1 is 2
      Element 2 is 3
      Element 3 is 4
       
    3. $.proxy(function, scopeObj) -
      example:
      var aFn = function() { console.log( this ); };
      var aObj = { name: "Riaz" };
      aFn();
      var proxyAFn = $.proxy( aFn, aObj );
      myProxyFunction();

      Output:
      Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…}
      Object {name: "Riaz"}
       
    4. $.type() - returns the type of passed object
    5. .map() - returns array from matched elements from selector
        
  11. jQuery events - 
    1. Some common events
    2. Mouse Event Key Event Form Event window Event
      click keypress submit load
      dblclick keydown change unload
      mouseenter keyup focus size
      mouseleave    blur scroll
    • Event call syntax - 
      • Assign an event - $("p").click();
      • Indicates what should happen after event -
        $("p").click(function(){ /*actions*/});
    • Usage of '.on()'. 
      • All the methods above are shortcut of this
      • Syntax - '$("p").on("click", function(){/*actions*/});'
    • Handling event - 
      • Many events single event handler - comma separated events
      • Multiple event and event handler association -'$( "p" ).on({ "click": function() { console.log( "clicked!" ); },
        "mouseover": function() { console.log( "hovered!" ); } });
        '
      • Data can be passed to event -
        '.on( "click", {name:"Riaz"}, function(event){ console.log("Name:"+event.data.name");});'
    • Instead of anonymous function, a named function can be passed as event handler 
    • Namespacing event - for complex and plugin application, it's a good idea to namespace application specific events to avoid conflict 
    • tead down events
      • Unbind all click event - $( "p" ).off( "click" ); 
      • Unbind only aHandler from click - $( "p" ).off( "click", aHandler );
    • Event handler to run only once - using '.one(...)'
    • Properties and method of eventhanlder
      • Properties - pageX pageY which type data target namespace timestamp etc.
      • Methods - preventDefault() stopPropagation() etc
12. Ajax in jQuery
  • Syntax - '$.ajax(...)'
  • Data types - type of data you expect to get back from an Ajax request
    • text html script json jsonp xml
  • API -
    // Using the core $.ajax() method
    $.ajax({
    // The URL for the request
    url: "- page url",
    // The data to send (will be converted to a query string)
    data: {  },
    // Whether this is a POST or GET request
    type: "GET",
    // The type of data we expect back
    dataType : "json",
    // Code to run if the request succeeds;
    success: function( json ) { /* do something */ },
    // Code to run if fails; raw request and status codes are passed
    error: function( xhr, status, errorThrown ) { /* do something */ },
    // Code to run regardless of success or failure
    complete: function( xhr, status ) { /* do something */ } });
  • Convenient functions - below functions are wrapper around core .ajax()
    • functions - $.get $.post $.getScript $.getJSON
    • parameters - 
      • Required - url
      • Optional - data success dataType
  • Ajax events
    • Local events - specify within ajax request object
      • beforeSend success error complete
    • Global events
      • ajaxtStart ajaxStop
13. Serializing form data
  • Using $("#aForm").serialize() - serializes form data into a query string
  • Using  $("#aForm").serializeArray() - serializes to array of objects

Resources:
1. http://api.jquery.com/
2. http://www.w3schools.com/jquery/
3. https://learn.jquery.com/

    Friday, October 16, 2015

    Design Pattern - Command pattern

    Description:
    The command pattern encapsulates a request as an object to perform an operation on an object (receiver). This allows client to parameterize other objects (invoker) with different requests, queue or log requests, and support undoable operations.

    In short - "Encapsulate a command request as an object"


    Problem:
    Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

    How to use Command pattern:
    1. Concepts involved in Command pattern, 'receiver', 'invoker' and 'command'

    2. Create an interface 'command' with abstract method 'execute'

    3. Create derived concrete class(es) from 'command' base class which encapsulates a 'receiver', a method to invoke and the arguments to pass

    4. 'Receiver' is actually responsible to perform the desired action which is encapsulated in the 'command' as attribute. Mostly passed to command through constructor

    5. 'Invoker' gets the command object(s) through method like 'setCommand(Command)' and provides a mean to make a call to 'command' class's 'execute' method

    6. Client of Command pattern creates a concrete 'command' object, passes reciever to it and sets it to 'invoker' by making call to 'setCommand(Command)'. Later client asks 'invoker' to execute the command.

    Class diagram:


























    Benefits:
    1. decouples the object that invokes the operation from the one that know how to perform it
    2. Allows parameterization of clients with different requests
    3. Allows invoker to save request in a queue
    4. Undo and redo functionality can be implemented as 


    Notes:
    1. Macro Command - represents set of commands to be performed on call to be executed. Macro commands can be implemented as Composite, can also have other operation like undo, redo, forward/backward traversing, logging, queue etc.
    2. Undo/redo action - can be performed two ways
    • Store receiver's previous state in memory
    • Store set of performed actions on receiver in memory
    3. Queuing the requests - as the commands are isolated from invoker, those can be executed asynchronously in background of an application. Usually invoker keeps a set of commands, runs in main thread and action request to receiver can happen in a separate thread. To have faster processing, multi-thread can be considered to run through the set of commands. Scheduler, thread pool, job queues etc. applications can be considered as good example of this scenario.



    Things to check back:
    1. Coexistence with other patterns
    2. Alternates of Command patterns


    Resources:
    1. Head First Design Pattern
    2. https://sourcemaking.com/design_patterns
    3. https://en.wikipedia.org/wiki/command_pattern

    Thursday, October 15, 2015

    Design Pattern - Iterator pattern

    Description:
    "The Iterator Pattern provides a way to access the elements of an aggregate object without exposing its underlying representation".

    This simplifies aggregate interface and implementation by placing traversal responsibility on iterator and this traversal of a collection is promoted to a full object comparing to a logic embedded in the aggregate.  In the process helping the client of aggregate object a polymorphic traversal.

    In short - "Sequentially access the elements of a collection"


    How to use Iterator pattern:
    1. Two types of objects needed, one is called 'aggregate', other is called 'iterator'

    2. "Aggregate" abstraction should have a method (i.e. createIterator) to create corresponding iterator

    3. Each derived concrete class of aggregate base class has to provide implementation of the abstract method (i.e. createIterator)

    4. Create abstract "iterator" base which can have method like next, hasNext, remove. See Note-3 and 4 to know more 

    5. Each derived concrete class of "iterator" base class should provide implementation of methods described in the "iterator".

    6. The client will create necessary aggregate object based on collection structure and ask for "iterator" from the aggregate object which will return a concrete iterator as generic type. 



    Class diagram:





















    Benefit:
    1. Aggregate object can have it's encapsulation intact without exposing how the collection structure is defined
    2. Allows the client to traverse different ways
    3. Supports multiple simultaneous traversal on a collection
    4. Provides uniform interface to traverse heterogeneous collections


    Notes:

    1. Internal Iterator vs External Iterator - java.util.Iterator is an external iterator as client has to control the iteration. Internal iterator is controlled by the iterator itself and client has to inform the iterator needs to be done as it iterator through.

    2. Robust Iterator - the iterator can provide both insertion and deletion during traversal and doesn't make a copy of the aggregate. This iterator makes sure the element(s) not fetched twice or skipped due to insert or delete in the collection. 

    3. java provides java.util.Iterator which can be used in most of the cases. This interface has three methods (next, hasNext, remove). If derived concrete Iterator doesn't need to support for remove method, java.lang.UnsupportedOperationException can be thrown.

    4. An Iterator can be defined to move backwards as well forwards. Java provides such interface java.util.ListIterator with next, hasNext, previous, hasPrevious, remove methods along with other like (nextIndex, previousIndex, set, add).

    Things to check back:
    1. How to write a thread safe, robust Iterator


    Resources:
    1. Head First Design Pattern
    2. https://sourcemaking.com/design_patterns
    3. https://en.wikipedia.org/wiki/Iterator_pattern 

    Tuesday, October 13, 2015

    Design Pattern - Visitor pattern

    Definition:
    From gang of four -  "Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates".

    Head First - "Use the Visitor pattern when you want to add capabilities to a composite of objects and encapsulation is not important".

    In short - "Defines a new operation to a class without change"

    How to use Visitor pattern:
    1. Two types of objects needed, one is called 'element', other is called 'visitor'

    2. Create a base visitor class hierarchy with "visit" method for each concrete derived class the composite hierarchy. Each "visit" method accepts a single argument - reference to the original element derived class

    3. Each derived concrete class of visitor base class has to provide implementation of each "visit" method

    4. Add abstract/virtual "accept" method in base element hierarchy. This takes an argument of abstract base class of visitor hierarchy 

    5. All sub-element or derived concrete classes has to provide implementation of "accept" method by simply calling "visit" method of passed concrete Visitor class where "this" is passed as reference

    6. For any operation needed for client will create and instance of concrete visitor class and pass that as reference to "accept" method in each concrete element class. The client of Visitor pattern is called traverser which knows how to guide the visitor through the composite structure. 

    Class diagram:


















    Examples:
    1. A restaurant Application might have menu, menu item and ingredient objects with related attributes and operations. If reality changes where customers demand nutritional information on menu items as well as on ingredients, rather making elements (menu, menu item, ingredient etc) level changes visitor pattern can be implemented.

    2. A Shopping cart where we can add different type of items (Elements), when we click on checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using visitor pattern

    Benefit:
    1. Allows to add operations/functionalities to a composite structure without changing the structure itself
    2. Adding new operations/functionalities is relatively easy
    3. The code for operations performed by the Visitor is centralized

    Trade-off:
    1. The composite classes' encapsulation is broken when the visitor pattern is used
    2. Because the traversal function is involved, changes to composite structure are more difficult


    Notes:
    1. Double dispatch - the operation executed depends on: the name of the request (method name), and the type of TWO receivers (the type of the Visitor and the type of the element it visits)

    From above class diagram double dispatch can be as below - 
    • When the accept method is called in the program, its implementation is chosen based on both: 
      • The dynamic type of the element. 
      • The static type of the visitor. 
    • When the associated visit method is called, its implementation is chosen based on both: 
      • The dynamic type of the visitor. 
      • The static type of the element as known from within the implementation of the accept method, which is the same as the dynamic type of the element. (As a bonus, if the visitor can't handle an argument of the given element's type, then the compiler will catch the error.) 
    • Consequently, the implementation of the visit method is chosen based on both: 
      • The dynamic type of the element. 
      • The dynamic type of the visitor.

    2. A more flexible approach to this pattern is to create a wrapper class implementing the interface defining the accept method. The wrapper contains a reference pointing to the 'abstract base element' which could be initialized through the constructor. This approach avoids having to implement an interface on each element. (Resource-04)


    Resources:
    1. Head First Design Pattern
    2. https://sourcemaking.com/design_patterns
    3. https://en.wikipedia.org/wiki/Visitor_pattern
    4. Java Tip 98: Reflect on the Visitor design pattern

    Thursday, October 1, 2015

    JavaScript - Karma - Setup - prepare the environment to work with karma

    Introduction:
    This article covers how to setup karma and run a sample test to make sure installation worked without any issues. Both local and global installation will be covered. Karma installation depends on some other dependent technologies which are not part of this article. 

    Brief introduction about the technologies involved:

    Node:
    • Considered as server side JavaScript or browser less JavaScript
    • JavaScript runtime built on Chrome’s V8 JavaScript engine
    • Node uses event driven, non-blocking I/O model which makes it lightweight and efficient

    npm:
    • This is a package manager for JavaScript is default for Node.js
    • Elaboration is 'Node.js Package Manager'

    karma:
    • Test Runner tool for JavaScript invented by AngularJS team 
    • Karma runs on Node.js and is available as an NPM package
    • Test runner means way to run jasmine/mocha (Javascript unit test tool) without loading explicitly in the browser. To confuse thing, it's testing without the browser in the browser. 

    Karma setup:
    Karma installation needs node and npm installed prior. So those two installation will be covered first. 

    Environment info:
    • Operating system - Windows 2008 R2
    • node version - 4.1.0
    • npm version - 3.3.3

    1. Setup node:
    • Link to download: https://nodejs.org/en/
    • Click on download button which will download file ‘node-v4.1.0-x64.msi’
    • Execute the msi file. Setup wizard is simple enough, just click on Next button
    • It will install command prompt and node.js, both are shell/command prompt. Node.js is used for node programming.
    • Test installation’s done successfully. Use command prompt. Run ‘node –v’. returned 4.1.0.

    2. Update npm
    • Node is bundled with a version of npm. However, npm gets updated more frequently than Node does, so it’s a good idea to upgrade npm. Before upgrading npm, run ‘npm -v’ which returned ‘2.14.3’.
    • Install npm – execute command ‘npm install npm -g’ in ‘node command prompt’
    • Check upgraded version. Execute ‘npm -v’ which returned 3.3.3.

    3. Install karma:
    Karma can be installed per project or in global context accessible for each project. 

    Local installation:
    • Go to the folder where karma needs to be installed
    • Execute command 'npm install karma' from 'node.js command prompt
    • This will create a folder called 'node_modules'. Actually installing any npm package will create that folder where all the dependent modules will be installed
    Global installation:
    • Execute command 'npm install karma -g' from 'node.js command prompt. -g argument indicates installation in global space. 
    • The 'node_modules' will be created in the user's directory.

    4. Install dependencies
    Karma requires to install test tool, browser launcher etc. Below commands will add all the dependencies need to run the karma locally. Just add -g to install globally.  

    - 'npm install karma-jasmine --save-dev'
    - 'npm install karma-requirejs --save-dev'
    - 'npm install karma-phantomjs-launcher --save-dev'
    - 'npm install karma-chrome-launcher --save-dev'


    5. Initialize karma:
    • Command: 'node node_modules/karma/bin/karma init'. This will ask series of questions.
    • Testing framework - default jasmine. Use up or down arrow keys to select preferred one
    • Need requireJS - default no. Up arrow to select yes. I use requireJS and all my posts will be referring it
    • Select Browser - default Chrome. Can select multiple in next line. To go to next option, needs to hit double Enter
    • Next needs to specify all source file locations. Double enter for next option
    • Exclude files. 
    • Bootstrap file for requireJS. Selecting yes will create a test-main.js in root location with RequireJS configured and run the tests. Selected no for the purpose of this post.
    • Watch file modification. Select yes. This streamlines any changes in source files and testing done immediately
    • Initialization is done. This will create a file 'karma.conf.js' in the root location where all the above settings can be seen and modified based on need.

    6. Run karma:
    • Command - 'node node_modules/karma/bin/karma start'
    • This will start karma on default port 9876 (if not changed) which will start Chrome browser for it's purpose.

    Notes:

    1. Error-01: Not so obvious error during global karma installation
    Solution: use command -
    - 'npm install --ignore-script -g karma'

    2. Error-02throw error('No provider for "' + name + '"!');
    Solution: next line of above should display which provider is missing. Install that provider using 'npm install --save-dev'


    Resources:
    1. http://karma-runner.github.io/0.13/intro/installation.html
    2.