Category: Design Patterns

.NET

Design Patterns

pattern is a commonly occurring reusable piece in software system that provides a certain set of functionality.A pattern is a commonly occurring reusable piece in software system that provides a certain set of functionality. The identification of a pattern is also based on the context in which it is used. Design patterns are solutions to general problems that software developers faced during software development. So, using patterns in modelling of systems helps in keeping design standardised and more importantly, minimizes the reinventing of the wheel in the system design. This article is all about patterns; especially design patterns.The class diagram in UML can be used to capture the patterns identified in a system.

Factory Method

  • How does this promote loosely coupled code?

A Factory pattern returns an instance of one of several possible classes, depending on the data provided to it.  Usually, all the classes it returns have a common parent class and common methods, but each of them performs a different task, and is optimized for different kinds of data.  Thus, the Factory pattern eliminates the need to bind application specific classes into the code.  The code only deals with the Product interface , and can therefore work with any user-defined Concrete Product classes. Thus the code is not tightly bound to a particular application. for eg. in the example discussed in class(and the book), the abstract classes Application and Document have generic methods to manipulate documents. However, to realize the application specific implementation, one has to subclass them- say a DrawingApplication and DrawingDocument for drawings, TextApplication and TextDocument.Instead of putting code inside Document and Application classes for each document type (binding application specific code), the factory method lets them defer the instantiation for a specific application to a subclass.

Proxy

  • If a Proxy is used to instantiate an object only when it is absolutely needed, does the Proxy simplify code?


This is not necessarily true.  A proxy pattern is used when we need to represent a complex object by a simpler one.  It provides a certain level of indirection when accessing an object.  A proxy usually has the same methods as the object it represents, and hence provides an identical interface to that object.  This definitely improves performance, but may or may not simplify the code.  In some cases, the overall code may become simpler.  e.g. protection proxies and smart references allow housekeeping tasks when an object is accessed (access permissions, ref counts, object locking etc.) This makes the Subject code simpler as it does not have to bother with the bookkeeping code. Thus a Proxy would simplify Subject code, by moving it to the RealSubject code, at the expense of implementing the Proxy code.

Strategy

  • What happens when a system has an explosion of strategy objects? Is there some better way to manage these strategies?


There are several ways to manage these strategies if a system has an explosion of strategy objects.  One way is to use the Template pattern which would in turn use several simpler strategy classes.  Such an explosion could occur if there are a lot of strategies for one context, or several context objects and corresponding strategy objects.  This leads to increased load on memory and system resources.  Other ways to manage this would be to implementing strategies as stateless objects that contexts can share, or making strategy objects optional. 

  • (ii) In the implementation section of this pattern, the authors describe two ways in which a strategy can get the information it needs to do its job. One way describes how a strategy object could get passed a reference to the context object, thereby giving it access to context data. But is it possible that the data required by the strategy will not be available from the context’s interface? How could you remedy this potential problem?


Yes, it is possible that the data required by the strategy will not be available from the context’s interface.  If the data were private to the context (not accessible from the interface), then the strategy would not be able to access it.  We could pass all the data required by the strategy explicitly, although this increases communication overhead.  We could also use strategies as template parameters – in this case, since the strategy would be a context method, the data would be accessible.

 

Decorator

  • In the Implementation section of the Decorator Pattern, the authors write: A decorator object’s interface must conform to the interface of the component it decorates. Now consider an object A, that is decorated with an object B. Since object B “decorates” object A, object B shares an interface with object A. If some client is then passed an instance of this decorated object, and that method attempts to call a method in B that is not part of A’s interface, does this mean that the object is no longer a Decorator, in the strict sense of the pattern? Furthermore, why is it important that a decorator object’s interface conforms to the interface of the component it decorates?


If some client is then passed an instance of this decorated object, and that method attempts to call a method in B that is not part of A’s interface, this does NOT necessarily mean that the object is no longer a Decorator, in the strict sense of the pattern. Object B’s interface is still the same as object A’s interface although some more methods are added.  The book says that a decorator and its component are not identical. Component can add functionality to the base class. Decorator object’s interface should conform to the interface of the component it decorates because of the inheritance issues, since the Decorator acts as a transparent enclosure.  The client would be unaware of the decorators presence, and would access the contents of the object through a common interface.

 

Adapter

  • Would you ever create an Adapter that has the same interface as the object which it adapts? Would your Adapter then be a Proxy?


An Adapter could indeed have the same interface as the object which it adapts.  In that case, the adapter would add some extra functionality before making the call to the adaptee object.  So, we would not want the exact same interface.  But in the case of a proxy, we do want the same interface since it is a virtual placeholder for an object.  Also, the adapter’s implementation would be different from that of the proxy.

Bridge

  • How does a Bridge differ from a Strategy and a Strategy’s Context?


A strategy is a behavioral pattern that allows a client (Strategy context) to interchangably use multiple algorithms (Strategy).  A bridge is a structural pattern that influences the creation of a class hierarchy by decoupling an abstraction from the implementation.   In a strategy, usually the Strategy is allowed to vary to change the behavior of the algorithm, while the Context may not vary as much. In a bridge however, the abstraction and its implementation can vary independently, and it hides the implementation details from the client.

 

Facade

  • (i) How complex must a sub-system be in order to justify using a facade?


