What Is Refactoring?

Refactoring is the process of changing a software system in such a way that it does not alter the
external behavior of the code yet improves its internal structure. It is a disciplined way to clean up
code that minimizes the chances of introducing bugs. In essence when you refactor you are
improving the design of the code after it has been written.

“Improving the design after it has been written.” That’s an odd turn of phrase. In our current
understanding of software development we believe that we design and then we code. A good
design comes first, and the coding comes second. Over time the code will be modified, and the
integrity of the system, its structure according to that design, gradually fades. The code slowly
sinks from engineering to hacking.

Refactoring is the opposite of this practice. With refactoring you can take a bad design, chaos
even, and rework it into well-designed code. Each step is simple, even simplistic. You move a
field from one class to another, pull some code out of a method to make into its own method, and
push some code up or down a hierarchy. Yet the cumulative effect of these small changes can
radically improve the design. It is the exact reverse of the normal notion of software decay.

With refactoring you find the balance of work changes. You find that design, rather than occurring all up front, occurs continuously during development. You learn from building the system how to improve the design. The resulting interaction leads to a program with a design that stays good as development continues.

 – By Martin Fowler

Different type of methods in Javascript

Object Creation:

Unlike most other object-oriented languages, JavaScript doesn’t actually have a concept of classes. In most other object-oriented languages you would instantiate an instance of a particular class, but that is not the case in JavaScript. In JavaScript, objects can create new objects, and objects can inherit from other objects. This whole concept is called prototypal inheritance and will be discussed more later in the “Public Methods” section. Fundamentally, though, there still needs to be a way to create a new object, no matter what type of object scheme JavaScript uses. JavaScript makes it so that any function can also be instantiated as an object. In reality, it sounds a lot more confusing than it is. It’s a lot like having a piece of dough (which is a raw object) that is molded using a cookie cutter (which is an object constructor, using an object’s prototype).

// A simple function which takes a name and saves it to the current context
function User( name ) {
this.name = name;
}

// Create a new instance of that function, with the specified name
var me = new User( “My Name” );

// We can see that its name has been set as a property of itself
alert( me.name == “My Name” );

// And that it is an instance of the User object
alert( me.constructor == User );

// Now, since User() is just a function, what happens
// when we treat it as such?
User( “Test” );

// Since its ‘this’ context wasn’t set, it defaults to the global ‘window’
// object, meaning that window.name is equal to the name provided
alert( window.name == “Test” );

The above listing shows the use of the constructor property. This property exists on every object and will always point back to the function that created it. This way, you should be able to effectively duplicate the object, creating a new one of the same base class but not with the same properties.

An Example of Using the Constructor Property

// Create a new, simple, User object
function User() {}

// Create a new User object
var me = new User();

// Also creates a new User object (from the constructor reference of the first)
var you = new me.constructor();

// We can see that the constructors are, in fact, the same
alert( me.constructor == you.constructor );

Now that we know how to create simple objects, it’s time to add on what makes objects so useful: contextual methods and properties.

Public Methods:

Public methods are completely accessible by the end user within the context of the object. To achieve these public methods, which are available on every instance of a particular object, you need to learn about a property called prototype, which simply contains an object that will act as a base reference for all new copies of its parent object. Essentially, any property of the prototype
will be available on every instance of that object. This creation/reference process gives us a cheap version of inheritance.

Since an object prototype is just an object, you can attach new properties to them, just like any other object. Attaching new properties to a prototype will make them a part of every object instantiated from the original prototype, effectively making all the properties public
(and accessible by all). Example of an Object with Methods Attached Via the Prototype Object.

// Create a new User constructor
function User( name, age ){
this.name = name;
this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
return this.name;
};

// And add another function to the prototype
// Notice that the context is going to be within the instantiated object
User.prototype.getAge = function(){
return this.age;
};

// Instantiate a new User object
var user = new User( “Bob”, 44 );

// We can see that the two methods we attached are with the
// object, with proper contexts
alert( user.getName() == “Bob” );
alert( user.getAge() == 44 );

Simple constructors and simple manipulation of the prototype object is as far as most JavaScript developers get when building new applications. In the rest of this section I’m going to explain a couple other techniques that you can use to get the most out of your object oriented code.

