Selecting DOM Elements

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

Ext.get()

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

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

let us inspect bookTitleEl  from debugger tools

image 

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

Note

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

Ext.Select()

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 = Ext.select('#authors li');
authors.hide();
and if you inspect authors in web console, you can see two li elements in it.
image

Ext.query()

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');
authors.hide();
. image
The Main Difference between Ext.select 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 Ext.select

When to use Ext.query/Ext.select:

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 Ext.select 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

Problem

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
        {
           FENDER, MARTIN, GIBSON, COLLINGS, OLSON, RYAN, PRS, ANY
        }
     public enum Type 
        {
            ACOUSTIC, ELECTRIC
        }
     public enum Wood
        {
            INDIAN_ROSEWOOD, BRAZILIAN_ROSEWOOD, MAHOGANY, MAPLE,
            COCOBOLO, CEDAR, ADIRONDACK, ALDER, SITKA
        }
    }
    

    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);
                guitars.Add(guitar);
            }
    
            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("")) &&
                        (!builder.Equals(guitar.getBuilder())))
                        continue;
                    String model = searchGuitar.getModel();
                    if ((model != null) && (!model.Equals("")) &&
                        (!model.Equals(guitar.getModel())))
                        continue;
                    String type = searchGuitar.getType();
                    if ((type != null) && (!searchGuitar.Equals("")) &&
                        (!type.Equals(guitar.getType())))
                        continue;
                    String backWood = searchGuitar.getBackWood();
                    if ((backWood != null) && (!backWood.Equals("")) &&
                        (!backWood.Equals(guitar.getBackWood())))
                        continue;
                    String topWood = searchGuitar.getTopWood();
                    if ((topWood != null) && (!topWood.Equals("")) &&
                        (!topWood.Equals(guitar.getTopWood())))
                        continue;
                    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..??)

    3.FindGuitarTest.cs
    It’s good that we have a test class

    
     [TestClass]
        public  class FindGuitarTest
        {
            Inventory inventory = new Inventory();
            public FindGuitarTest()
            {
                initializeInventory(inventory);
            }
    
            [TestMethod]
            public void SearchGuitar()
            {
                Guitar whatErinLikes = new Guitar("", 0, "fender", "Stratocastor",
                                       "electric", "Alder", "Alder");
    
                Guitar guitar = inventory.search(whatErinLikes);
                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() + "!");
                }
                else
                {
                    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
    
    inventory.addGuitar(“V95693”,
    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 = inventory.search(whatErinLikes);
    
    

    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

    IceBergClass -AntiPattern

    found some article here

    http://deviq.com/iceberg-class/

    its a good read… !!

    In Short.. its not good to have more PRIVATE methods in your class.
    if you have more methods that depends on some behaviour.. its better to have abstracted them. i.e have an interface and declare all your behaviours in the interface and have the class implement this interface.. so that you will abstract the behaviour in to a concrete class and if ever this behaviour were to be changed, you will do changes in the concrete class.. by that way you will be adhering to single responsibility principle and open closed principle

    Design Smells

    In This post We will discuss on Design Smells

    When you will know your design Rots…when you are experiencing any of the following in your project/ code you are working on.. you should be certain that there is something wrong happening and you really need to look in to it

    1. Rigidity
    2. Fragility
    3. Immobility
    4. Viscosity
    5. Needless Complexity
    6. Needless Repetition
    7. Opacity

    1. Rigidity

    Rigidity is the tendency of the software difficult to change..A design is rigid , if a single change causes a cascade of subsequent changes..

    Its like you are developing a system , and you are half way there.. and while adding new features or when you were asked to do a small change in existing system and if you are experiencing it is difficult to do that change because, its impacting most of the things in system and you need to change most of the existing system.you should consider your system is not rigidit

    2. Fragility

    Fragility is the tendency of a program to break in many places when a single change is made..

    I would say fragility and rigidity would complement each other… when you are adding a new feature to the system, ideally there should be no impact to existing system.. as we would all agree it is almost impossible :).. BUT there should be minimal or no impact to existing system..then you should consider your system is not Fragile

    3. Immobility

    A design is immobile, when it contains parts that could be useful in other systems, but the effort and the risk involved with separating those parts from system are tooo great. this is unfortunate but very common occurrence

    4.Viscosity
    a viscous project is one in which the design of the software is difficult to preserve

    when you find any problem in your system,generally we find more than one way to do that change.. one is adhering to design and the other which is not( A Hack ;)). When design preserving methods are harder to implement than hacks.. then your design is viscus

    5.Needless Complexity

    This may happen when developers are way ahead than Requirements..At first this may seem like a good thing to do..

    i.e consider you may anticipate future requirements and you will put in elements in system which will be needed later in future, which you might consider a good thing to do. But you should consider that preparing for future changes should keep our code flexible and prevent nightmarish changes later.

    unfortunately, the effect is just opposite.by preparing for future contigencies, design becomes littered…some of these preparations may pay off… but many are NOT

    6. Needless Repetition

    Cut and paste may be useful text-editing operations, but they can be disastrous to your system..

    consider this.. suppose you need to convert a calendar date to business date and you thought that this must be somewhere in the system already and you do ctrl+shift+f and copy the code and paste it in your module… it happens that the code which you copied was written by a X developer which he had copied and pasted in his module from seeing in another module which has been developed by Y developer.. and also happens that Y developer copied and pasted that code in his module from another module which is developed by Z developer.. and Z developer had written that module… so there is a lot and lot of same code.. and if need to change that code… consider the nightmare…!!!!

    7. Opacity

    Opacity is the tendency of a module to difficult to understand..to avoid this code should be written in clean, clear and Expressive manner..

    its a complete developers responsibility to write clean, clear and expressive code…
    when you first write a code, it may seem every thing is clear to you at first.. because you might of immersed in it at an intimate level and you know every detail of whats happening over there…some months later, when you revisit the code and wonder if you had written this code…

    To make your system free from opacity… its one’s responsibility to put ourselves in readers shoes and make a concrete effort to make code clean , clear and expressive

    Now we have some understanding what are code smells and when can we identify them, let us also understand , why there are code smells.. and why they are accumulated in system..??

    Why software Rots..??? Why there are code smells
    You will see most of the software rots and code smells in non-agile environments..why mostly in non-agile environments..?

    Because Requirements change in a ways that the initial design did not anticipate. and often these changed need to be made quickly and may be made by developers who are not familiar with the original design philosophy..though change to design works, it somehow violates the original design. Bit by Bit, as a changes continue, these violations accumulate making code worse and rotten…

    However, we should not blame the changes in requirements for your rotten code.. if you are a software developer and if you have been in this industry, you should already know that requirements are most volatile elements in software projects and they are tend to change.. if our designs are failing owing to constant changes in requirements…its our design and practices that are at fault..and we must somehow need to find a way to make our designs resilient to those changes and practices that protect them from rotting..

    what you need to do to keep your system clean
    you should be agile… as an agile team thrives on change. team invests little upfront so it is not vesting on aging initial design .you should keep your system as clean as possible and back up your system with lots and lots of unit tests, this keeps design flexible and easy to change.. when you are changing some thing you know you have your tests and rely on them…
    in each iteration(sprint) should end with a system whose design is as appropriate(clean) it can be for the requirements in that iteration.

    Adapter Pattern

    Adapter Pattern-Definition

    “Adapter pattern is a software design pattern that allows the interface of an existing class to be used from another interface. It is often used to make existing classes work with others without modifying their source code.”

    Graphical Representation

    In the above diagram you see a client class on the left which requires a particular interface shown by a half circle
    and in the right side you see a component class having the functionality that client needs and expects an interface of Inverted triangle..
    we cannot connect these two classe.. so adapter comes in between

    Real World Example

    I guess no information is required for the above…

    UML Diagram

    Example of Adapter pattern in Microsoft Framework

    let us implement adapter pattern which is present in Microsoft .NET Framework

    we have an existing class named DataRenderer, below is the source code

    
    public class DataRenderer
        {
            private readonly IDbDataAdapter _dataAdapter;
    
            public DataRenderer(IDbDataAdapter dataAdapter)
            {
                _dataAdapter = dataAdapter;
            }
    
            public void Render(TextWriter writer)
            {
                writer.WriteLine("Rendering Data:");
                var myDataSet = new DataSet();
    
                _dataAdapter.Fill(myDataSet);
    
                foreach (DataTable table in myDataSet.Tables)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        writer.Write(column.ColumnName.PadRight(20) + " ");
                    }
                    writer.WriteLine();
                    foreach (DataRow row in table.Rows)
                    {
                        for (int i = 0; i &lt; table.Columns.Count; i++)
                        {
                            writer.Write(row[i].ToString().PadRight(20) + " ");
                        }
                        writer.WriteLine();
                    }
                }
            }
    
        }
    
    

    StubDbAdapter.cs

     public class StubDbAdapter : IDbDataAdapter
        {
            public int Fill(DataSet dataSet)
            {
                var myDataTable = new DataTable();
                myDataTable.Columns.Add(new DataColumn("Id", typeof(int)));
                myDataTable.Columns.Add(new DataColumn("Name", typeof(string)));
                myDataTable.Columns.Add(new DataColumn("Description", typeof(string)));
    
                var myRow = myDataTable.NewRow();
                myRow[0] = 1;
                myRow[1] = "Adapter";
                myRow[2] = "Adapter Description";
                myDataTable.Rows.Add(myRow);
                dataSet.Tables.Add(myDataTable);
                dataSet.AcceptChanges();
    
                return 1;
            }
    }
    

    Test case

     [TestClass]
        public class DataRendererShould
        {
            [TestMethod]
            public void RenderOneRowGivenStubDataAdapter()
            {
                var myRenderer = new DataRenderer(new StubDbAdapter());
    
                var writer = new StringWriter();
                myRenderer.Render(writer);
    
                string result = writer.ToString();
                Console.Write(result);
    
                int lineCount = result.Count(c =&gt; c == '\n');
                Assert.AreEqual(3, lineCount);
            }
    
            [TestMethod]
            public void RenderTwoRowsGivenOleDbDataAdapter()
            {
                var adapter = new OleDbDataAdapter();
                adapter.SelectCommand = new OleDbCommand("SELECT * FROM Pattern");
                adapter.SelectCommand.Connection =
                    new OleDbConnection(
                        @"Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\Users\Steve\Documents\My Dropbox\PluralsightCurrent\009 - Adapter Pattern\AdapterDemo\AdapterDemo\Sample.sdf");
                var myRenderer = new DataRenderer(adapter);
    
                var writer = new StringWriter();
                myRenderer.Render(writer);
    
                string result = writer.ToString();
                Console.Write(result);
    
                int lineCount = result.Count(c =&gt; c == '\n');
                Assert.AreEqual(4, lineCount);
            }
        }
    

    As you can see from the above test case, Data Renderer class accepts IDataAdapter..
    in the first test we have StubDbAdapter which will stubb data . and in second class we used OleDbDataAdapter, in future we may use sql adapter or oracle adapter etc..

    Another Example

    Now let us create our own adapter…

    let us assume that we have a repository which will gives us a list( for example consider the the repository will gives us the data from the table “Pattern” which we have created earlier)

    for now i have stubbed the data,but practically it should come from a table

    
     public class PatternRepository : IPatternsRepository
        {
            public IEnumerable&lt;Pattern&gt; GetPatterns()
            {
                var patterns = new List&lt;Pattern&gt;
                                 {
                                     new Pattern {Id = 1, Name = "Pattern One", Description = "Pattern One Description"},
                                     new Pattern {Id = 2, Name = "Pattern Two", Description = "Pattern Two Description"}
                                 };
                return patterns;
            }
        }
    

    Now let us create Pattern Renderer class.

    
    public class PatternRenderer : IRenderer
        {
            public IList&lt;Pattern&gt; ListPatterns(IPatternsRepository patternRepository)
            {
                return patternRepository.GetPatterns().ToList();
            }
    
            public void Render(TextWriter writer)
            {
    
            }
        }
    

    The code which present in DataRenderer.cs can be reused in PatternRenderer, let us see if we can achieve that with out Adapter pattern

    Before Implementing Adapter Pattern

    
    public class PatternRenderer : IRenderer
        {
            private IList&lt;Pattern&gt; ListPatterns(IPatternsRepository patternRepository)
            {
                return patternRepository.GetPatterns().ToList();
            }
        
            public void Render(TextWriter writer)
            {
                var myDataSet = new DataSet();
    
                var myDataTable = new DataTable();
                myDataTable.Columns.Add(new DataColumn("Id", typeof(int)));
                myDataTable.Columns.Add(new DataColumn("Name", typeof(string)));
                myDataTable.Columns.Add(new DataColumn("Description", typeof(string)));
    
                var _patterns = ListPatterns(new PatternRepository());
    
                foreach (var pattern in _patterns)
                {
                    var myRow = myDataTable.NewRow();
                    myRow[0] = pattern.Id;
                    myRow[1] = pattern.Name;
                    myRow[2] = pattern.Description;
                    myDataTable.Rows.Add(myRow);
                }
                myDataSet.Tables.Add(myDataTable);
                myDataSet.AcceptChanges();
    
    
                foreach (DataTable table in myDataSet.Tables)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        writer.Write(column.ColumnName.PadRight(20) + " ");
                    }
                    writer.WriteLine();
                    foreach (DataRow row in table.Rows)
                    {
                        for (int i = 0; i &lt; table.Columns.Count; i++)
                        {
                            writer.Write(row[i].ToString().PadRight(20) + " ");
                        }
                        writer.WriteLine();
                    }
                }
            }
        }
    
    

    what we have done???

    we will be getting a list from repository, if we have to use the existing code from DataRenderer.cs we need to convert the list in to datatable and then need to loop through the table to write.. thats all we have done.. !!!

    Test case for the above code

         [TestMethod]
            public void RenderTwoPatterns()
            {
                var myRenderer = new PatternRenderer();
                var writer = new StringWriter();
                myRenderer.Render(writer);
                string result = writer.ToString();
                Console.Write(result);
    
                int lineCount = result.Count(c =&gt; c == '\n');
                Assert.AreEqual(4, lineCount);
            }
    
    

    As you can see all the highlighted code is duplicated between classes PatternRenderer.cs and DataRenderer.cs

    Now we will implement Adapter Pattern and see if we are able to avoid duplicate code

    After Implementing Adapter Pattern

    PatternRenderer.cs

    
     public class PatternRenderer : IRenderer
        {
            private readonly IDbDataAdapter _dataAdapter;
            private IList&lt;Pattern&gt; ListPatterns(IPatternsRepository patternRepository)
            {
                return patternRepository.GetPatterns().ToList();
            }
    
            public PatternRenderer(IDbDataAdapter dataAdapter)
            {
                _dataAdapter = dataAdapter;
            }
            public void Render(TextWriter writer)
            {
               var  _dataRenderer = new DataRenderer(_dataAdapter);
                _dataRenderer.Render(writer);
            }
        }
    
    

    from the highlight code, you can see that we are reusing existing DataRenderer class. we have avoided duplicate code !!! 🙂

    PatternCollectionDbAdapter.cs

    
     public class PatternCollectionDbAdapter : IDbDataAdapter
        {
            private readonly IEnumerable&lt;Pattern&gt; _patterns;
    
            public PatternCollectionDbAdapter(IEnumerable&lt;Pattern&gt; patterns)
            {
                _patterns = patterns;
            }
            public PatternCollectionDbAdapter():this(new PatternRepository().GetPatterns())
            {
    
            }
            public int Fill(DataSet dataSet)
            {
                var myDataTable = new DataTable();
                myDataTable.Columns.Add(new DataColumn("Id", typeof(int)));
                myDataTable.Columns.Add(new DataColumn("Name", typeof(string)));
                myDataTable.Columns.Add(new DataColumn("Description", typeof(string)));
    
                foreach (var pattern in _patterns)
                {
                    var myRow = myDataTable.NewRow();
                    myRow[0] = pattern.Id;
                    myRow[1] = pattern.Name;
                    myRow[2] = pattern.Description;
                    myDataTable.Rows.Add(myRow);
                }
                dataSet.Tables.Add(myDataTable);
                dataSet.AcceptChanges();
    
                return myDataTable.Rows.Count;
            }
    }
    

    This is our new class PatternCollectionDbAdapter, it all does is to convert list that we have got from repo in to data table.

    Test Method..(this is same as above test ..not changed a bit!!)

    
     [TestMethod]
            public void RenderTwoPatterns()
            {
                var patternCollectionAdapter = new PatternCollectionDbAdapter();
                var myRenderer = new PatternRenderer(patternCollectionAdapter);
                var writer = new StringWriter();
                myRenderer.Render(writer);
                string result = writer.ToString();
                Console.Write(result);
    
                int lineCount = result.Count(c =&gt; c == '\n');
                Assert.AreEqual(4, lineCount);
            }
    
    

    with this i have covered adapter pattern… 🙂

    you can find the source code for this pattern here..

    SimUDuck App – Strategy Pattern

    In this blog i will discuss about strategy pattern…

    before diving through Strategy Pattern.. let us consider the use case below..

    There is an existing application “SimUDuck” Duck simulation app.. you can imagine the app displaying the Duck… and upon clicking the duck which would perform some things like giving sound.. will swim etc…. and here is the class diagram for this app..

    Duck Class

     public class Duck
        {
           
            public string Display()
            {
              return  "I am Duck";
            }
    
            public string Quack()
            {
              return  "Quack";
            }
    
            public string Swim()
            {
                return "I am Swimming";
            }
                   
        }
    

    MallardDuck

        class MallardDuck : Duck
        {
            public new  string Display ()
            {
                return "I am Mallard Duck";
            }
        }
    

    RedHeadDuck

    class RedHeadDuck : Duck
        {
    
            public new string Display()
            {
                return "I am RedHead Duck";
            }
        }
    

    New Requirement

    Now PMG thinks that Ducks Need to fly.. So PMG asks to have the duck ability to fly…

    As you can see.. Just adding a Fly method in Main Class .. gave ability to fly to the child classes…awesome right!!!

    But something went horribly wrong…

    Now there is one more class “Rubber Duck Class” inheriting the main Duck Class..so now Rubber Duck has also have ability to fly.. which is wrong..

    We failed to notice not all subclasses of Duck should have ability to fly..

    so in order to resolve this issue what could we have done is to override fly method in Rubber Duck class to do nothing…

    Cleaning up the code…

    We came to realize the inheritance is not the best solution here..when ever new class is added.. need to override the methods in the class.. which is maintenance headache..

    Another possible Solution

    RedHeadDuck.cs

     class RedHeadDuck : Duck, IFlyable
        {
    
            public new string Display()
            {
                return "I am RedHead Duck";
            }
    
            public string Fly()
            {
                return "I am Flying";
            }
        }
    

    MallardDuck.cs

     class MallardDuck : Duck,IFlyable
        {
            public new  string Display ()
            {
                return "I am Mallard Duck";
            }
    
            public string Fly()
            {
               return "I am Flying";
            }
        }
    

    IFlyable.cs

    namespace Duck
    {
        public interface IFlyable
        {
            string Fly();
        }
    }
    

    RubberDuck.cs

      class RubberDuck : Duck
        {
            public new string Display()
            {
                return "I am Rubber Duck";
            }
        }
    

    So now you can see.. Rubber Duck is not implementing IFlyable interface.. so we could able to resolve our problem..but this is not the solution we wanted because…of maintenance headache..

    Problem with the above approach

    Let us suppose… we want to change the flying behaviour of the duck..then we need to change in the following two classes which have implemented IFlyable interface… i.e we need to modify code in MallardDuck.cs and RedHeadDuck.cs.. imagine IFlyable were to implemented in 20 classes.. it would become a nightmare for a developer..

    Zeroing in on the problem…
    So now we know.. duck behavior(flying) is not same across all the subclasses..the above implementation sounded promising for a while because.. the duck subclasses which wanted to adapt flying behavior will implement IFlying interface… but the main problem here is.. interfaces does not have any implementation( no code reuse .. and if we were to change the implementation.. we need to track down all the classes where the interface is implemented and need to change the code , which is gruesome task…

    So at the time like this we have a design principle to follow

    Identify the aspects of application that vary and separate them from what stays the same…

    i.e if you’ve got to know, some aspect of your code that is changing with every new requirement you need to pull that out and separate it for what is not changing

    in programming way you can think it like

    “take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don’t.

    Designing the Duck Behaviors

    We’d like to keep things flexible; after all, it was the inflexibility in the duck behaviors that got us into trouble in the first place. And we know that we want to assign behaviors to the instances of Duck. For example, we might want to instantiate a new MallardDuck instance and initialize it with a specific type of flying behavior. And while we’re there, why not make sure that we can change the behavior of
    a duck dynamically? In other words, we should include behavior setter methods in the Duck classes so that we can, say, change the MallardDuck’s flying behavior at runtime.

    and here is the class diagram for this approach

    Abstract Duck.cs

     public abstract class Duck
        {
            protected IFlyBehavior flyBehavior;
            protected IQuackBehavior quackBehavior;
    
            public IQuackBehavior QuackBehavior
            {
                get
                {
                    return quackBehavior;
                }
                set
                {
                    quackBehavior = value;
                }
            }
    
            public IFlyBehavior FlyBehaviour
            {
                get
                {
                    return flyBehavior;
                }
                set
                {
                    flyBehavior = value;
                }
            }
    
            public abstract object Display();
    
            public object PerformFly()
            {
                return FlyBehaviour.Fly();
            }
    
            public object PerformQuack()
            {
                return QuackBehavior.Quacking();
            }
    
            public string Swim()
            {
                return "All ducks float, even toys ...";
            }
        }
    

    IFlyBehavior

    public interface IFlyBehavior
        {
            object Fly();
        }
    

    FlyNoWay.cs – No flying Behaviour

      public class FlyNoWay : IFlyBehavior
        {
            public object Fly()
            {
                return "I can't fly.";
            }
        }
    

    FlyRocketPowered.cs – Flying with rocket behaviour

    public class FlyRocketPowered : IFlyBehavior
        {
            public object Fly()
            {
                return "I'm flying with a rocket";
            }
        }
    

    FlyWithWings – normal flying behaviour

     public class FlyWithWings : IFlyBehavior
        {
            public object Fly()
            {
                return "I'm flying!!";
            }
        }
    

    IQuackBehavior

    public interface IQuackBehavior
        {
            object Quacking();
        }
    

    MuteQuack .cs

    class MuteQuack : IQuackBehavior
        {
            public object Quacking()
            {
                return "<<silence>>";
            }
        }
    

    Quack.cs

     public class Quack : IQuackBehavior
        {
            public object Quacking()
            {
                return "Quack";
            }
        }
    

    Squeak.cs

    public class Squeak : IQuackBehavior
        {
            public object Quacking()
            {
                return "Squeak";
            }
        }
    

    MallardDuck.cs

     public class MallardDuck : Duck
        {
            public MallardDuck()
            {
                quackBehavior = new Quack();
                flyBehavior = new FlyWithWings();
            }
            public override object Display()
            {
                return "I'm a real Mallard duck";
            }
        }
    }
    

    ModelDuck.cs

     public class ModelDuck : Duck
        {
            public ModelDuck()
            {
                flyBehavior = new FlyNoWay();
                quackBehavior = new Quack();
            }
            public override object Display()
            {
                return "I'm a model duck";
            }
        }
    

    And finally this is our test class….

      [TestClass]
        public class DuckTest
        {
            [TestMethod]
            public void TestMallardDuck()
            {
                var mallard = new MallardDuck();
                Assert.AreEqual("Quack", mallard.PerformQuack());
                Assert.AreEqual("I'm flying!!", mallard.PerformFly());
            }
    
            [TestMethod]
            public void TestModelDuck()
            {
                var modelDuck = new ModelDuck();
                Assert.AreEqual("Quack", modelDuck.PerformQuack());
                Assert.AreEqual("I can't fly.", modelDuck.PerformFly());
    
                modelDuck.FlyBehaviour = new FlyWithWings(); // changing the behavior runtime
                Assert.AreEqual("I'm flying!!", modelDuck.PerformFly());
            }
        }
    

    As you can see.. in the test case we are changing behavior of the duck dynamically.. 🙂

    Recap

    what we have done..??

    we made Abstract duck class have IFlyBehavior and IQuackBehavior with getters and setters.. and child class will set those behaviors. with this approach we can adapt to any future changes easily..

    we completed implementing Strategy pattern… 🙂

    Journey towards design patterns

    back from grave… lost completely these two months..i think i am so bloody lazy…could keep up the desire to blog…

    Started reading Head First design patterns.. and will try to blog what i had learned reading this book.. hopefully i will complete alteast this book… 🙂

    I have had experience reading Head First series .. actually i read head first C# book.. the way the authors explain the concepts is different..actually very good… found it a bit of both practical and theoretical…