A facade is justified whenever the dependencies between the clients and the implementation classes of an abstration become complex enough to decouple the subsystem.  Sometimes, it is justified to use even for single class subsystem, if we expect that to grow in the future (although this would be against the principles of extreme programming 🙂 

  • (ii) What are the additional uses of a facade with respect to an organization of designers and developers with varying abilities? What are the political ramifications?


The facade in indeed a great tool for an organization of designers and developers with varying abilities.  It provides a simple access to complex subsystems for less experienced participants, but as they grow and learn, they could access the subsystems directly.  Also, the developers may present a facade of the system to the designers, thus the designers do have to concern themselves about the details of the subsystems.  Thus the developers could extend on the subsystem code independently, without affecting the design.

 

Composite

  • (i) How does the Composite pattern help to consolidate system-wide conditional logic?


It does this by providing a general design which makes client code simple and makes it easier to add new kinds of components. Thus the clients can treat composite structures and individual objects uniformly,  without worrying about whether they’re a leaf or composite node.  This helps avoid a lot of case style statements. 

  • (ii) Would you use the composite pattern if you did not have a part-whole hierarchy? In other words, if only a few objects have children and almost everything else in your collection is a leaf (a leaf that has no children), would you still use the composite pattern to model these objects?


We could still use a composite pattern here to provide a common interface to all the objects.  Thus we may define a composite pattern and call an operation on the component, when we wish to issue an operation on a few composite objects, and all the leaf objects.

Iterator

  • Consider a composite that contains loan objects. The loan object interface contains a method called “AmountOfLoan()”, which returns the current market value of a loan. Given a requirement to extract all loans above, below or in between a certain amount, would you write or use an Iterator to do this?


An iterator goes through all the objects, and hence that would be a very inefficient search, given our problem.  However, if we built the hierarchy like a binary search tree and stored some min/max key value at each composite node, then we could implement an iterator to go through the children of a composite which satisfies the current search criterion.

 

Template Method

  • The Template Method relies on inheritance. Would it be possible to get the same functionality of a Template Method, using object composition? What would some of the tradeoffs be?


Yes, but we would then have to store the state of our class in such a way that all the different objects can access it.  But we couldn’t run these at the same time, unless they are very independent of each other.

 

Abstract Factory

  • In the Implementation section of this pattern, the authors discuss the idea of defining extensible factories. Since an Abstract Factory is composed of Factory Methods, and each Factory Method has only one signature, does this mean that the Factory Method can only create an object in one way?


We would have to specify different concrete factory subclasses in order to create an object in multiple ways.  We could avoid this by using a prototype pattern for implementing the concrete factory. 

  • Consider the MazeFactory example. The MazeFactory contains a method called MakeRoom, which takes as a parameter one integer, representing a room number. What happens if you would also like to specify the room’s color & size? Would this mean that you would need to create a new Factory Method for your MazeFactory, allowing you to pass in room number, color and size to a second MakeRoom method?


In the current MazeFactory implementation we would have to add another Factory Method with a MakeRoom method to create a room with a number, color and size. We could also use overloaded constructors which take multiple arguments (and initialize some, e.g. color and size to a default if we want to pass only the room number). The other alternative would be to use a prototype based approach, in which the concrete MakeRoom factory would have methods to add color, size parts to the catalog.

Builder

  • Like the Abstract Factory pattern, the Builder pattern requires that you define an interface, which will be used by clients to create complex objects in pieces. In the MazeBuilder example, there are BuildMaze(), BuildRoom() and BuildDoor() methods, along with a GetMaze() method. How does the Builder pattern allow one to add new methods to the Builder’s interface, without having to change each and every sub-class of the Builder?


The builder method returns child nodes back to the director, which passes them back to the builder to build additional/parent nodes. MazeBuilder does not create the maze itself, but just defines the interface for creating mazes – letting the subclasses do the actual work. Since the subclasses use the methods defined in the Builder interface, adding  a new method to the interface would not require changing each subclass as the original methods would still work and create a valid maze. Once might want to create a new subclass of the builder to make use of the additional methods in the Builder’s interface.

 

Singleton

  • The Singleton pattern is often paired with the Abstract Factory pattern. What other creational or non-creational patterns would you use with the Singleton pattern?


We could also use the Facade pattern since we would need a single instance of a point of entry/layer to the subsystem.  We could also use a mediator with a singleton, providing one controller for the system of classes, and a proxy with a singleton, providing a single placeholder to the real object.

 

Mediator

  • Since a Mediator becomes a repository for logic, can the code that implements this logic begin to get overly complex, possible resembling spaggheti code? How could this potential problem be solved?


Yes, this is likely to happen in certain situations.  We could then use a behavioral pattern such as strategy to couple together a family of policies to be used depending on the classes.  We may also group the classes into a hierarchy and use the Composite pattern to talk to them, simplifying code in the client (the mediator).

 

Observer

  • (i) The classic Model-View-Controller design is explained in Implementation note #8: Encapsulating complex update semantics. Would it ever make sense for an Observer (or View) to talk directly to the Subject (or Model)?


The Observer may request an immediate update from the Subject without going through the Controller, when we need a “real-time” update of the Subject.  This would, however, create redundant update and synchronization issues, and would be in conflict with the Mediator based design of the Controller. 

  • (ii) What are the properties of a system that uses the Observer pattern extensively? How would you approach the task of debugging code in such a system?


The system can be divide into two distinct part – the observers and the subjects.   If we were to model the relationships between objects as graph links, the graph would resemble a digraph.   We could then debug the two components of the digraph independantly.  We could first check if the subjects are updating states correctly, observers are recording the updates correctly, and then check if the communication(update) protocol between the two is working correctly. 

  • (iii) Is it clear to you how you would handle concurrency problems with is pattern? Consider an Unregister() message being sent to a subject, just before the subject sends a Notify() message to the ChangeManager (or Controller).


We would have to add a communication protocol at the Controller for handling the updates. e.g. the Controller could buffer the updates from the subjects, check if the system is in a consistent state, send the updates to the observers, check for consistency and then send the messages to the subjects.  It would be trade-off between efficiency and consistency.

 

Chain of Responsibility

  • (i) How does the Chain of Responsibility pattern differ from the Decorator pattern or from a linked list?.


In a chain, an object in the chain may or may not act on a request and just pass it on to the next object(handler). A decorator, however, adds responsibilites to an object dynamically, and each object in the list adds responsibilities.  Also in a chain, a receipt is not guaranteed (the request can drop off the end of the chain without ever being handled) 

  • (ii) Is it helpful to look at patterns from a structural perspective? In other words, if you see how a set of patterns are the same in terms of how they are programmed, does that help you to understand when to apply them to a design?


Yes, sometimes it helps.  And of course, experience with programming, and using the right patterns helps tp figure out more easily what patterns to use in a given situation.

 

Memento

  • The authors write that the “Caretaker” participant never operates on or examines the contents of a memento. Can you consider a case where a Caretaker would infact need to know the identity of a memento and thus need the ability to examine or query the contents of that memento? Would this break something in the pattern?


The idea of the memento is based on that the “Caretaker” participant never operates on or examines the contents of a memento.  So, yes, the pattern is broken if it is allowed to examine or query the contents of the memento.  But, say we wish to ensure that something cannot be “undone” after a certain action, then we would need such an ability for the Caretaker.

 

Command

  • In the Motivation section of the Command pattern, an application’s menu system is described. An application has a Menu, which in turn has MenuItems, which in turn execute commands when they are clicked. What happens if the command needs some information about the application in order to do its job? How would the command have access to such information such that new comamnds could easily be written that would also have access to the information they need?


In such a case, the application and the command could both access a made-up in-between object, so that the command could get the information that way.  We can create more commands, but we need to make them all aware of this in-between object.

 

Prototype

  • (i) When should this creational pattern be used over the other creational patterns?


Prototype hides the concrete product classes from the user, reducing the number of names the user needs to know.  This is of course common to several creational patterns.  But the Prototype allows a client to be installed and removed at run time, which adds flexibility that other creational patterns don’t have. 

  • (ii) Explain the difference between deep vs. shallow copy.


With a shallow copy, pointers will be continue to be shared between the original and the copy.  i.e. the copy will not be completely independent because it will still refer to the same variable as the original.  With a deep copy, however, we copy the original itself, but we also make copies of all the variables’ original uses. So the new object is independent , because when it refers to a variable , it actually refers to its own variable, which is a copy of the original variable.

 

State

  • If something has only two to three states, is it overkill to use the State pattern?


Not really.  One uses the State pattern when the transitions between the states are complex.  Also, albeit in contrast with extreme programming principles, if future growth will demand more states, then the State pattern should be used.

 

Visitor

  • One issue with the Visitor pattern involces cyclicality. When you add a new Visitor, you must make changes to existing code. How would you work around this possible problem?


We could make a default Visitor that could be implemented by most of the other Visitors.

 

Flyweight

  • (i) What is a non-GUI example of a flyweight?


An example is the checkout system at a video store.  There are a large number of different objects here, but we make one single instance of an object and pass as an intrinsic state the data about who is checking out what video. 

  • (ii) What is the minimum configuration for using flyweight? Do you need to be working with thousands of objects, hundreds, tens?


There is better savings if more flyweights are shared, i.e. more objects are added.  However, it depends on the size of the objects.  If we use large and different objects and only few of them, we would still save space, although there is additional overhead for using the flyweight itself.

 

What are design patterns?

Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a problem context and the proposed solution for the same. Design patterns existed in some or other form right from the inception stage of software development. Let’s say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns.

 

Which are the three main categories of design patterns?

There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

 Abstract Factory:- Creates an instance of several families of classes 
 Builder: – Separates object construction from its representation 
 Factory Method:- Creates an instance of several derived classes 
 Prototype:- A fully initialized instance to be copied or cloned 
 Singleton:- A class in which only a single instance can exist

Note: – The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).
Structural Patterns

 Adapter:-Match interfaces of different classes. 
 Bridge:-Separates an object’s abstraction from its implementation. 
 Composite:-A tree structure of simple and composite objects. 
 Decorator:-Add responsibilities to objects dynamically. 
 Façade:-A single class that represents an entire subsystem.
 Flyweight:-A fine-grained instance used for efficient sharing. 
 Proxy:-An object representing another object.

Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns

 Mediator:-Defines simplified communication between classes.
 Memento:-Capture and restore an object’s internal state. 
 Interpreter:- A way to include language elements in a program.
 Iterator:-Sequentially access the elements of a collection. 
 Chain of Resp: – A way of passing a request between a chain of objects.
 Command:-Encapsulate a command request as an object. 
 State:-Alter an object’s behavior when its state changes. 
 Strategy:-Encapsulates an algorithm inside a class. 
 Observer: – A way of notifying change to a number of classes. 
 Template Method:-Defer the exact steps of an algorithm to a subclass. 
 Visitor:-Defines a new operation to a class without change.