Private Methods:

Private methods and variables are only accessible to other private methods, private variables, and privileged methods (discussed in the next section). This is a way to define code that will only be accessible within the object itself, and not outside of it. This technique is based on the work of Douglas Crockford, whose web site provides numerous documents detailing how object-oriented JavaScript works and how it should be used:

• List of JavaScript articles: http://javascript.crockford.com/
• “Private Members in JavaScript” article: http://javascript.crockford.com/private.html

Let’s now look at an example of how a private method could be used within an application,
as shown in below listing. 

Example of a Private Method Only Usable by the Constructor Function.

// An Object constructor that represents a classroom

function Classroom( students, teacher ) {
   // A private method used for display first student
   function disp() {
   alert(‘Classroom created’);
   }
   // Store the class data as public object properties
   this.students = students;
   this.teacher = teacher;
   // Call the private method to display the message at the time of object creation
   disp();
}

// Create a new classroom object
var class = new Classroom( [ "John", "Bob" ], “Mr. Smith” );

// Fails, as disp is not a public property of the object
class.disp();

While simple, private methods and variables are important for keeping your code free of collisions while allowing greater control over what your users are able to see and use. Next, we’re going to take a look at privileged methods, which are a combination of private and public methods that you can use in your objects.

Privileged Methods:

Privileged methods is a term coined by Douglas Crockford to refer to methods that are able to view and manipulate private variables (within an object) while still being accessible to users as a public method. Below listing shows an example of using privileged methods.

Example of Using Privileged Methods

// Create a new User object constructor
function User( name, age ) {
    // Attempt to figure out the year that the user was born
    var year = (new Date()).getFullYear() – age;
    // Create a new Privileged method that has access to
    // the year variable, but is still publically available
    this.getYearBorn = function(){
    return year;
    };
}
// Create a new instance of the user object
var user = new User( “Bob”, 44 );

// Verify that the year returned is correct
alert( user.getYearBorn() == 1962 );

// And notice that we’re not able to access the private year
// property of the object
alert( user.year == null );

In essence, privileged methods are dynamically generated methods, because they’re added to the object at runtime, rather than when the code is first compiled. While this technique is computationally more expensive than binding a simple method to the object prototype, it is also much more powerful and flexible. 

Static Methods :

The premise behind static methods is virtually identical to that of any other normal function. The primary difference, however, is that the functions exist as static properties of an object. As a property, they are not accessible within the context of an instance of that object; they are only available in the same context as the main object itself. For those familiar with traditional classlike inheritance, this is sort of like a static class method. In reality, the only advantage to writing code this way is to keep object namespaces clean. Below listing shows an example of a static method attached to an object.

A Simple Example of a Static Method

// A static method attached to the User object
User.cloneUser = function( user ) {
   // Create, and return, a new user
   return new User(
   // that is a clone of the other user object
   user.getName(),
   user.getAge()
   );
};
Static methods are the first methods that we’ve encountered whose purpose is purely organizationally related. A fundamental aspect of developing professional quality JavaScript is its ability to quickly, and quietly, interface with other pieces of code, while still being understandably accessible.

Content impressed from Pro JavaScript Techniques- John Resig

Anniversary of the blog

Anniversary of the blog

Praise goes to Almighty as 40 Posts in a Year. I thank Intentional and Accidental landing users and appreciate their support. Please write your suggestions, if any, at alavudeen@outlook.com

JQuery and CDN

jQuery is simply a bunch of JavaScript programming in an external JavaScript file. Like any external JavaScript file, you need to link it to your web page. However, because jQuery is so popular,you have a few choices when it comes to adding it to a web page: You can either use a version hosted at Google, Microsoft, or jQuery.com, or you can download the jQuery file to your own computer and add it to your website.

The first method uses a CDN or content distribution network—that is, another website hosts the jQuery file and sends it out to anyone who requests it. There are a couple of benefits to this approach: First, you can save your web server a few milliseconds by letting Google, Microsoft, or jQuery handle distributing the file to your site’s visitors.

