JavaScript: You think you know it well?

Just because you are a C# or Java developer that you think you know JavaScript well.  Well I don’t.  But no worries, below are some quick pointers to remember:

  • null and undefined are types, just like Numbers, Strings, Booleans, and Objects.  null indicates a deliberate non-value while undefined indicates an uninitialized value.
  • Primitive/literal values (null, undefined, “string”, 10, true, false) are converted to objects (wrapper objects) when properties are accessed.
  • Functions and Arrays are special types of objects.
  • Built in Error types are there as well.
  • Object(), Array(), String(), Number(), Boolean(), Function(), Date(), RegExp(), and Error() are native constructor functions.
  • parseInt() and parseFloat() parse the number in string until it reaches an invalid character.
  • Unary + operator converts values to numbers (+ “42” = 42 ) and returns NaN (Not a Number) if non-numeric.
  • isNaN() tests for NaN.
  • isFinite() tests for Infinity (1/0), -Infinity (-1/0), and NaN.
  • false, 0, empty string (“” ), NaN, null, and undefined convert to false, and all others convert to true.
  • Blocks do not have scope, only functions have scope.
  • “3” + 4 + 5 = 345, while 3 + 4 + “5” = 75.
  • Triple-equals operator avoids type coercion.  1 === true is false, but true === true is true.
  • JavaScript objects are simple collections of name-value pairs where the name is a JavaScript string and the value is any JavaScript value.
  • array.length isn’t necessarily the number of items in the array.  It is one more than the highest index.
  • No return statement or empty return with no value in a function returns undefined.
  • arguments variable contains all the values passed to the function.
  • IIFEs (Immediately Invoked Function Expressions) is basically what it says.  It’s a function in an expression and invoked immediately ( (function () { … })();  )
  • To call functions recursively, you can use a named IIFE ( (function myFunc() { myFunc(); })();  ).  The name is only available to the function’s own scope.
  • this inside a function refers to the current object if the function is called against an object or using dot notation or bracket notation; otherwise it will refer to the global object.
  • Global object or the head object in JavaScript in a web browser environment is the window object.  Variables you declare globally in your JavaScript code will become properties of the window object.
  • JavaScript does not have classes; it only has object prototypes. It uses functions as classes.  You declare the properties inside the function and declare the methods by assigning them to the function object’s prototype.
  • prototype is an object shared by all instances of the object.  It forms part of a lookup chain, which has a special name called prototype chain.  Anything assigned to the object’s prototype becomes available to all instances of the object.
  • Inner or nested functions can access variables in their parent function’s scope.
  • Closure happens when an outer function returns the inner function and the inner function needs access to the outer function’s local variables.  The outer function’s scope object is actually retained even after the outer function has returned.  Only when there are no more references to the inner function will the outer function’s scope object be garbage collected.
  • Scope objects form a chain called the scope chain.  Scope object is created every time the function starts executing.
Advertisements

Design Patterns: Factory Method, Abstract Factory, and Singleton

Back again with design patterns, defining them briefly and the design principles they are based on, and providing several very good (almost) real-world C# examples that are available on the Internet.  In this series we have the factory patterns and the singleton pattern and their several different implementations.

 

Design Pattern #4: Factory Method Pattern

  • Defines an interface for creating an object but lets subclasses decide which class to instantiate.  It lets a class defer instantiation to the subclasses.
  • Design Principle:
    • Design Principle #6 :  Depend on abstraction.  Do not depend on concrete classes.
  • C# Examples:
    • An online bookstore application using multiple distributors to send books to its customers.  This example uses the parameterized factory implementation or the procedural solution/basic noob implementation, wherein the bookstore factory receives the customer location to determine which distributor to choose from.
      Product IDistributor
      ConcreteProduct EastCoastDistributor, MidwestDistributor, WestCoastDistributor
      Creator IBookStore; with abstract method GetDistributor()
      ConcreteCreator BookStoreA
    • A lodging inquiry system wherein a customer can get details of different types of available rooms.  This example also shows the registration with reflection implementation, the self registration without reflection implementation and the self registration with reflection implementation.  It is actually using a factory pattern, a pattern that is the basis for the factory method pattern and the abstract factory pattern. The only difference between the factory pattern and the factory method pattern is in the creator. The factory method pattern requires an abstract class which defines the interface for several factories, thus abstracting the client from both the type of product and type of factory used to create the product.
      Product IRoomType
      ConcreteProduct ACRoom, DeluxeRoom, NonACRoom
      Creator
      ConcreteCreator RoomFactory; concrete class with concrete method GetRoomType()

 

Design Pattern #5: Abstract Factory Pattern

  • Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Design Principle:
    • Same as the factory method pattern, it follows the Design Principle #6.
  • C# Examples:
    • A drawing and printing machine that can process low and high resolution.  This can be extended to process medium resolution by creating a medium resolution factory that provides the medium resolution display and print drivers.
      AbstractFactory ResFactory; with abstract methods getDispDrvr() and getPrtDrvr()
      ConcreteFactory LowResFact, HighResFact
      AbstractProduct DisplayDriver, PrintDriver
      ConcreteProduct LowDisplayDriver, HighDisplayDriver, LowPrintDriver, HighPrintDriver
      Client ApControl
    • An audio/video device object providing access to it’s audio and video properties.  Again this can be extended to include Bluray by creating a Bluray object that exposes Bluray audio and video objects.
      AbstractFactory IAVDevice; with abstract methods GetAudio() and GetVideo()
      ConcreteFactory CCd, CDvd
      AbstractProduct IAudio, IVideo
      ConcreteProduct CCdAudio, CDvdAudio, CCdVideo, CDvdVideo
      Client CAVMaker
    • An example using employee and customer factories that provides personal information.  This example shows the dependency injection implementation and the inversion of control container implementation.  These types of implementations, factory pattern, dependency injection, and inversion of control container, are all techniques to implement inversion of control, a programming technique in which object coupling is bound at run time and is typically not known at compile time.  I will talk more about inversion of control on a separate post, as this I think, is a hot topic too in the object oriented programming world.
      AbstractFactory IPersonAbstractFactory
      ConcreteFactory EmployeeFactory, CustomerFactory
      AbstractProduct IPerson
      ConcreteProduct Employee, Customer
      Client MySample

 