Note: – Just remember Music……. 2 MICS On TV (MMIICCSSOTV).

Note :- In the further section we will be covering all the above design patterns in a more detail manner.

Can you explain factory pattern?

·         Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it’s meant to construct and create something. In software architecture world factory pattern is meant to centralize creation of objects. Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client. There are two issues with the code below:-

·         First we have lots of ‘new’ keyword scattered in the client. In other ways the client is loaded with lot of object creational activities which can make the client logic very complicated.

Second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type called as ‘InvoiceWithFooter’ we need to reference the new class in the client and recompile the client also.

clip_image003

Figure: – Different types of invoice

Taking these issues as our base we will now look in to how factory pattern can help us solve the same. Below figure ‘Factory Pattern’ shows two concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’.

The first issue was that these classes are in direct contact with client which leads to lot of ‘new’ keyword scattered in the client code. This is removed by introducing a new class ‘ClsFactoryInvoice’ which does all the creation of objects.

The second issue was that the client code is aware of both the concrete classes i.e. ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’. This leads to recompiling of the client code when we add new invoice types. For instance if we add ‘ClsInvoiceWithFooter’ client code needs to be changed and recompiled accordingly. To remove this issue we have introduced a common interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’ inherit and implement the ‘IInvoice’ interface.

The client references only the ‘IInvoice’ interface which results in zero connection between client and the concrete classes ( ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’). So now if we add new concrete invoice class we do not need to change any thing at the client side. 

In one line the creation of objects is taken care by ‘ClsFactoryInvoice’ and the client disconnection from the concrete classes is taken care by ‘IInvoice’ interface.


clip_image004

Figure: – Factory pattern

Below are the code snippets of how actually factory pattern can be implemented in C#. In order to avoid recompiling the client we have introduced the invoice interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithOutHeaders’ and ‘ClsInvoiceWithHeader’ inherit and implement the ‘IInvoice’ interface.

 

Figure :- Interface and concrete classes

We have also introduced an extra class ‘ClsFactoryInvoice’ with a function ‘getInvoice()’ which will generate objects of both the invoices depending on ‘intInvoiceType’ value. In short we have centralized the logic of object creation in the ‘ClsFactoryInvoice’. The client calls the ‘getInvoice’ function to generate the invoice classes. One of the most important points to be noted is that client only refers to ‘IInvoice’ type and the factory class ‘ClsFactoryInvoice’ also gives the same type of reference. This helps the client to be complete detached from the concrete classes, so now when we add new classes and invoice types we do not need to recompile the client.

clip_image005

Figure: – Factory class which generates objects

Note :- The above example is given in C# . Even if you are from some other technology you can still map the concept accordingly. You can get source code from the CD in ‘FactoryPattern’ folder.

Can you explain abstract factory pattern?

 

Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class. All other things related to factory pattern remain same as discussed in the previous question.

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client.

clip_image006

Figure: – Abstract factory unifies related factory patterns

 

Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (AbstractFactory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface. For instance in figure ‘Implementation of abstract factory’ both the concrete classes ‘product1’ and ‘product2’ inherits from one interface i.e. ‘common’. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit. 

clip_image008

Figure: – Implementation of abstract factory


Now let’s have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘ClsFactoryButton’ and ‘ClsFactoryText’. Both these classes inherit from common interface ‘InterfaceRender’. Both the factories ‘ClsFactoryButton’ and ‘ClsFactoryText’ inherits from the common factory ‘ClsAbstractFactory’. Figure ‘Example for AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( ClsAbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘ClsAbstractFactory’ class provides a common interface for both factories ‘ClsFactoryButton’ and ‘ClsFactoryText’. 

clip_image009

Figure: – Example for abstract factory

Note: – We have provided a code sample in C# in the ‘AbstractFactory’ folder. People who are from different technology can compare easily the implementation in their own language.

We will just run through the sample code for abstract factory. Below code snippet ‘Abstract factory and factory code snippet’ shows how the factory pattern classes inherit from abstract factory.

clip_image011

Figure: – Abstract factory and factory code snippet

Figure ‘Common Interface for concrete classes’  how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes.

clip_image013

Figure: – Common interface for concrete classes


The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘ClsAbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.

clip_image014

Figure: – Client, interface and abstract factory

 

Can you explain builder pattern?

Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction. 

clip_image015

Figure: – Builder concept


To understand what we mean by construction and representation lets take the example of the below ‘Tea preparation’ sequence.

You can see from the figure ‘Tea preparation’ from the same preparation steps we can get three representation of tea’s (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk). 

clip_image016

Figure: – Tea preparation


Now let’s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘EXCEL’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.

clip_image017

Figure: – Request a report

Now let’s take a different view of the problem as shown in figure ‘Different View’. The same flow defined in ‘Request a report’ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.

clip_image018

Figure: – Different View


We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

 Builder: – Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
 Director: – Director takes those individual processes from the builder and defines the sequence to build the product.
 Product: – Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportEXCEL’ builder will be built.

clip_image019

Figure: – Builder class hierarchy

 

Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). These two custom builders define there own process according to the report type.


 

clip_image021

Figure: – Builder classes in actual code

Now let’s understand how director will work. Class ‘clsDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or EXCEL.

 

 


clip_image023

Figure: – Director in action

 

 

The third component in the builder is the product which is nothing but the report class in this case.

 

 

clip_image024

Figure: – The report class

 

Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

 

 

 

clip_image026

Figure: – Client, builder, director and product 

 

 

The output is something like this. We can see two report types displayed with their headers according to the builder.

 

 

clip_image027

Figure: – Final output of builder

 


Note :- In CD we have provided the above code in C# in ‘BuilderPattern’ folder.

 

 

Can you explain prototype pattern?

 

 

Prototype pattern falls in the section of creational pattern. It gives us a way to create new objects from the existing instance of the object. In one sentence we clone the existing object with its data. By cloning any changes to the cloned object does not affect the original object value. If you are thinking by just setting objects we can get a clone then you have mistaken it. By setting one object to other object we set the reference of object BYREF. So changing the new object also changed the original object. To understand the BYREF fundamental more clearly consider the figure ‘BYREF’ below. Following is the sequence of the below code:-
• In the first step we have created the first object i.e. obj1 from class1.
• In the second step we have created the second object i.e. obj2 from class1.
• In the third step we set the values of the old object i.e. obj1 to ‘old value’.
• In the fourth step we set the obj1 to obj2.
• In the fifth step we change the obj2 value.
• Now we display both the values and we have found that both the objects have the new value.

 

 

clip_image028

Figure :- BYREf

 

 

The conclusion of the above example is that objects when set to other objects are set BYREF. So changing new object values also changes the old object value.

There are many instances when we want the new copy object changes should not affect the old object. The answer to this is prototype patterns.

Lets look how we can achieve the same using C#. In the below figure ‘Prototype in action’ we have the customer class ‘ClsCustomer’ which needs to be cloned. This can be achieved in C# my using the ‘MemberWiseClone’ method. In JAVA we have the ‘Clone’ method to achieve the same. In the same code we have also shown the client code. We have created two objects of the customer class ‘obj1’ and ‘obj2’. Any changes to ‘obj2’ will not affect ‘obj1’ as it’s a complete cloned copy.

 

clip_image029

Figure: – Prototype in action 

 

 


Note :- You can get the above sample in the CD in ‘Prototype’ folder. In C# we use the ‘MemberWiseClone’ function while in JAVA we have the ‘Clone’ function to achieve the same.

Can you explain shallow copy and deep copy in prototype patterns?

There are two types of cloning for prototype patterns. One is the shallow cloning which you have just read in the first question. In shallow copy only that object is cloned, any objects containing in that object is not cloned. For instance consider the figure ‘Deep cloning in action’ we have a customer class and we have an address class aggregated inside the customer class. ‘MemberWiseClone’ will only clone the customer class ‘ClsCustomer’ but not the ‘ClsAddress’ class. So we added the ‘MemberWiseClone’ function in the address class also. Now when we call the ‘getClone’ function we call the parent cloning function and also the child cloning function, which leads to cloning of the complete object. When the parent objects are cloned with their containing objects it’s called as deep cloning and when only the parent is clones its termed as shallow cloning.

 

 

clip_image030

Figure: – Deep cloning in action

 

 

Can you explain singleton pattern?

 

 

There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern:-

1) Define the constructor as private.
2) Define the instances and methods as static.

Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and methods using the static keyword as shown in the below code snippet figure ‘Singleton in action’. The static keyword ensures that you only one instance of the object is created and you can all the methods of the class with out creating the object. As we have made the constructor private, we need to call the class directly.

 