In addition, CDNs have the added benefit of having servers located around the globe. So if someone in Singapore, for example, visits your site, he’ll receive the jQuery file from a server that’s probably a lot closer to him than your web server, which means he’ll get the file faster and your site will appear to run more quickly.

Lastly, and most importantly, because other designers use these CDNs as well, there’s a pretty good chance that someone visiting your site already has the jQuery file saved in their browser’s cache. Since he’s already downloaded the jQuery file from Google while visiting another site, he doesn’t need to download it again when visiting your site, resulting in a substantial speed increase.

There are a couple of downsides to using a CDN: First, visitors need to be connected to the Internet for this method to work. That becomes an issue if you need to make sure your site works offline, for example, in a kiosk at a museum or during a programming
demonstration in a classroom. In that case, you need to download the jQuery file from jQuery.com and add it to your website.

Adding your own jQuery file also ensures that your website will continue to work if the CDN servers go down. (Of course, if Google’s servers ever go down, then there may be bigger problems in the world than whether your website works.) Linking to the jQuery file on a CDN server Microsoft, jQuery, and Google all let you include the jQuery file on one of your web pages using their servers. For example, to link to version 1.6.3 of jQuery using Microsoft’s CDN, you would add this line of code in the <head> of your web page (just before the closing </head> tag), like this: 

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.3.min

.js”></script>

Using the jQuery CDN, you’d use this code:
<script src=”http://code.jquery.com/jquery-1.6.3.min

.js”></script>

And the code using Google’s CDN looks like this:

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min

.js”></script>

You only need to use one of these lines on your page, based on the CDN you prefer
to use. The Google CDN seems to be the most popular, so if you’re unsure of which
to use, use the Google servers.

 

Content impressed from JavaScript & jQuery - David Sawyer McFarland

Adapter pattern: Design Pattern Series – Part: 13

Adapter Pattern falls under Structural pattern:

According to the GoF, the intent of the Adapter pattern is,

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces

Problem: 
Sometimes a toolkit or class library can not be used because its interface is  incompatible with the interface required by an application and We can not change the library interface,  since we may not have its source code. For example the below example uses the grid which have the Method called Fill. But lets say  at some point of time you might like to use Infragistics grid(3rd party) which is not having the method called “Fill”, for example, and you may not populate the Client object with the Infragistics grid because of this incompatibility.

Solution:
The solution is to create an InfragisticsAdapter(Who Adapts the adaptee to client – pattern) which composes the Adaptee(Infragistics) and the InfragisticsAdapter will be compatible with the existing interface so that the client can be populated with Adapter.

Please find below the UML for this pattern:

adpater

The UML class diagram above describes an implementation of the adapter design pattern. The items in the diagram are described below:

 Client: The client class is that which requires the use of an incompatible type. It expects to interact with a type that implements the ITarget interface. However, the class that we wish it to use is the incompatible Adaptee.
 ITarget: This is the expected interface for the client class. Although shown in the diagram as an interface, it may be a class that the adapter inherits. If a class is used, the adapter must override its members.
 Adaptee: This class contains the functionality that is required by the client. However, its interface is not compatible with that which is expected.
 Adapter: This class provides the link between the incompatible Client and Adaptee classes. The adapter implements the ITarget interface and contains a private instance of the Adaptee class. When the client executes MethodA on the ITarget interface, MethodA in the adapter translates this request to a call to MethodB on the internal Adaptee instance.

Example:

public class Client
{
   
    public Client(IGrid  iGrid)
    {
        this.iGrid = iGrid;
 } 
 private IGrid iGrid;
 
    public void PopulateGrid(DataSet ds)
    {
        iGrid.Fill(ds);
    }
}
 
 
public interface IGrid
{
    void Fill(DataSet ds);
}
 
 
public class Infragistics
{
    public void DataFill(DataSet ds)
    {
        // fill the data into grid.
    }
}

public class InfragisticsAdapter : IGrid
{
    Infragistics _adaptee = new Infragistics();
 
    public void Fill(DataSet ds)
    {
        _adaptee.DataFill(ds);
    }
}

public void static Main()
{
 var client = new Client(new InfragisticsAdapter());
 var ds = GetDataset();
 client.PopulateGrid(ds); //– Hurray it will now work.
}

