Software Design Patters : Principle : Open Close Principle

patterns

I was about to write on the Factory Pattern and the while preparing the post thinking I kept referring to the Open Closed Principle and thought let me talk about this first, so along with Patterns I will keep adding a few principles along the way.

Open Closed Principle basically states that your code should be Open for Extension but Closed for Modification

So what does this mean ? Basically this means that the software entities should be written in such a way that the extending it should be fairly easy and you should not be actually hacking into the original code to introduce a new way.
Let me take a simple example, say you are building a shopping cart, and you have to accept the payment from the user. If the principle is not applied the code would be written something like (this is simplifying a lot but you should get the idea.

       public bool ProcessCart(Cart cart, string PaymentMethod)
        {
            switch (PaymentMethod)
            {
                case "Cash On Delivery":
                    return PayUsingCash(cart);
                case "Credit Card":
                    return PayUsingCreditCard(cart);
            }
        }

This code should function fine but the problem is this method is closed for extension and to introduce a new payment method we have to modify the code and introduce a new case and then implement it, every time we need to implement a new payment method we have to go in and modify the original code, which means retest the whole thing,
What Open Closed principle suggests is that the this code should be open for extension and should not be modified. Thus if we were to re factor this into OCP our code would look something like

       interface IPaymentProcessor
       {
           bool Process(Cart cart);
       }
 
       public bool ProcessCart(Cart cart, String PaymentMethod)
       {
           IPaymentProcessor payproc = PaymentFactory.CreateProcessor(PaymentMethod);
           payproc.Process(cart);
       }

We basically start Of with an interface which implements a method called Process, and our ProcessCart Method does not have to worry about the options available, the PaymentFactory is responsible for the getting the payment processor based on parameter, and this factory can be designed to read the available options say using configuration thus eliminating the need to recompile code everytime a new payment processor is added.
I will dwell into the details of the FactoryPattern in my next post on how exactly we can do this.
In the meanwhile please feel free to comment on the posts.

31
Jan 2012
Author naresh
Comments No Comments

Software Design Patterns : Command Pattern

patterns

So As Promissed we are Starting of with command pattern, I feel that the command pattern is simple and highly resuable,
This is also called an Action pattern, and the pattern is just that it represents an action as an object, and this pattern completely decouples the client to the inner working of the command, the command is self contained meaning it handles its own dependencies and requirements, the client is just responsible calling the command, The advanatage of this being you can build an extensible framework of actions and you would not e have to write up the complex logic of looking up a command and passing arguements into it. This implementation also allows you to do a batch command processing, Logging also become easier as the execution of a command can be used to enforce logging, so does the reversal of the command,
Let me start of with a example, Even though I could have started off with a command line utility as all others do, I would take the much harder route and acually show you a realworld example, A WYSIWIG Text Editor with Simple Formatting Options. (This is would really be a very simple editor).
So Start of with the base command structure, its just a interface with a single method which doesn’t accept any parameters.

    public interface ICommand 
    {
        void ApplyFormatting();
    }

Because we will be working with a Text Editor Let me go ahead and setup a class which will serve as the base for the all the toggle commands, Note that to keep things simple I have oversimplified the implementation and also basically limited myself to three actions but you get the Idea. Down the line i will update this to be more proper.

  public abstract class ToggleCommand : ICommand, INotifyPropertyChanged
    {
        public RichTextBox TextEditor { get; set; }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        public void NotifyPropertyChanged(string Property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(Property));
        }
 
        public ToggleCommand(RichTextBox TextEd)
        {
            TextEditor = TextEd;
            TextEditor.KeyDown += (s, e) => { NotifyPropertyChanged("IsChecked"); };
            TextEditor.MouseClick += (s, e) => { NotifyPropertyChanged("IsChecked"); };
        }
 
        public abstract bool IsChecked { get; }
 
        public abstract void ApplyFormatting();
 
        protected void ApplyToggle(FontStyle Style)
        {
            var condition = (Style == FontStyle.Bold) ? TextEditor.SelectionFont.Bold : (Style == FontStyle.Italic) ? TextEditor.SelectionFont.Italic : TextEditor.SelectionFont.Underline;
            if (condition)
                TextEditor.SelectionFont = new Font(TextEditor.SelectionFont.FontFamily, TextEditor.SelectionFont.Size, TextEditor.SelectionFont.Style ^ Style);
            else
                TextEditor.SelectionFont = new Font(TextEditor.SelectionFont.FontFamily, TextEditor.SelectionFont.Size, TextEditor.SelectionFont.Style | Style);
        }
 
        protected bool IsFormattingApplied(FontStyle Style)
        {
            if (TextEditor.SelectionLength > 0)
            {
                var condition = (Style == FontStyle.Bold) ? TextEditor.SelectionFont.Bold : (Style == FontStyle.Italic) ? TextEditor.SelectionFont.Italic : TextEditor.SelectionFont.Underline;
                return condition;
            }
            else
            {
                var i = TextEditor.SelectionStart;
                TextEditor.Select(i, 1);
                var condition = (Style == FontStyle.Bold) ? TextEditor.SelectionFont.Bold : (Style == FontStyle.Italic) ? TextEditor.SelectionFont.Italic : TextEditor.SelectionFont.Underline;
                TextEditor.Select(i, 0);
                return condition;
            }
        }
    }