clip_image032

Figure: – Singleton in action


 

Note :- In JAVA to create singleton classes we use the STATIC keyword , so its same as in C#. You can get a sample C# code for singleton in the ‘singleton’ folder.

Can you explain command patterns?

 

Command pattern allows a request to exist as an object. Ok let’s understand what it means. Consider the figure ‘Menu and Commands’ we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of ‘IF’ condition which makes the coding more cryptic.

 

clip_image033

Figure: – Menu and Commands

 

Command pattern moves the above action in to objects. These objects when executed actually execute the command. 
As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.


 

clip_image034

Figure: – Objects and Command

 

Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action. 
So we have added all the actions in one collection i.e. the arraylist. We have exposed a method ‘getCommand’ which takes a string and gives back the abstract object ‘IExecute’. The client code is now neat and clean. All the ‘IF’ conditions are now moved to the ‘clsInvoker’ class.


 

clip_image036

Figure: – Invoker and the clean client

 

Note: – You can find a sample code for C# code in command pattern in ‘Command’ folder. 

 

Define UML?

Unified Modeling Language, a standard language for designing and documenting a system in an object-oriented manner. It has nine diagrams which can be used in design document to express design of software architecture.

Can you explain use case diagrams?

Use case diagram answers what system does from the user point of view. Use case answer ‘What will the system do?’. Use cases are mainly used in requirement document to depict clarity regarding a system. There are three important parts in a use case scenario, actor and use case. 

Scenario: – A scenario is a sequence of events which happen when a user interacts with the system.

Actor: – Actor is the who of the system, in other words the end user. 

Use Case: – Use case is task or the goal performed by the end user. Below figure ‘Use Case’ shows a simple scenario with ‘Actor’ and a ‘Use Case’. Scenario represents an accountant entering accounts data in the system. As use case’s represent action performed they are normally represented by strong verbs.

Actor’s are represented by simple stick man and use case by oval shape as shown in figure ‘Use Case’ below.

clip_image037

Figure: – Use Case

Can you explain primary and secondary actors?


Actors are further classified in to two types primary and secondary actors. Primary actors are the users who are the active participants and they initiate the user case, while secondary actors are those who only passively participate in the use case.


How does a simple use case look like?


Use case’s have two views of representation in any requirement document. One is the use case diagrams and the other is a detail step table about how the use case works. So it’s like a pair first an over view is shown using a use case diagram and then a table explaining the same in detail. Below is a simple ‘login’ use case shown diagrammatically and then a detail table with steps about how the use case is executed.

clip_image038

Figure: – Login Use Case

Use Case

Rel001

Use Case Name

Login

Description

This uses depicts the flow of how user will log-in into the chat application.

Primary Actor

Simple chat user.

Trigger

User types chat application on URL of the browser.

Pre-condition

NA

Assumption

No password is currently present for the system
Rooms will remain constant as explained in the assumption section of this document

Failed End conditions

Duplicate user name is not allowed in the chat application.

Action

User clicks on the log-in button.

Main Scenario

• User types chat application on URL of the browser which in turn opens the main page.
• In the main page of application user is popped up with ‘Enter user name’ option and various ‘rooms’ option drop down menu.
• User then types the name and selects one of the room from drop down menu and then clicks on the ‘Log-in’ button.
• Application then checks whether the user name is unique in the system if not then user is popped up with error message that “user already exist”.
• After entering the unique name the user is finally logged in the application.

Action

NA

Alternate Scenario

NA

Success Scenarios

1. Opens page of a selected room in that other user names and their messages can be seen.

Note and Open Issues

NA

 

Table: – Login use case table

Note: – You must be wondering why we have this pair why not just a use case table only. Use case diagrams are good to show relationship between use case and they also provide high over view. The table explanation of a use case talks details about the use case. So when a developer or a user is reading a requirement document, he can get an overview by looking at the diagram if he is interested he can read the use case tables for more details.

Can you explain ‘Extend’ and ‘Include’ in use cases?


‘Extend’ and ‘Include’ define relationships between use cases. Below figure ‘Extend and Include’ shows how these two fundamentals are implemented in a project. The below use case represents a system which is used to maintain customer. When a customer is added successfully it should send an email to the admin saying that a new customer is added. Only admin have rights to modify the customer. First lets define extend and include and then see how the same fits in this use case scenario.

Include: – Include relationship represents an invocation of one use case by the other. If you think from the coding perspective its like one function been called by the other function.

Extend: – This relationship signifies that the extending use case will work exactly like the base use case only that some new steps will inserted in the extended use case.

Below figure ‘Extend and Include’ shows that ‘add customer’ is same as the ‘add discounted customer’. The ‘Add discounted customer’ has an extra process, to define discount for the discounted customer which is not available for the simple customer. One of the requirements of the project was that when we add a customer, the system should send an email. So after the customer is added either through ‘Add simple customer’ use case or ‘Add discounted customer’ use case it should invoke ‘send a email’ use case. So we have defined the same with a simple dotted line with <<include>> as the relationship.

clip_image038[1]

Figure: – Extend and Include

Note: – One of the points to be noted in the diagram ‘Extend and Include’ is we have defined inheritance relationship between simple and admin user. This also helps us defining a technical road map regarding relationships between simple and admin user.

Can you explain class diagrams?


Class diagram

Class is basically a prototype which helps us create objects. Class defines the static structure of the project. A class represents family of an object. By using Class we can create uniform objects.

In the below figure you can see how the class diagram looks. Basically there are three important sections which are numbered as shown in the below. Let’s try to understand according to the numbering:-
• Class name:-This is the first section or top most section of the Class which represents the name of the Class (clsCustomer).
• Attributes:-This is the second section or the middle section of the class which represents the properties of the system.
• Methods: – This section carries operation or method to act on the attributes.

clip_image039

Figure: – Three sections of the class

Now in the next section we will have a look on Association relationship between these classes.


How do we represent private, public and protected in class diagrams?


In order to represent visibility for properties and methods in class diagram we need to place symbols next to each property and method as shown in figure ‘Private, Public and Protected’. ‘+’ indicates that it’s public properties/methods. ‘-‘indicates private properties which means it can not be accessed outside the class. ‘#’ indicate protected/friend properties. Protected properties can only be seen within the component and not outside the component.


clip_image040

Figure: – Private, public and protected

what does associations in a class diagram mean?

Associations in Class diagrams


A single Class cannot represent the whole module in a project so we need one or more classes to represent a module. For instance, a module named ‘customer detail’ cannot be completed by the customer class alone , to complete the whole module we need customer class, address class, phone class in short there is relationship between the classes. So by grouping and relating between the classes we create module and these are termed as Association. In order to associate them we need to draw the arrowed lines between the classes as shown in the below figure. 