Design Pattern #6: Singleton Pattern

  • Ensures a class only has one instance and provides a global point of access to it
  • C# Examples:
    • Singleton implementations from MSDN.  It shows 3 implementations: the basic implementation, the static initialization implementation, and the multithreaded or double-check locking implementation.

     

    • Singleton implementations from the book C# In Depth.  It shows 6 implementations:
      • basic implementation that is not thread-safe
      • simple thread-safe implementation using a lock
      • attempted thread-safe using double-check locking implementation
      • static initialization implementation that is thread-safe without using locks but not quite as lazy

       

      • full lazy static initialization implementation
      public sealed class Singleton
      {
      private Singleton()
      {
      }

      public static Singleton Instance { get { return Nested.instance; } }

      private class Nested
      {
      // Explicit static constructor to tell C# compiler
      // not to mark type as beforefieldinit
      static Nested()
      {
      }

      internal static readonly Singleton instance = new Singleton();
      }
      }

       

      • C# 4.0’s Lazy<T> static initialization implementation
      public sealed class Singleton
      {
      private static readonly Lazy<Singleton> lazy =
      new Lazy<Singleton>(() => new Singleton());

      public static Singleton Instance { get { return lazy.Value; } }

      private Singleton()
      {
      }
      }

* This is the second in the Design Patterns series.  The first one is Design Patterns: Strategy, Observer, and Decorator.

HTTP Fundamentals, Part 2: Communication Stack, HTTP Connections, and REST Style of Architecture

Communication Stack

HTTP is the topmost layer in the communication stack and is called an application layer protocol.  From the web browser, it travels down a series of layers, and when it arrives at the web server, it then travels up through a series of layers.  The layers that make up the communication stack are:

  • Application – An example would be HTTP.
  • Transport – Responsible for error detection, flow control, and overall reliability.  An example would be TCP (Transmission Control Protocol).
  • Network – Responsible for taking pieces of information and moving them through the various switches, routers, gateways, repeaters, and other devices that move information from one network to the next and all around the world.  An example would be IP (Internet Protocol).  This is where the IP address comes in to play.
  • Data Link – This is where data have to travel over a piece of wire, a fibre optic cable, a wireless network, or a satellite link.  It’s focused more on 1s, 0s, and electric signals.  An example would be Ethernet.

HTTP relies on TCP to connect to the server.  It opens a TCP socket by specifying the server address (host name) and port (defaults to 80).  With an open socket, HTTP can write into it and read from it when it gets response from the server.

A free tool you can use to view HTTP,  TCP and IP packets is Wireshark.

 

HTTP Connections

Gone is the old days of simple web pages.  Nowadays, a webpage requires more than a single resource to fully render.  To compensate for this and so as not to bog down the Internet, several approaches have been employed   when using HTTP:

  • Parallel Connections – Browsers can open more than one connection to download several resources at the same time but there is a limit to it that is set by the server.  This is better though than doing a request in a serial one-by-one fashion.
  • Persistent Connections – Browsers can persist a connection to the server reducing overhead associated with opening and closing a TCP socket and thus improving performance.  This is the default connection style with HTTP 1.1.  These connections are only persistent for a period of time as set by either the server or the browser.  The server can also opt not to accept a persistent connection by specifying the Connection: close header in every HTTP response message.
  • Pipelined Connections – Not widely used as parallel and persistent connections, this type of connection allow multiple requests to be sent by the browser before the browser waits for the first response.

 

REST Style of Architecture

HTTP lends itself to the REpresentational State Transfer (REST) style of architecture.  If you think of resources and URLs as just not files on a web server’s file system, but more like as resource abstractions, you start to see the web as part of your application and as a flexible architectural layer you can build on.  The following are some RESTful aspects of a URL:

  • A URL cannot restrict the client or server to a specific type of technology.
  • A URL cannot force the server to store a resource using any particular technology.
  • A URL cannot specify the representation of a specific resource, and a resource can have multiple representations.  This is where content negotiation, discussed in Part 1 of this series, kicks in.
  • A URL cannot say what a user wants to do with a resource.  This is where the HTTP methods comes in.

Because an HTTP message is a simple, plain text message and fully self-describing, and together with the indirection provided by URLs, HTTP applications can rely on a number of services that provide value as a message moves between the client application and the server application.  Examples of services would be:

  • Web server
    • Route message to proper application
    • Log message to a local file
    • Compress message if client supports it
  • Proxy server – A computer that sits between a client and server.  Can either be a forward proxy that sits closer to the client or a reverse proxy that sits closer to the server.  Note that a proxy server does not have to be a physical server.
    • Prevent message to go out to specific servers
    • Remove confidential data in the message
    • Log message to create audit trails
    • Compress message
    • Forward message to one of several web servers (load balancing)
    • Encrypt and decrypt message (SSL acceleration)
    • Filter out potentially dangerous message (cross-site scripting, SQL injection attack)
    • Store copies of frequently accessed resources and respond to messages requesting those resources directly (caching)

These services can be layered into the network without impacting the application, and that is the beauty of HTTP.  It is scalable, simple, reliable, and loosely coupled.  In fact, REST was initially described in the context of HTTP.

 

*This article is Part 2 of the HTTP Fundamental series.  For Part 1, click here.