As mentioned the command takes care of all the requirements and is self contained, As we are working on WYSIWIG editor the command needs a RichTextEditor to work with, and implements the ICommand Interface, I have also made this implement the INotifyPropertyChanged and introduce a property which exposes the state text at current position.
From then on its straight forward implement this class
For Bold

 class BoldCommand : ToggleCommand
    {
        public BoldCommand(RichTextBox TextControl)
            : base(TextControl)
        {
 
        }
        public override void ApplyFormatting()
        {
            ApplyToggle(FontStyle.Bold);
            NotifyPropertyChanged("IsChecked");
        }
 
        public override bool IsChecked
        {
            get
            {
                return IsFormattingApplied(FontStyle.Bold);
            }
        }
    }

For Italic

 public class ItalicCommand : ToggleCommand
    {
        public ItalicCommand(RichTextBox TextControl)
            : base(TextControl)
        {
 
        }
 
        public override bool IsChecked
        {
            get { return IsFormattingApplied(System.Drawing.FontStyle.Italic); }
        }
 
        public override void ApplyFormatting()
        {
            ApplyToggle(System.Drawing.FontStyle.Italic);
            NotifyPropertyChanged("IsChecked");
        }
    }

For Underline

 public class UnderlineCommand : ToggleCommand
    {
        public UnderlineCommand(RichTextBox TextControl)
            : base(TextControl)
        {
 
        }
 
        public override bool IsChecked
        {
            get { return IsFormattingApplied(System.Drawing.FontStyle.Underline); }
        }
 
        public override void ApplyFormatting()
        {
            ApplyToggle(System.Drawing.FontStyle.Underline);
            NotifyPropertyChanged("IsChecked");
        }
    }

To Visualize this


Due to All this the client is very simple

 private void Form1_Load(object sender, EventArgs e)
        {
            actionToolStripButtonBold.Command = new BoldCommand(this.richTextBox1);
            actionToolStripButtonItalic.Command = new ItalicCommand(this.richTextBox1);
            actionToolStripButtonUnderline.Command = new UnderlineCommand(this.richTextBox1);
        }
 
        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ((ActionToolStripButton)e.ClickedItem).Command.ApplyFormatting();
        }

I have attched the project file for download

29
Jan 2012
Author naresh
Comments No Comments

Software Design Patterns : The Primer : Introduction

patterns

My primary work is designing. I earn my living by designing applications small and large. And because designing software more or less is bringing solution to problem, the steps you take also are similar. You break down the problem, you solve each piece using either your existing knowledge of learn from others and the complete the solution, you reuse the same methods to solve the same kind of problems. This is what is called a pattern,  a pattern is all about how you approach the problem, its not about semantics on how you solve a particular piece.