In the figure ‘Order is paid by payments class’, we can see Order class and the Payment class and arrowed line showing relationship that the order class is paid using payment class in other words order class is going to be used by payment class to pay the order. The left to right marked arrow basically shows the flow that order class uses the payment class.
In case payment class using the order class then the marked arrow should be right to left showing the direction of the flow.

clip_image041

Figure:- Order is paid by Payments class

There are four signs showing the flow:-

clip_image042

Figure: – Direction signs in UML

Multiplicity

Multiplicity can be termed as classes having multiple associations or one class can be linked to instances of many other classes. If you look at the below figure the customer class is basically associated with the address class and also observes the notations (*, 0 and 1).If you look at the right hand side the (1….*) notation indicates that at least one or many instance of the address class can be present in the customer class. Now towards left hand side we have (0….*) notation indicating that address class can exist without or many customer class can link him.
In order to represent multiplicity of classes we have to show notations like (1….*), (0….*) as shown in below figure.

Note: ‘*’ means “many” where as ‘(0, 1)’ means “(zero or at least one)” respectively.

clip_image043

Figure: – Multiplicity in Classes


Can you explain aggregation and composition in class diagrams?


In this Association there are two types mainly Aggregation Association and Composition Association.

Aggregation Association signifies that the whole object can exist without the Aggregated 
Object. For example in the below figure we have three classes university class, department class and the Professor Class. The university cannot exist without department which means that university will be closed as the department is closed. In other words lifetime of the university depend on the lifetime of department.

In the same figure we have defined second Association between the department and the Professor. In this case, if the professor leaves the department still the department continues in other words department is not dependent on the professor this is called as Composition Association.

Note: – The filled diamond represents the aggregation and the empty diamond represents the composition. You can see the figure below for more details.

clip_image044


Figure: – Aggregation and composition in action


What are composite structure diagram and reflexive association in class diagrams?

Composite structure diagramWhen we try to show Aggregation and Composition in a complete project the diagram becomes very complicated so in order to keep it simple we can use Composite structure diagram. In the below figure we have shown two diagrams one is normal diagram other is Composite structure diagram and the simplicity can easily be identified. In the composite diagram the aggregated classes are self contained in the main class which makes it simpler to read.


clip_image045

Figure: – Composite Structure diagram

Reflexive associations
In many scenarios you need to show that two instances of the same class are associated with each other and this scenario is termed as Reflexive Association. For instance in the below figure shows Reflexive Association in the real project. Here you can see customer class has multiple address class and addresses can be a Head office, corporate office or Regional office. One of the address objects is Head office and we have linked the address object to show Reflexive Association relationship. This is the way we can read the diagram Regional address object is blocked by zero or one instance of Head office object.

clip_image046

Figure: – Reflexive association


Can you explain business entity and service class?


Business entity objects represent persistent information like tables of a database. Just making my point clearer they just represent data and do not have business validations as such. For instance below figure ‘Business entity and service’ shows a simple customer table which with three fields ‘Customer Code’,’ Customer Address’ and ‘Phone Number’. All these fields are properties in ‘ClsCustomer’ class. So ‘ClsCustomer’ class becomes the business entity class. The business entity class by itself can not do anything it’s just a place holder for data. In the same figure we have one more class ‘ClsServiceCustomer’. This class aggregates the business entity class and performs operations like ‘Add’,’ Next’ (Move to next record), ‘Prev’ (Move to previous record) and ‘GetItem’ (get a customer entity depending on condition).

With this approach we have separated the data from the behavior. The service represents the behavior while the business entity represents the persistent data.

clip_image047

Figure:-Business entity and service


Can you explain System entity and service class?


System entity class represents persistent information which is related to the system. For instance in the below figure ‘System entity and service class’ we have a system entity class which represents information about ‘loggedindate’ and ‘loggedintime’ of the system registry. System service class come in two flavors one is it acts like a wrapper in the system entity class to represent behavior for the persistent system entity data. In the figure you can see how the ‘ClsAudit’ system entity is wrapped by the ‘ClsAuditSytem’ class which is the system service class. ‘ClsAuditSystem’ adds ‘Audit’ and ‘GetAudit’ behavior to the ‘ClsAudit’ system entity class.

clip_image048

Figure: – System entity and service class


The other flavor of the system service class is to operate on non-persistent information. The first flavor operated on persistent information. For instance the below figure ‘Non-persistent information’ shows how the class ‘ClsPaymentService’ class operates on the payment gateway to Check is the card exists , Is the card valid and how much is the amount in the card ?. All these information are non-persistent. By separating the logic of non-persistent data in to a system service class we bring high reusability in the project.

clip_image049

Figure: – Non-persistent information


Note: – The above question can be asked in interview from the perspective of how you have separated the behavior from the data. The question will normally come twisted like ‘How did you separate the behavior from the data?’.


Can you explain generalization and specialization?


Generalization and specializationIn Generalization and Specialization we define the parent-child relationship between the classes. In many instance you will see some of the classes have same properties and operation these classes are called super class and later you can inherit from super class and make sub classes which have their own custom properties. In the below figure there are three classes to show Generalization and Specialization relationship. All phone types have phone number as a generalized property but depending upon landline or mobile you can have wired or simcard connectivity as specialized property. In this diagram the clsphone represent Generalization whereas clslandline and clsmobile represents specialization.

clip_image050

Figure: – Generalization and Specialization


How do we represent an abstract class and interface UML?


Interface is represented by <<type>> in the class diagram. Below figure ‘Interface in action’ shows we have defined an interface ‘IContext’. Note the ‘<<type>>’ represents an interface. If we want to show that the interface is used in a class we show the same with a line and a simple circle as shown in figure ‘Interface in Action’ below.

clip_image051

Figure: – Interface in action

Abstract classes are represented by ‘{abstract}’ as shown in figure ‘Abstract classes in action’.

clip_image052

Figure: – Abstract classes in action.

How do we achieve generalization and specialization?

By using inheritance.

Can you explain object diagrams in UML?


Class represents shows the static nature of the system. From the previous question you can easily judge that class diagrams shows the types and how they are linked. Classes come to live only when objects are created from them. Object diagram gives a pictorial representation of class diagram at any point of time. Below figure ‘Object diagram’ shows how a class looks in when actual objects are created. We have shown a simple student and course relationship in the object diagram. So a student can take multiple courses. The class diagram shows the same with the multiplicity relationship. We have also shown how the class diagram then looks when the objects are created using the object diagram. We represent object with Object Name: Class Name. For instance in the below figure we have shown ‘Shiv : ClsStudent’ i.e ‘Shiv’ is the object and ‘ClsStudent’ the class. As the objects are created we also need to show data of the properties, the same is represented by ‘PropertyName=Value’ i.e. ‘StudentName=Shiv’.

clip_image053

Figure: – Object diagrams


The diagram also states that ‘ClsStudent’ can apply for many courses. The same is represented in object diagram by showing two objects one of the ‘Computer’ and the other of ‘English’.

Note: – Object diagrams should only be drawn to represent complicated relationship between objects. It’s possible that it can also complicate your technical document as lot. So use it sparingly.

Can you explain sequence diagrams?


Sequence diagrams
Sequence diagram shows interaction between objects over a specific period time. Below figure ‘Sequence diagram’ shows how a sequence diagram looks like. In this sequence diagram we have four objects ‘Customer’,’Product’,’Stock’ and ‘Payment’. The message flow is shown vertically in waterfall manner i.e. it starts from the top and flows to the bottom. Dashed lines represent the duration for which the object will be live. Horizontal rectangles on the dashed lines represent activation of the object. Messages sent from a object is represented by dark arrow and dark arrow head. Return message are represented by dotted arrow. So the figure shows the following sequence of interaction between the four objects:-

• Customer object sends message to the product object to request if the product is available or not.
• Product object sends message to the stock object to see if the product exists in the stock.
• Stock object answers saying yes or No.
• Product object sends the message to the customer object.
• Customer object then sends a message to the payment object to pay money.
• Payment object then answers with a receipt to the customer object.

