We can think delegate type as a single method interface , and a delegate instance as an object implementing that interface.

As an example, consider your will, “pay the bills, make a donation to the charity,leave the rest of my estate to my cat” for instance you write it before your death and leave it in an appropiately safe place . After your death, your attorny will act on those instructions.”

A delegate in c# acts like your will in real world- it allows you to specify a sequence of actions to be executed at the appropriate time.

A Recipe for Simple Delegates

In order for a delegate to do anything , four things need to happen

  1. The delegate Type needs to be declared
  2. The code to be executed must be contained in a method
  3. The delegate instance must be created
  4. The delegate instane must be invoked


class Program
   delegate void StringProessor(string input);
   static void Main(string[] args)
     Person jon = new Person("jon");
     Person tom = new Person("Tom");
     StringProessor jonsVoice, tomsVoie, background;
     jonsVoice = new StringProessor(jon.Say);
     tomsVoie= new StringProessor(tom.Say);
     background = new StringProessor(Background.Note);
     tomsVoie.Invoke("Hello, Dady!");
     background("An Airplae files past");
 class Person
   string name;
   public Person(string name)
   { = name;
   public void Say(string message)
     Console.WriteLine("{0} says: {1}", name , message);
 class Background
   public static void Note(string note)

Later equals never

if you have been a programmer for more than 2 or 3 years, have you ever been impeded by bad code written by you or your team.? when i say impediment, what i think about impediment is if you were asked to do a change and it ideally should have taken less time, but practically it is never the case, doing small change requires making lot of other changes.

I think this will happen because of bad code. and ofcourse this bad code was written by us the programmers. but why do you think we write bad code? may be because of

we are trying to go fast or we were in a rush ignoring the principles , perhaps we were ignorant or tired of working on program for so long and may be frustrated because of this or promised to your manager to get it done by this time at any cost! or may be something cool coming up and you were pretty excited to get it started so didn’t concentrate on the current task in your hand.

and most of the time you know the program is in a mess and you have choosen to leave it for another day since you might have relieved by your QA confirmed that the code is working.We all have done it. I had done it saying to ourselfs we will come late and clean this up!

There is a law called LeBlane’s law which says ‘Later equals Never’. Now you know the law and its applicable to us

Selecting DOM Elements

    <h1 id="book-title">Ext JS 4 Cookbook</h1>
<ul id="authors">
<li>Stuart Ashworth</li>
<li>Andrew Duncan</li>
<h2>What's new in Ext JS 4?</h2>
<ul id="whats-new">
<li>Data Package</li>
<li>Enhanced Grid</li>
<li>Powerful Theming</li>


Ext.onReady(function () {
var bookTitleEl = Ext.get('book-title');
alert('Book Title ID: ' +;

Above is the snippet to select id(‘book-title)’ from html

let us inspect bookTitleEl  from debugger tools


As you can see it returned an object.

So what’s Happened?

When you give an id to Ext.get() method, ExtJS framework uses browsers underlying document.getElementById(), and after creating DOM node , it wraps it in Ext.Element instance and will return object of instance Ext.Elemet


Ext.get method only returns a single element, so when we want to deal with multiple matches we should consider using Ext.Select or Ext.Query methods


if you ever worked on css selectors, using Ext.Select would be very familiar for you. Consider if we want to select all the ‘li’ elements of id ‘author’ and would want to disable them, below snippet does that

    var authors ='#authors li');
and if you inspect authors in web console, you can see two li elements in it.


We can achieve the same functionality which we had done using Ext.Select() through Ext.query. see below snippet.

    var authors = Ext.query('#authors li');
. image
The Main Difference between and Ext.query is, Ext.query will NOT wrap underlying DOM elements with Ext.Element . it will return DOM object which is not the case with

When to use Ext.query/

When you are working on huge DOM objects, and performance is your concern, its advisable to go for Ext.query, also you need to consider if you are going for Ext.query you are loosing additional capabilities and functionalities provided by ExtJS framework , contrary to the case with where framework would wrap the DOM objects to Ext.Element and will provide us with additional capabilities like searching and traversing etc.

Refactoring Ricks Guitar Application -1

In previous post we saw problems with existing Ricks guitar application. it has both design problems and bugs. Now where do we need to start.?

The Three Steps

author explains following three simple steps for us to follow so that we could write Great Software

Applying three principles to Ricks Application

1. Make sure Application does what customer wants to

first we will explain the problem and try to discuss the possible solutions/approaches and finally we will pick best possible solution and will implement in Ricks application


we have a bug in the application. In current application all the properties of guitars are strings. Inventory and Search methods in application expects Strings to be passed and have to be case sensitive to work as expected.

Possible Solutions

  • The first and easiest solution we can apply here is calling toLowerCase() or toUpperCase()
  • Another solution we can have is by having enums.
  • Now we need to decide on among the two? which we should apply them in order to resolve the problem we have.

    you can probably argue we should implement first solution i.e making them to lower or to upper as it is easiest one and it will resolve our problem

    Having possibility of accepting wrong data in to our application is the main reason we have an issue now and by making toupper or tolower we are not eliminating this problem, we are creating a workaround which would again result in to a bug in near future.
    Don’t create problems to solve problems.

    So implementing enums is the correct solution for this problem.

    Ditching String comparisons

    Now we will create the following enum classes and will remove all the string comparisons..

     public enum Builder
     public enum Type 
     public enum Wood

    I am not pasting entire source code here.. (but will do post class diagram). at the end of the post please look at git link for source code(in c#)

    Now this is how Guitar.cs look like, since now Guitar.cs accepts enums , we do not have any possibility of entering wrong data.

        public Guitar(String serialNumber, double price,
                   Builder builder, String model, Type type,
                   Wood backWood, Wood topWood)
                this.serialNumber = serialNumber;
                this.price = price;
                this.builder = builder;
                this.model = model;
                this.type = type;
                this.backWood = backWood;
                this.topWood = topWood;

    here is the classdiagram after we implemented enums..

    Now by applying 1st principle we made our Refactored code less fragile.. why ..???
    we’ve added both type safety and value safety with these enums. Now compiler also doest allow us to pass wrong information/data in to search/add methods of Guitar/inventory classes.

    Now we are good to go with second principle which is Apply basic OO principles to add flexibility.. will discuss in next post

    Rick’s Guitar Application Before Refactoring

    I have started reading HeadFirst OOAD book, and in Chapter 1 – “Well Designed Apps Rock” authors describe how a great software should look like by taking an example of bad written application and explaining why we call it “BAD” written software and best ways to make it good

    when do you say good- as per my understanding a good written program should adhere to solid principles.

    i will post the bad code from this book and will discuss problems with the code. lets get started..

    Rick’s Guitar Store- Dirty and Ugly

    Rick is a customer and he would be selling guitars. and he wanted to get rid of papers and pins so he asked for a software with following Requirements

    1. He need to add a new guitar to System
    2. He needs to Search guitars from system

    with the above requirements here is the class diagram and source code

    class diagram

    we have the following classes

    1. Guitar.cs – here just we have guitar property’s and their getters and setters

    public class Guitar
            private String serialNumber, builder, model, type, backWood, topWood;
            private double price;
            public Guitar(String serialNumber, double price,
                   String builder, String model, String type,
                   String backWood, String topWood)
                this.serialNumber = serialNumber;
                this.price = price;
                this.builder = builder;
                this.model = model;
                this.type = type;
                this.backWood = backWood;
                this.topWood = topWood;
            public String getSerialNumber()
                return serialNumber;
            public double getPrice()
                return price;
            public void setPrice(float newPrice)
                this.price = newPrice;
            public String getBuilder()
                return builder;
            public String getModel()
                return model;
            public String getType()
                return type;
            public String getBackWood()
                return backWood;
            public String getTopWood()
                return topWood;

    Guitar.cs looks fine. i don’t have any thing to comment on it as of now.
    2. Inventory.cs –
    we have three methods in inventory class

  • addGuitar- will add guitar to inventory
  • getGuitar- will get guitar by serial number
  • search- will take guitar class as input and will search for matching guitar in inventory
  •  public class Inventory
            private IList<Guitar> guitars;
            public Inventory()
                guitars = new List<Guitar>();
            public void addGuitar(String serialNumber, double price,
                          String builder, String model,
                          String type, String backWood, String topWood)
                Guitar guitar = new Guitar(serialNumber, price, builder,
                                           model, type, backWood, topWood);
            public Guitar getGuitar(String serialNumber)
                foreach (var guitar in guitars)
                    if (guitar.getSerialNumber().Equals(serialNumber))
                        return guitar;
                return null;
            public Guitar search(Guitar searchGuitar)
                foreach (var guitar in guitars)
                    String builder = searchGuitar.getBuilder();
                    if ((builder != null) && (!builder.Equals("")) &&
                    String model = searchGuitar.getModel();
                    if ((model != null) && (!model.Equals("")) &&
                    String type = searchGuitar.getType();
                    if ((type != null) && (!searchGuitar.Equals("")) &&
                    String backWood = searchGuitar.getBackWood();
                    if ((backWood != null) && (!backWood.Equals("")) &&
                    String topWood = searchGuitar.getTopWood();
                    if ((topWood != null) && (!topWood.Equals("")) &&
                    return guitar;
                return null;

    I don’t like Inventory.cs class particularly method search. Ideally we should avoid string comparisons. String comparisons will cost us a lot( may be bugs..??)

    It’s good that we have a test class

        public  class FindGuitarTest
            Inventory inventory = new Inventory();
            public FindGuitarTest()
            public void SearchGuitar()
                Guitar whatErinLikes = new Guitar("", 0, "fender", "Stratocastor",
                                       "electric", "Alder", "Alder");
                Guitar guitar =;
                if (guitar != null)
                   Debug.WriteLine("Erin, you might like this " +
                      guitar.getBuilder() + " " + guitar.getModel() + " " +
                      guitar.getType() + " guitar:\n   " +
                      guitar.getBackWood() + " back and sides,\n   " +
                      guitar.getTopWood() + " top.\nYou can have it for only $" +
                      guitar.getPrice() + "!");
                    Debug.WriteLine("Sorry, Erin, we have nothing for you.");
            private static void initializeInventory(Inventory inventory)
                inventory.addGuitar("11277", 3999.95, "Collings", "CJ", "acoustic",
                                    "Indian Rosewood", "Sitka");
                inventory.addGuitar("V95693", 1499.95, "Fender", "Stratocastor", "electric",
                                    "Alder", "Alder");
                inventory.addGuitar("V9512", 1549.95, "Fender", "Stratocastor", "electric",
                                    "Alder", "Alder");
                inventory.addGuitar("122784", 5495.95, "Martin", "D-18", "acoustic",
                                    "Mahogany", "Adirondack");
                inventory.addGuitar("76531", 6295.95, "Martin", "OM-28", "acoustic",
                                    "Brazilian Rosewood", "Adriondack");
                inventory.addGuitar("70108276", 2295.95, "Gibson", "Les Paul", "electric",
                                    "Mahogany", "Maple");
                inventory.addGuitar("82765501", 1890.95, "Gibson", "SG '61 Reissue",
                                    "electric", "Mahogany", "Mahogany");
                inventory.addGuitar("77023", 6275.95, "Martin", "D-28", "acoustic",
                                    "Brazilian Rosewood", "Adirondack");
                inventory.addGuitar("1092", 12995.95, "Olson", "SJ", "acoustic",
                                    "Indian Rosewood", "Cedar");
                inventory.addGuitar("566-62", 8999.95, "Ryan", "Cathedral", "acoustic",
                                    "Cocobolo", "Cedar");
                inventory.addGuitar("6 29584", 2100.95, "PRS", "Dave Navarro Signature",
                                    "electric", "Mahogany", "Maple");

    at 1000 foot view, this code should work. ideally it should work.But we have a problem with this code let see

    A Bug

    this is what we are adding in inventory
    1499.95, “Fender”, “Stratocastor”,
    “electric”, “Alder”, “Alder”);
    if this is what we are searching for
    Guitar whatErinLikes = new Guitar(“”, 0, “fender”, “Stratocastor”,
    “electric”, “Alder”, “Alder”);
    Guitar guitar =;

    this code will definitely break

    Now we know there are problems with this code.. and here are some of the problems according to author’s view
    Things that could change

  • String comparisons , those look terrible
  • Design is terrible, Inventory class and Guitar classes depend on each other too much
  • what if search method needs to return multiple guitars
  • these are some of the problems with existing design author put forth which i would agree to..

    But how do we know where to start? How do we write Great software. what do we need change in Rick’s Application?

    In the next post i will discuss these

    oAuth 2.0 Protocol Flow

    OAuth 2.0 Protocol Flow

    let us discuss about oAuth 2.0 Protocol flow in this post..

    protocol flow

    see the above diagram for oAuth 2.0 protocol flow.. i.e how oAuth should be implemented… this has been taken from oauth ietf

    below depicts the flow

    1.Client requests authorization from resource owner . the authorization request can be made directly to resource owner(as shown) or preferably via authorization server as an intermediately

    2.the client receives an Authorization grant which a credential representing the resource owners Authorization, expressed using one of four grant types(will be discussed in next blog) or an extension grant type

    3.Then client requests the access token by authenticating with authorization server and presenting authorization grant

    4.The Authorization server , authenticates the client and validates the authorization grant, and if valid issues an access token

    5.Client requests the protected resource from the resource server and authenticates by providing access token

    6.resource server validates the access token,and if valid serves the protected resource

    Note:Preferred method for the client to obtain an Authorization grant from the resource owner(see A and B in the diagram) is to use Authorization Server as an intermediary

    This is the Typical flow for an ideal oAuth 2.0 protocol.. in the next blog we will see grant types..

    OAuth 2.0… basics you need to know…

    OAuth 2.0

    Before jumping straight in to oAuth.. let me ask you some questions..(may be rewind yourselfs 2-3 years back..because in the last 2-3 years.. each and every popular site you are interacting with would already have implemented oAuth)

    How many have you given passwords of either facebook/gmail/yahoo to other sites like slideshare/zomato etc..
    if your answer is yes.. then its a bad thing.. its wrong to share passwords.. you are giving access to slideshare or any other third party application access to your full gmail account.

    Necessity and Birth of oAuth

    with new applications(mobile/web) growing day by day.. and its mandatory that at some point of time .. we have to register to theapplication.. and to make user’s life easy(by not having remembering new passowrd :D) app providers have provided a way to login via google/facebook/twitter to their applications.this has led to user sharing their username/password of gmail/twitter/facebook to the third party provider..

    This is a huge security breach.. consider you have provided your gmail id and password.. third party has access to your entire gmail.. i.e it can post/delete mail with your consent..

    So there is a need to register with facebook/gmail/twitter with out having to share username/password..

    i believe that need has became developing oAuth

    OAuth Definition

    Here’s the definition of OAuth 2.0 from the OAuth 2.0 IETF specification itself:
    “The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.”

    Terms to Know

    1. Resource Server – The Server that holds the resource
    2. Resource Owner – The user who owns the specific resources
    3. Authorization Server – A server that authenticates the resource owner and issues access tokens to the client
    4. client – the application that requests access on resource on behalf of resource owner