Software Design patterns are also the same, its about how you solve common problems that are encountered every time you design a software. A pattern has less to do with actual code and more to do with the approach(or can be eloquently put as less to do with algorithms). And patterns are abstractions over code meaning there is no set conventions on a pattern like naming of classes etc, and also that these patterns have no barrier of programming language, there are some specific cases where few patters make more sense on a particular programming platform, but in general you should be able to use them across languages and platforms. And if you are into LOB applications its pretty certain that somebody else has already solved the problem that you are facing. So Its better to know about the existing patterns and how they can help you solve your problems, and Patterns range wide, starting from a very simple one which makes say a Data Structure mode bind able to issues in enterprise architecture.

Design Patterns can be classified into categories based on what problems you are trying to solve and the list is fairly extensive, just to pull of few on top of my head

  • Creation
  • Functional
  • Parallel Programming
  • Behavioral
  • Security
  • User Interface
  • Concurrency
  • Distributed Computing
  • Relational

and the list is growing and as new problems and new ways of solving them are found.

So the big question why should I care about Design Patterns ?, The simplest answer for this question is that you do not reinvent a wheel, the problem you are facing in software architecture is not always unique and understanding patterns will get you started quickly in solving the problems. Benefits also include decrease in effort and improvement in development time, and the application will generally have a better design and can be universally understandable.

So What Next? Over the next series of posts I plan to put information on few of the simple patters to more complex ones, I am trying to make this as simple as possible and get the discussion started, and even though design patters are fairly simple to understand what I would be writing is just my understanding and experience and should not be considered the final authority. I also plan to do simple implementation examples and again those would be just mine. For the simpler Patterns i would be using C# as the language but down the line when we get to say MVVM I also plan to include some iOS Code.

To begin with I will be writing about the Command Pattern which according to me is a highly reused pattern.

Find Control of a Type in WPF

I had previously written a piece of Code to retrieve a control of a single type in ASP.net, now working on WPF I had to do basically the same thing, and VisualTreeHelper came to the rescue.

In this process I discovered that if the content of the user control/window is a scroll panel you have to reference the scroll panel. so without further blabber , here is the code. (Please Note that this also works with controls inside a groupbox)

   public static class VisualEnumerable
    {
        /// <summary>
        /// Gets the Visual Tree filtered by Type for a DependencyObject with that DependencyObject as the root.
        /// </summary>
        public static IEnumerable<t> GetVisualOfType</t><t>(this DependencyObject element)
        {
            var temp = GetVisualTree(element).ToList();
            return temp.Where(t => t.GetType() == typeof(T)).Cast</t><t>();
        }
 
        /// <summary>
        /// Gets the Visual Tree for a DependencyObject with that DependencyObject as the root.
        /// </summary>
        public static IEnumerable<dependencyobject> GetVisualTree(this DependencyObject element)
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(element);
 
            for (int i = 0; i < childrenCount; i++)
            {
                var visualChild = VisualTreeHelper.GetChild(element, i);
                if (visualChild != null) yield return visualChild;
 
                if (visualChild is GroupBox)
                {
                    var gb = visualChild as GroupBox;
                    object gpChild = gb.Content;
                    yield return visualChild;
                    visualChild = (DependencyObject)gpChild;
                }
 
                foreach (var visualChildren in GetVisualTree(visualChild))
                {
                    yield return visualChildren;
                }
            }
        }
    }

To Use this you can simply do

var textboxes = this.MainPanel.GetVisualOfType<textbox>()
</textbox>

04
Jan 2012
Author naresh
Comments No Comments

iOS 5 GUI psd kit

An absolute must have for ios designers

18
Oct 2011
Author naresh
Category

Web

Comments No Comments
TAGS

Recover Jobs from a crashed SQL Server

I recently came across the scenario where a SQL server had crashed (with Windows) but the file system was intact, so we started restore of databases which was straight forward as easy as attaching to the new instance on different server. But we also had lot of jobs scheduled on the old server, and wanted to recover them as well, so after a doing a bit of search figured out that the jobs are saved in “msdb” system database.