Rules of thumb
* Adapter makes things work after they’re designed; Bridge makes them work before they are.
* Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to   make unrelated classes work together.
* Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced   interface.
* Adapter is meant to change the interface of an existing object. Decorator enhances another object without changing its   interface. Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports   recursive composition, which isn’t possible with pure Adapters.
* Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing   interfaces work together as opposed to defining an entirely new one.

 

Proxy pattern: Design Pattern Series – Part: 12

Proxy Pattern falls under Structural pattern:

According to the GoF, the intent of the Proxy pattern is,

 Provide a surrogate or placeholder for another object to control access to it.

Problem:
 You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are  actually requested by the client.

Solution:

 A Proxy can also be defined as a surrogate. In the real work a cheque or debit card is a proxy for what is in our bank account.  It can be used in place of cash, which is what is needed, and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – controls and manage access to the object they are “protecting”.

Please find below the UML for this pattern:

proxy

The participants classes in the proxy pattern are:

Subject – Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.

Proxy – Maintains a reference that allows the Proxy to access the RealSubject.
Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject.
Controls access to the RealSubject and may be responsible for its creation and deletion.
Other responsibilities depend on the kind of proxy.

RealSubject – the real object that the proxy represents.

 

Example :

public interface Image {    // Subject Interface

 void showImage();
 
}

public class ImageProxy : Image { // Proxy Subject

 private String imageFilePath;
 
 private Image proxifiedImage;
 
 
 public ImageProxy(String imageFilePath) {
  this.imageFilePath= imageFilePath; 
 }
  
 public void showImage() {

  proxifiedImage = new HighResolutionImage(imageFilePath);
  
  // now call showImage on realSubject
  proxifiedImage.showImage();
  
 } }

public class HighResolutionImage : Image { // Real Subject

 public HighResolutionImage(String imageFilePath) {
  
  loadImage(imageFilePath);
 }

 private void loadImage(String imageFilePath) {

  // load Image from disk into memory
  // this is heavy and costly operation
 }

 
 public void showImage() {

  // Actual Image rendering logic

 } }

Rules of thumb:
* Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced  interface.
* Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection  to another object, and the implementations keep a reference to the object to which they forward requests.

 

Abstract Factory pattern: Design Pattern Series – Part: 11

Abstract Factory falls under Creational Pattern:

According to the GoF, the intent of the Abstract Factory pattern is,

 Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Problem:
You have seen a factory method already. But in the real world, factory class will not be one and it could be many to produce appropriate family of objects. Lets say, In a car company, a particular factory can be used to create different doors (front, back, side., ) , for example DoorFactory. The same goes to different lights, seats etc., So here what we have is group of factories. The problem here is sometimes we need to create a particular factory among group of factories.
 

Solution:

So we abstract out factories and at runtime we are going to create desired concrete factory.

Please find below the UML for this pattern:

abstract

The classes and/or objects participating in this pattern are:

•AbstractFactory  (AnimalFactory) declares an interface for operations that create abstract products

•ConcreteFactory   (SeaFactory, LandFactory) implements the operations to create concrete product objects

•AbstractProduct   (Animal) declares an interface for a type of product object

•Product  (Lion, Fish) defines a product object to be created by the corresponding concrete factory
 implements the AbstractProduct interface

•Client  (AnimalWorld) uses interfaces declared by AbstractFactory and AbstractProduct classes

Example :

public interface AnimalFactory { // Abstrct Factory
  Animal createAnimal(string condition);
}

 public class SeaFactory : AnimalFactory { // Concrete Factory
   public Animal createAnimal(string condition) {

     if(condition == “S”)
       return new Shark();
     return new Fish();
  } 
}

public class LandFactory : AnimalFactory { // Concrete Factory

  public Animal createAnimal(string condition) {
     if(condition == “E”)
       return new Elephant();
     return new Lion();
  }
}

public class AnimalWorld
{
 public AnimalFactory GetAnimalFactory(string condition)
 {
    if(condition == “Land”)
       return new LandFactory ();
     return SeaFactory();
 }
}

Follow

Get every new post delivered to your Inbox.