One of the points to be noted is product and stock object is not active when the payment activity occurs.


clip_image054

Figure: – Sequence diagram


Messages in sequence diagrams
There are five different kinds of messages which can be represented by sequence 
Synchronous and asynchronous messages:-
Synchronous messages are represented by a dark arrow head while asynchronous messages are shown by a thin arrow head as shown in figure ‘Synchronous and Asynchronous’.

clip_image055

Figure: – Synchronous and Asynchronous

Recursive message:-
We have scenarios where we need to represent function and subroutines which are called recursively. Recursive means the method calling himself. Recursive messages are represented by small rectangle inside a big rectangle with an arrow going from the big rectangle to the small rectangle as shown in figure ‘Recursive message’.

clip_image056

Figure: – Recursive message


Message iteration:-

Message iteration represents loops during sequences of activity. Below figure ‘message iteration’ shows how ‘order’ calls the ‘orderitem’ objects in a loop to get cost. To represent loop we need to write ‘For each <<object name>>’. In the below figure the object is the ‘orderitem’. Also note the for each is put in a box to emphasize that it’s a loop.

clip_image056[1]

Figure: – Message iteration

Message constraint:-
If we want to represent constraints it is put in a rectangle bracket as shown in figure ‘message constraint’. In the below figure ‘message constraint’ the ‘customer’ object can call ‘book tickets’ only if the age of the customer is greater than 10.

clip_image057

Figure: – Message constraint

Message branching:-
Below figure ‘message branching’ shows how ‘customer’ object have two branches one is when the customer calls save data and one when he cancels the data.

clip_image058

Figure: – Message branching


Doing Sequence diagram practically
Let’s take a small example to understand sequence diagram practically. Below is a simple voucher entry screen for accounts data entry. Following are the steps how the accountant will do data entry for the voucher:-

  • Accountant loads the voucher data entry screen. Voucher screen loads with debit account codes and credit account codes in the respective combo boxes.
  • Accountant will then fill in all details of the voucher like voucher description, date, debit account code, credit account code, description, and amount and then click ‘add voucher’ button.
  • Once ‘add voucher’ is clicked it will appear in the voucher screen below in a grid and the voucher entry screen will be cleared and waiting for new voucher to be added. During this step voucher is not added to database it’s only in the collection.
  • If there are more vouchers to be added the user again fills voucher and clicks ‘add voucher’.
  • Once all the vouchers are added he clicks ‘submit voucher’ which finally adds the group of vouchers to the database.

Below figure ‘Voucher data entry screen’ shows pictorially how the screen looks like.

clip_image059

Figure: – Voucher data entry screen


Figure ‘Voucher data entry sequence diagram’ shows how the sequence diagram looks like. Below diagram shows a full sequence diagram view of how the flow of the above screen will flow from the user interface to the data access layer. There are three main steps in the sequence diagram, let’s understand the same step by step.

Step 1:- The accountant loads the voucher data entry screen. You can see from the voucher data entry screen image we have two combo boxes debit and credit account codes which are loaded by the UI. So the UI calls the ‘Account Master’ to load the account code which in turn calls the data access layer to load the accounting codes.

Step 2:- In this step the accountant starts filling the voucher information. The important point to be noted in this step is that after a voucher is added there is a conditional statement which says do we want to add a new voucher. If the accountant wants to add new voucher he again repeats step 2 sequence in the sequence diagram. One point to be noted is the vouchers are not added to database they are added in to the voucher collection.

Step 3:- If there are no more vouchers the accountant clicks submit and finally adds the entire voucher in the database. We have used the loop of the sequence diagram to show how the whole voucher collection is added to the database.

clip_image060

Figure: – Voucher data entry sequence diagram

 

Digg This
Design Patterns

S.O.L.I.D. Design Principles.

Design Principle and Patterns
Design Principle and Patterns

S.O.L.I.D. Design principles suggest that the Individual pieces / building blocks of software should be of solid quality and highly accurate in design. For e.g. build blocks of rockets or Formula 1 car. The high quality software should follow principles of SOLID design principles by Martin R Fowler. The solid principles depend on the following principles

1. Agile Software Development

2. You Aren’t Gonna Need it

3. Keep it simple stupid

4. Vertical slice

5. Big Ball of mud.

Design Pattern is solution to common problems encountered at the software design level where reusability of code is very easy and flexible. Learning of Design Pattern and applying them in production environment needs lots of practice of developing software and experiencing the software programming. So many beginners overuse design patterns or use wrong design pattern.

The object oriented design implementation should be mostly composed of interfaces and abstract classes between two concrete implementations, this helps in loose coupling of dependency and software is less rigid for change in software requirements. Otherwise it will be similar to removing the windscreen when we need to change the steering wheel of the car.

Hence interfaces based programming is preferred over concrete classes based programming for a high quality development of the software. The five standard Design principles are as follows

  1. (S) The Single Responsibility Principle.
  2. (O) The Open/Closed Principle.
  3. (L) The Liskov Substitution Principle.
  4. (I) The Interface Segregation Principle
  5. (D) The Dependency-Inversion Principle.

I have briefly explained the 5 standard S.O.L.I.D. design principles below

The Single Responsibility Principle

A class should have only one reason to change. In other words Single Responsibility principle is defined as “THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.”

public interface Socket

{

public void Connect(string pno);

public void Disconnect();

public void SendData(char c);

public char RecvData ();

}

Single Responsibility Principle applied to Socket Interface to have separated responsibilities, One responsibility is Connection to the port and Disconnection to the port. Second responsibility is communication of Data with the server port.




The Open/Closed Principle (OCP)

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

Modules that conform to the open-closed principle have two primary attributes.

They are “Open For Extension”.

They are “Closed for Modification”.

In most of the design scenarios the Open Closed principle is at the core of object oriented design. Adherence to this principle is what yields the greatest benefits of object oriented methodology; i.e. reusability and maintainability.

Here the Render Interface is both open and closed interface, as Render Implementation uses different implementation of render depending on the device on which page is being displayed. So a Render instance uses RenderPage Interface which is closed w. r. t. adding new methods or changing the render methods but it is open to using the derivative of Display device instances.

Extension methods and static class are examples of violations of SOLID principles. All third party code should be encapsulated and isolated from developer code, so third party code can be later replaced by other pieces of code as new versions of code are generated. Method parameters should be interface type not specific class type.

There are two types of Open-Closed Principle Implementation, namely

Meyers open closed principle: Here developer is allowed to modify the class design only to fix the bugs and developers are prohibited from changing the behavior or state of the class.

Polymorphic open closed principle: Apart from maintaining the behavior and state of the class developer should make all the variables private and avoid the Global variables.

The Liskov Substitution Principle

Subtypes must be substitutable for their base types when inject into the functions.

In other words we can define Liskov Substitution Principle as follows:

FUNCTIONS THAT USE POINTERS OR REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.


The Liskov Substitution Principle is one of the prime enablers of OCP. The substitutability of subtypes allows a module, expressed in terms of a base type, to be extensible without modification. That substitutability must be something that developers can depend on implicitly. Thus, the contract of the base type has to be well and prominently understood, if not explicitly enforced, by the code.

The term IS-A is too broad to act as a definition of a subtype. The true definition of a subtype is substitutable, where substitutability is defined by either an explicit or implicit contract. Functions that use pointers and reference base classes as parameters, they are substituted by subclass instances without knowledge of the functions that will process them. This substitution is applied through Polymorphism usually by developer who is following Test Driven Design methodologies; One care must be that code implementing Liskov Substitution Principle should avoid Run Time Type Information.

E.g.1. Inheritance of Line and LineSegment is the case of LSP.

In the case of the Line and LineSegment, a simple solution illustrates an important tool of OOD. If we have access to both the Line and LineSegment classes, we can factor the common elements of both into an abstract base class LinearObject.

E.g.2. Peel method for Oranges is different than Peel method for apples. But Peel method is common and can be used as an interface method.