So to restore
  1. Create a dummy instance of SQL Server.
  2. Stop the instance.
  3. Replace the .mdf & .ldf files from the crashed server of the msdb database.
  4. Start the Server Instance as well as agent.
  5. voila, you have your jobs, now script those jobs and execute on new server

and you are good to go..

11
Oct 2011
Author naresh
Comments No Comments

Nifty Little script to check identity columns

I had to recently check for identity specification on all the tables in a database and this nifty little script helped me in doing this.

Thanks Akshay for writing this for me.

CREATE PROC dbo.CheckIdentities  
AS  
BEGIN  
 SET NOCOUNT ON  
 
 SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' +  QUOTENAME(t.name) AS TableName,   
  c.name AS ColumnName,  
  CASE c.system_type_id  
   WHEN 127 THEN 'bigint'  
   WHEN 56 THEN 'int'  
   WHEN 52 THEN 'smallint'  
   WHEN 48 THEN 'tinyint'  
  END AS 'DataType',  
  IDENT_CURRENT(SCHEMA_NAME(t.schema_id)  + '.' + t.name) AS CurrentIdentityValue,  
  CASE c.system_type_id  
   WHEN 127 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id)  + '.' + t.name) * 100.) / 9223372036854775807  
   WHEN 56 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id)  + '.' + t.name) * 100.) / 2147483647  
   WHEN 52 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id)  + '.' + t.name) * 100.) / 32767  
   WHEN 48 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id)  + '.' + t.name) * 100.) / 255  
  END AS 'PercentageUsed'   
 FROM sys.COLUMNS AS c   
  INNER JOIN  
  sys.TABLES AS t   
  ON t.[object_id] = c.[object_id]  
 WHERE c.is_identity = 1  
 ORDER BY PercentageUsed DESC  
END
10
Oct 2011
Author naresh
Category

.net Programming

Comments No Comments
TAGS

,

New Look & House Cleaning

For a long time i have kept the look for a photography portfolio for my site, but i felt that this was not updated for a long time, i havent done too much of photography in the last year and all unimportant ones have been pushed to Facebook, So i thought why not re organise and give more focus on blog, which at least is updated, so here is the new look, I really liked the tumbler look, thus a lovechild of wordpress and tumblr, and beacuse i did this there are still a few things which are completely broken like the photography posts, i am still resolving the best way to resolve this, ill update this post once done, please leave comments on this post if you feel anything needs to be addressed.

08
Oct 2011
Author naresh
Category

Blog, Personal

Comments No Comments
TAGS

Asp.net ReportViewer : Access Remote Server Report with Credentials

If you want to work with remote SSRS report while debugging your asp.net application you would want to authenticate with the remote server, you cannot use asp.net impersonation as this would actually make the entire application run under impersonation so to solve this we can use impersonation for the report viewer only to do this :

#if (DEBUG)
this.ReportViewer1.ServerReport.ReportServerCredentials = new ReportServerCredentials("username", "password","domain");
#endif

and a ReportServerCredentials class

public class ReportServerCredentials : IReportServerCredentials
    {
        private string _userName;
        private string _password;
        private string _domain;
 
        public ReportServerCredentials(string userName, string password, string domain)
        {
            _userName = userName;
            _password = password;
            _domain = domain;
        }
 
        public System.Security.Principal.WindowsIdentity ImpersonationUser
        {
            get { return null; }
        }
 
 
        public System.Net.ICredentials NetworkCredentials
        {
            get { return new System.Net.NetworkCredential(_userName, _password, _domain); }
        }
 
 
        bool IReportServerCredentials.GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)
        {
            authCookie = null;
            userName = _userName;
            password = _password
            authority = _domain;
            return false;
        }
    }

Janlokpal Bill : An overview and my unanswered questions

