Software Design Patters : Principle : Open Close Principle
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.
Software Design Patterns : Command Pattern
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
Software Design Patterns : The Primer : Introduction
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.