E.g.3. Similarly width method is common for Square and Rectangle.

The Dependency-Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions.

In the example of remote controlling the Television, the internal working of either remote or TV is not known to each other but each interact.


Remote instance will interact with the Universal TV interface and TV instance interacts with Universal Remote interface. So both remote models and TV models can be changed so there is dependency between them.

Consider the software that might control the regulator of a furnace. The software can read the current temperature from an I/O channel and instruct the furnace to turn on or off by sending commands to a different I/O channel. The structure of the algorithm might look something like

const byte TERMOMETER = 0x86;  const byte FURNACE = 0x87;  const byte ENGAGE = 1;  const byte DISENGAGE = 0;  void Regulate(double minTemp, double maxTemp)  {   for(;;)   {   while (in(THERMOMETER) > minTemp)   wait(1);   out(FURNACE,ENGAGE);   while (in(THERMOMETER) < maxTemp)   wait(1);   out(FURNACE,DISENGAGE);   }  } 

void Regulate(Thermometer t, Heater h,   double minTemp, double maxTemp)  {   for(;;)   {   while (t.Read() > minTemp)   wait(1);   h.Engage();   while (t.Read() < maxTemp)   wait(1);   h.Disengage();   }  } 

This shows that the Regulate function takes two arguments that are both interfaces. The Thermometer interface can be read, and the Heater interface can be engaged and disengaged. This is all the Regulate algorithm needs. Now it can be written as shown above.

This has inverted the dependencies such that the high-level regulation policy does not depend on any of the specific details of the thermometer or the furnace. The algorithm is nicely reusable. Passing a reference of Interface and instantiation happens inside a static class.

The Interface Segregation Principle

Clients should not be forced to depend on methods they do not use. In other words Integration Segregation Principle is defined as follows:

CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACESTHAT THEY DO NOT USE.

For e.g.

Public interface UserLogin {

Public string Username;

Public string Password

Public string role;

Public string authorization;

}

So for user to login you would require only a username and password and nothing more. So the above interface needs to be broken into related interfaces and then used as two instances for different responsibilities

Public interface userLogin {

Public string getusername();

Public string getpassword();

}

Public interface Authorization {

Public string role;

Public string authorization;

Public string group;

}

Public class user implements userLogin {

String Username {get; set ;}

String Password {get; set ;}

}

Public class Groups implements Authorization, UserLogin {

Public Username {get; set; }

Public string role {get; set; }

Public string authorization {get; set;}

Public string group {get; set;}

}


Fat classes cause bizarre and harmful couplings between their clients. When one client forces a change on the fat class, all the other clients are affected. Thus, clients should have to depend only on methods that they call. This can be achieved by breaking the interface of the fat class into many client-specific interfaces. Each client-specific interface declares only those functions that its particular client or client group invoke. This breaks the dependence of the clients on methods that they don’t invoke and allows the clients to be independent of one another.

The ISP acknowledges that objects require non-cohesive interfaces; but it is advised that user of these objects should not know about them as a single class. Instead, users of these objects should know about abstract base classes that have cohesive interfaces; and are multiply inherited into the concrete class that describes the non-cohesive object.

This chapter has introduced the concept of design principle used in object oriented design and architecture of application. and I have try to explain very briefly the design principle applied to the structure of classes and interfaces helps in keeping the software application flexible, robust, reusable, and developable.

In my next series of blogs I would try to explain briefly the twenty three official standard design patterns used in Object oriented design. Also provide me the comments feedback of this blog so that I can improve my future articles.

Design Patterns

Design Pattern Part – 1

Design patterns are documented tried and tested solutions for recurring software problems in a given design context. So basically you have a problem to be solved and the proposed solution in the form of design pattern for the same problem. Design patterns existed in some or other form right from the inception stage of software development. Let’s say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns which are recurring solutions to common problems of design, they provide practical and concrete solutions to real world problems. Design Pattern are very context specific, and they are ”Best-fits” for the given set of concerns/trade-offs. For Domain experts and experienced professional they are perfect solution and are as easy to apply as “Old hat”. Design patterns is a literary form for documenting best practices and a shared vocabulary for problem-solving discussions.

Design Pattern are an very powerful and effective means of reusing, collaborating, and developing upon existing experience/expertise of the seasoned professional.

Christopher Alexander says, “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice”.

Design pattern is designed not to reinvent the wheel using object oriented design but to provide general solution to the common occurring software problems. In the lifecycle of software development it is normal for some requirements to change, and dependent interface also change. This leads to introduction of design pattern to Interface between old object and another object with modified interface.

Design patterns are helpful to object oriented programmer for e.g. Asp.NET pages contains lot of internal navigation logic and are connected to other pages. Routing logic between pages is one of the common logic is used by the application. This distribution of routing code between pages is actually an overhead to the application; it can fine tuned by abstracting and isolating the routing logic and substituting it with a design pattern in the application architecture so that it can be reused wherever required.

System requirements for the design pattern is very less as Design Pattern is a concept that is common to all languages and independent of all programming languages. There are 23 official standard Design patterns

There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

Abstract Factory:- Creates an instance of several families of classes
Builder: – Separates object construction from its representation
Factory Method:- Creates an instance of several derived classes
Prototype:- A fully initialized instance to be copied or cloned
Singleton:- A class in which only a single instance can exist

Structural Patterns

Adapter:-Match interfaces of different classes.
Bridge:-Separates an object’s abstraction from its implementation.
Composite:-A tree structure of simple and composite objects.
Decorator:-Add responsibilities to objects dynamically.
Façade:-A single class that represents an entire subsystem.
Flyweight:-A fine-grained instance used for efficient sharing.
Proxy:-An object representing another object.

Behavioral Patterns

Mediator:- Defines simplified communication between classes.
Memento:-Capture and restore an object’s internal state.
Interpreter:- A way to include language elements in a program.
Iterator:-Sequentially access the elements of a collection.
Chain of Responsibility: – A way of passing a request between a chain of objects.
Command:-Encapsulate a command request as an object.
State:-Alter an object’s behavior when its state changes.
Strategy:-Encapsulates an algorithm inside a class.
Observer: – A way of notifying change to a number of classes.
Template Method:- Defer the exact steps of an algorithm to a subclass.
Visitor:- Defines a new operation to a class without change.

Relationships between Design Patterns
Relationships between Design Patterns

This is the first of the series of blogs about design pattern I would be publishing. I would tried to explain them concisely and to the point to keep them very easy for reading and understand them. so that developers can use them effectively in developing of effective robust software.

Design Patterns

Design Patterns Part – 2

Abstract Factory

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client. Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class.

In the Implementation phase,Authors discuss about the idea of defining extensible factories. An Abstract Factory is composed of Factory Methods, and each Factory Method has only one signature. Abstract Factory class provides an interface for creating families of related or dependent objects without specifying their concrete classes. We would have to specify different concrete factory subclasses in order to create an object in multiple ways.