I have been watching closely on what was happening with the entire process of fasts, demonstrations over Lokpal and Janlokpal bill, I went through the bullet points of Janlokpal bill and began wondering, how does this bill help in curbing corruption or for that matter bringing back the black money back to India, I have seen so many people get behind this movement most of them not knowing what the content of the bill is and how does it improve their lives, I know that people are fed up of corruption and want it rooted out but there is a lot more to this than just a bill.
Let us first discuss what Janlokpal bill wants to achieve and my doubts and counter arguments on why this would not be enough, All this keeping in mind that that I am not against the bill.

These are salient features of the bill (taken from http://www.indiaagainstcorruption.org/salient.html)

  • An institution called LOKPAL at the centre and LOKAYUKTA in each state will be set up
  • Like Supreme Court and Election Commission, they will be completely independent of the governments. No minister or bureaucrat will be able to influence their investigations.
  • Cases against corrupt people will not linger on for years anymore: Investigations in any case will have to be completed in one year. Trial should be completed in next one year so that the corrupt politician, officer or judge is sent to jail within two years.
  • The loss that a corrupt person caused to the government will be recovered at the time of conviction.
  • How will it help a common citizen: If any work of any citizen is not done in prescribed time in any government office, Lokpal will impose financial penalty on guilty officers, which will be given as compensation to the complainant.
  • So, you could approach Lokpal if your ration card or passport or voter card is not being made or if police is not registering your case or any other work is not being done in prescribed time. Lokpal will have to get it done in a month’s time. You could also report any case of corruption to Lokpal like ration being siphoned off, poor quality roads been constructed or panchayat funds being siphoned off. Lokpal will have to complete its investigations in a year, trial will be over in next one year and the guilty will go to jail within two years.
  • But won’t the government appoint corrupt and weak people as Lokpal members? That won’t be possible because its members will be selected by judges, citizens and constitutional authorities and not by politicians, through a completely transparent and participatory process.
  • What if some officer in Lokpal becomes corrupt? The entire functioning of Lokpal/ Lokayukta will be completely transparent. Any complaint against any officer of Lokpal shall be investigated and the officer dismissed within two months.
  • What will happen to existing anti-corruption agencies? CVC, departmental vigilance and anti-corruption branch of CBI will be merged into Lokpal. Lokpal will have complete powers and machinery to independently investigate and prosecute any officer, judge or politician.
  • It will be the duty of the Lokpal to provide protection to those who are being victimized for raising their voice against corruption.

So we are basically setting up a new institution which is supposed to be independent, but how can this institution be independent, how would the members of the committee be appointed, it is always mentioned that the committee would be comprised of eminent people, but who would the judge of this, we are the people who knowingly elect so called corrupt people into parliament, so should we be responsible for appointing people ? If not us then who is going to this.

The next being who is going to conduct the investigations and how can it me made sure that the investigations are unbiased, if the corrupt are able to coarse the existing investigation agencies, I am sure that this would be no exception, and how would the timeline of one year for investigation and one year for trail be met? where are the proposed changes for the judicial systems which would allow this timeline to come into existence ? And what would be the appeal process ? the officer/politician would always say that they have done nothing wrong and would want to appeal, In this scenario are they re investigated or would the initial investigation and judgement would be held authoritative ?

And i would not even try to address the point of recovery of loss from convicted as this seems too much hypothetical, good luck trying to get back money from A.Raja or Suresh Kalmadi.

And if Lokpal would be approached for every other issue, how is it going to address the huge list of complaints that it is going to receive ? again we would be ending up in a system which looks like our judicial system.

Again coming back to the process of selection of members this is a point which has not been addressed to in any of the discussions that i have seen. There is no guarantee that even after all the other anti corruption agencies are merged this  institution would independent enough or that the people in this institution cannot be influenced, so how can this be addressed ?

The very first counter argument that i always receive is that this a begging step and and we would have to start somewhere. But if we are fighting for it so passionately why settle for first step why not for more? , I welcome you to join this discussion and educate me if I am wrong but I still don’t see light at the end of the dark tunnel of corruption we are in.

23
Aug 2011
Author naresh
Category

Blog, Personal

Comments 4 Comments