Figure: – Abstract factory unifies related factory patterns

Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (Abstract Factory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface.

Figure: – Implementation of abstract factory

For instance in figure ‘Implementation of abstract factory’ both the concrete classes ‘product1’ and ‘product2’ inherits from one interface i.e. ‘common’. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit.

Now let’s have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘jpFactoryButton’ and ‘jpFactoryText’. Both these classes inherit from common interface ‘InterfaceRender’.

Figure: – Example for abstract factory

Both the factories ‘jpFactoryButton’ and ‘jpFactoryText’ inherits from the common factory ‘jpAbstractFactory’. Figure ‘Example for AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( jpAbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘jpAbstractFactory’ class provides a common interface for both factories ‘jpFactoryButton’ and ‘jpFactoryText’.

We will just run through the sample code for abstract factory. Below code snippet ‘Abstract factory and factory code snippet’ shows how the factory pattern classes inherit from abstract factory.

Figure: – Abstract factory and factory code snippet

Figure: – Common interface for concrete classes

Figure ‘Common Interface for concrete classes’ how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes.


The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘jpAbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.

Figure: – Client, interface and abstract factory

The Abstract Factory is applied when Pattern Factory of factories are to be dynamically customizable. Abstract class of factory are implemented when different types of factories are required. e.g. factory class to create controls for individual OS.

Abstract Factory entities should  create objects at the time of creation of objects not at the time of factory creation or not during the execution of factory constructor. Sample code shows how factories are created dynamically not at abstract factory instantiation time.

Public abstract class connectionFactory {

createConnection()

}

SecureFactory extends connectionFactory {

connectionFactory create(String type) {

if (type.equals(‘Oracle’)

return new OracleConnection();

if(type.equals(‘SQLServer’))

return new SQLServer();

else return new MySQL();

}

}

The next blog in the series I will be explaining about Adapter Design Pattern. Please send me the feedback on this blog so that I can improve the future blog contents.

Digg This
Design Patterns

Design Pattern Part–3.

Adapter Pattern

Two different objects have unfriendly interfaces and then we introduce adapter to communicate and interact between them without any changes to the existing interface of the two objects.

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

An Adapter could indeed have the same interface as the object which it adapts.  In that case, the adapter would add some extra functionality before making the call to the adaptee object.  So, we would not want the exact same interface.  Also, the adapter’s implementation would be different from that of the proxy.

Adapter pattern is like developing mobile software with lot of adapter to run the same software on different mobile brands. Every developer should write documentation about what that adapter method does it do? How to install and configure adapter?

There are four roles within the adapter pattern: client, adapter, adaptee, and the target interface.

The client is a user object that expects a specific interface (or type). We could for the purposes of simplicity state that the client is callee on a type that implements a specific interface. As another example the client may need to concert with a type later on that has implemented a specific interface.

The Adapter wraps the adaptee up and implements the interface the client expects. The adapter sometimes delegates its work to the adaptee.

An adaptee is the type that we want to use with the new code but we can’t because it doesn’t adhere to expected behavior that the client expects.

Finally the target interface is the name given to the interface that the client expects.

Let us illustrate the above mentioned  terminology with the help of a simple example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns.Adapter {
//Interface
public abstract class Connector     {
public abstract void ReadData();
}
//Adaptee
public class DatabaseUtil
{
      public void QueryForUpdates()
      {
          Console.WriteLine("Updates queried from DB.");
     }
}
//Adapter
public class DatabaseConnector : Connector
          {
          public override void ReadData()
         {
         var dbUtil = new DatabaseUtil();
         dbUtil.QueryForChanges();
         }
     }
//Client
     public class TradingDataImporter
     {
         public void ImportData(Connector connector)
         {
             connector.ReadData();
         }
     }
 }
UML Diagram of Adapter Design Pattern
UML Diagram of Adapter Design Pattern

To summarize, we have the following options when matching adapter and adaptee interfaces:

Adapter interface and adaptee interface have same signature
Many examples of the Adapter pattern operate at this level and are not illustrative or helpful in explaining its real power. Beware of them.
Adapter interface has fewer parameters than adaptee interface
The adapter calls the adaptee with some dummy input.
Adapter interface has more parameters than adaptee interface
The adapter adds the missing functionality, making it half an adapter and half a component in its own right.
Adapter interface has other types than adaptee interface
The adapter performs some type conversion (casting).

You should use Adapter pattern when you need to implement

  • A domain-specific interface.
  • A class to connect to with a mismatching interface.
  • a reusable class to cooperate with yet-to-be-built classes.
  • the modification of names of methods as called and as implemented.
  • different sets of methods for different purposes.

In the Next blog I will be explaining about the Bridge pattern. By that time read the blog and send me the feedback.

Digg This
Design Patterns

Design Pattern Part – 4

UML Diagram of Bridge Design Pattern
UML Diagram of Bridge Design Pattern

Bridge Pattern

The bridge pattern is a design pattern used in software engineering which is meant to decouple an abstraction from its implementation so that the two can vary independently”.[1] The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

 

A bridge is a structural pattern that influences the creation of a class hierarchy by decoupling an abstraction from the implementation. In a bridge however, the abstraction and its implementation can vary independently, and it hides the implementation details from the client.

A simple Illustration of Bridge Design Pattern is ‘Remote has a Car object relationship’. This “has-a” relationship bridge is implemented as Bridge Pattern. Two different parts of the code that is changing except the relationship between them then it is bridge between two changing objects.

Inheritance tree of Car with each node representing the different make of Car, is an example of Bridge pattern.

The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction.

When a class varies often, the features of object-oriented programming become very useful because changes to a program‘s code can be made easily with minimal prior knowledge about the program with the help of bridge pattern.

The bridge pattern can also be thought of as two layers of abstraction.

The following is the sample code Bridge pattern.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DesignPatterns.Bridge {

public abstract class DataObject

{

public abstract void Register();

public abstract DataObject Copy();

public abstract void Delete();

}

public abstract class Repository

{

public abstract void AddObject(DataObject dataObject);

public abstract void CopyObject(DataObject dataObject);

public abstract void RemoveObject(DataObject dataObject);

public void SaveChanges()

{

Console.WriteLine(“Changes were saved”);

}

}

public class ClientDataObject : DataObject

{

public override void Register()

{

Console.WriteLine(“ClientDataObject was registered”);

}

public override DataObject Copy()

{

Console.WriteLine(“ClientDataObject was copied”);

return new ClientDataObject();

}

public override void Delete()

{

Console.WriteLine(“ClientDataObject was deleted”);

}

}

public class ProductDataObject : DataObject

{

public override void Register()

{

Console.WriteLine(“ProductDataObject was registered”);

}

public override DataObject Copy()

{

Console.WriteLine(“ProductDataObject was copied”);

return new ProductDataObject();

}

public override void Delete()

{

Console.WriteLine(“ProductDataObject was deleted”);

}

}

public class ProductRepository : Repository

{

public override void AddObject(DataObject dataObject)

{

// Do repository specific work

dataObject.Register();

}

public override void CopyObject(DataObject dataObject)

{

// Do repository specific work

dataObject.Copy();

}

public override void RemoveObject(DataObject dataObject)

{

// Do repository specific work

dataObject.Delete();

}

}

}

You should use Bridge pattern whenever you Identify that there are operations that do not always need to be implemented in the same way.

You should implement Bridge pattern when following are the requirements of your application:

• Completely hide implementations from clients.

• Avoid binding an implementation to an abstraction directly.

• Change an implementation without even recompiling an abstraction.

• Combine different parts of a system at runtime.

The next blog I will be explaining about the Builder Pattern.

Digg This
Design Patterns

Design Pattern Part – 5.

Builder Design Pattern falls under the type of creational pattern category.

Just like a house construction follows an ordered process of construction namely

1. Foundation

2. Wall Door & window construction.

3. Roof construction.

Similarly a build pattern follows a ordered process to construct objects. E.g. DB normalization before domain objects and business layer is constructed.

 Figure: – Builder concept

The Builder Design Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

The Builder pattern requires that you define an interface, which will be used by clients to build complex objects in bits and pieces. Builder pattern is useful when the construction of the object is very complex.

The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.

Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘WORD’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display. The construction process is same for both the types of reports but they result in different representations.

We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

• Builder: – Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
• Director: – Director takes those individual processes from the builder and defines the sequence to build the product.
• Product: – Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportWORD’ builder will be built.

Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to WORD or PDF), set report headers, set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘WORD’ (ReportWord). These two custom builders define their own process according to the report type.

Figure: – Builder classes in actual code

Now let’s understand how director will work. Class ‘jpDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or WORD.

Figure: – Director in action

The third component in the builder is the product which is nothing but the report class in this case.

Figure: – The report class

Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

Figure: – Client, builder, director and product 

I hope you enjoyed reading this blog from Design Pattern Series, in my next blog I will be discussing about “Chain of Responsibility” Design Pattern till then happy reading.