Saturday 30 November 2013

Simple Factory, Factory Method & Abstract Factory Pattern

World without factory pattern

All the object creation logic creeps in the Client Code and it is usually in the form of IF-ELSE or SWITCH statement that return the Family of Objects based on some input.

Adding new classes make us modify the switch statement.

This switch statement may become monolithic when number of classes grow.

Client code should programmed against the relatively stable interfaces, those prevent client code to 
be break in case of change and also this these interfaces can be mocked to unit test our code.

This object creation logic should be segregated and put in the separate class. 

Factory Pattern
This pattern is used when we have CASE or SWITCH statement creating the family of objects. Adding new objects means updating the switch statements. This hampers the Hot Deployment. That means we simply add compiled classes to the running application to augment its functionality. This does not require us to change the already coded classes. this is the very soul of Open/Close Software Design Principle. Software should be build and feel that is made of Lego Blocks. Everything seems loosely coupled but still attached. Everything seems modular but still integrated. 




Simple Factory Variation
This pattern variation is used when we have Single Family of objects, and all family of classes extend an Interface. Along with this we have one Factory Class that returns the instance of concrete class based on configurations. 

Client Code  ==>>  (Interface + ClassA, Class B, Class C + Concrete FactoryClass)



Factory Method Variation
This pattern variation is the same case as above, but the client code does not depend upon the concrete Factory class, but we introduce the interface for the Factory classes as well. For Single Family of objects, this seems overhead. For most Single Family of objects the Simple Factory will work fine. It makes sense when we have following situation in the context of testing.

Basic theme is that client code should depend upon Interface rather than the Concrete Class.

There is One-To-One relationship between Factory and Product Class it can create. Each factory is responsible to create only One type of object.

Client Code  ==>>  (Interface + ClassA, Class B, Class C + Concrete FactoryClass)
Client Code  ==>>  (Interface + MockClassA, MockClassB, MockClassC + TestFactoryClass)

In this situation the Interface for factory cannot be avoided.



Abstract Factory Variation
This pattern variation is used when we have Multiple Families of objects. We have
1. Interface for the Factory Classes
2. Interface that all Product Classes will implement.
3. Factory Interface will have Multiple Create methods for different type of Products it can create.

There is One-To-Many relationship between Factory and Product Class it can create. Each factory is responsible to create Many type of objects.




Saturday 23 November 2013

OO Design Patterns Catalog

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 of which only a single instance can exist

  Structural Patterns
  Adapter  Match interfaces of different classes
  Bridge  Separates an object’s interface from its implementation
  Composite  A tree structure of simple and composite objects
  Decorator  Add responsibilities to objects dynamically
  Facade  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
  Chain of Resp.  A way of passing a request between a chain of objects
  Command  Encapsulate a command request as an object
  Interpreter  A way to include language elements in a program
  Iterator  Sequentially access the elements of a collection
  Mediator  Defines simplified communication between classes
  Memento  Capture and restore an object's internal state
  Observer  A way of notifying change to a number of classes
  State  Alter an object's behavior when its state changes
  Strategy  Encapsulates an algorithm inside a class
  Template Method  Defer the exact steps of an algorithm to a subclass
  Visitor  Defines a new operation to a class without change

Thursday 7 November 2013

Why Software design and software architecture matters?

Why Software design and software architecture matters?


1. Maintainability, changeability, evolution and modifiablility, agility, software process, iterative and incremental development, support IID/Agile software development.


2. Extensibility and growth-path as the result of Modularity, support IID/Agile software development.


3. Testability, Unit testing, UI based testing, Functional testing, Automated testing, TDD, support IID/Agile software development.


4. Re usability of Software Design (attacks the essential complexity of software development), support IID/Agile software development.


5. Separation of concerns, Loose Coupling and High Cohesion, Modularity, support IID/Agile software development.


6. Crisp clear abstractions or simplicity, raising the level of abstraction ( deals with the accidental complexity of software development), visibility or vocabulary  for reasoning about the software design


7. Balanced distribution of responsibilities among the classes or objects


These seven factors are the main focus points of the Design Principles and Design Patterns. Software should be really soft to change, extend, reuse and then test, this the whole point of OO Design Principles and Patterns

Dynamic wiring of Events and Events Handlers

Basic concept of Events & Events handlers is that, when some things special happens to an object,
others related objects are to be notified about that something special that is happened to first object.
By analyzing the WHAT has happened to first object, the second object execute some code that can ye any thing in Object oriented Programming. Usually we notify when

1. Some property of Object is changed
2. Some functionality is executed.
3. Some special condition occurs related to Object State.

The Event Subscriber object must be the alive and resident in the memory.

With Observer/Publish Subscriber/Mediator/Event Aggregator design patterns, we usually assume the static wiring of events and events handlers at the compile time.

But this complex wiring of events and event handlers can be added, modified and removed at the run time.

 It is completely dynamic and even it can be injected as the dependency that describes how the events and event handlers can be wired at the application start up. According to application logic new objects can be created, they can hooked up to events of others objects; other objects can subscribe the events of newly created objects and so on. This is dynamic and can be changed according to the business logic or the domain logic of the application.

Design Patterns and Thick Client Applications

I have feeling that these design patterns make more sense in case thick client application where we have big object-graph in the memory all the time, the static and dynamic complex wiring of objects really yield something very immensely interesting and elegantly awesome.

It is very hard to have such user specific object graph on Server for the a particular user. It do not
make sense, on the Web, we have request response model.

But Objects can make their magic work on the Server in case of Session Object stored on the Server.
But these Session or State Object are light weight. The are not the complex object graph of objects.

But this can be done in case of RIA applications where moderate size client, like the SWF
resides on the Client Machine.

Midiator vs Observer or Publish Subscriber Pattern vs Event Aggregator Pattern

There is quite overlap in the Mediator and Observer/Publish-Subscriber pattern. Mediator pattern provide a way to decouple the Subject and Observers and move the communication logic to the middle component. This makes the Subjects and Observers decouple and reusable and allow them to grow independently without bothering each other. Otherwise, components will be coupled to each other and they will be less reusable and maintenance can be problematic.
Event based GUI programming used both design patterns (Mediator and Observer/Publish-Subscriber pattern). Usually GUI form is a mediator and the different components on it are the Subjects and Observers. One component can be both Subject and Observer at the same time. It can send events and it can subscribe event. In case of GUI, the Form component subscribes the different events of the components on the form and different event handlers on the form do the communication and state changing logic in its events. All the communication, co-ordination, state changing, data binding, data fetch, data validation, event subscription is done on the form or mediator.

The same Mediator and Observer/Publish-Subscriber pattern can be implemented on the complex business logic object. We can simulate this on the complex business logic objects in the memory that do the different things in the back ground like logging, data base persistence, emails, service invocation, database backup, data uploading, data downloading and many other those have less to do with the GUI.

Event aggregator design pattern is a specialized case of Observer + Mediator design pattern. In this pattern, the Mediator also handles the event-wiring and registration and un-registration logic of the events. It further decouples the Subjects and Observers and really makes them reusable and maintainable. 

Monday 4 November 2013

State Design Pattern (Behavioral Pattern)

State Pattern

In nutshell, State Pattern allow us to have a configurable behavior of the object by composition. This behavior is configured when some state member of object is changed. Usually this behavior is provided when object change its state and some property setter is called.

If the method of the class are partitioned on the basis of STATE of an instance variable, then State Design Pattern is the answer. All the switches in the methods that change the method behaviour based on the current state, is a code smell that should be re-factored to the State Pattern.

For all different states, we define separate classes those comply an Interface

Composition + Delegate based solution is applied to handle different state based methods of a class

When the state is changed, and the State Setter Method is called, the Composition-Delegate based
instance variable is also changed.Now the setter will instantiate the Composition-Delegation based 
instance variable. This will result in State Setter having IF-Else/Switch for the initialising the 
instance variable. This can be solved by the Simple Factory variation of Factory Design Pattern.


State Pattern + Factory Pattern are used in combination 
Different State based classes are the Family of Classes those are created by factory design pattern 
while implementing the State Pattern.

Decorator Pattern

1.       If we have object composition like the stack or like the onion, and functionality is hieratical, then decorator pattern is used. For example, Form composed of may buttons, Data grid compose of many components.

Strategy Pattern

Factory and Strategy Pattern
In nutshell, Strategy Pattern allow us to have a configurable behavior of the object by composition. We can change this behavior of the object at deployment time or at runtime. Usually this behavior is provided when the object is created.
Factory is very handy design pattern, the whole idea of dependency injection is related to it. Usually dependencies are the variable part of our applications we want to defer it to deployment time or to execution time. At deployment time these dependencies are put in the configuration files and some Factory method mechanism is exploited by the DI Container to load them. Sometimes dependencies are injected at the runtime by the choices made by user when the software is executed. This may be selecting from the Drop Down what Sorting Strategy we can use for the set of input arrays.
LINQ and Strategy Pattern

Lambda Expressions or Queries or LINQ operators are also the Strategies those specify the SQL Operations at higher level of abstraction. We pass the data set and operations that we want to perform on it and we get the results back.

Usually the Class has Family of behaviors within itself. All behaviors are defined as different methods within class, and another method has big switch statement, and some flag in this switch statement decides, what behaviors will be provided by the class. 

An object can have Family Of Behaviors, but only one at one time. This behavior can be injected while creating that object or it can be configured at run time.

For example, an object encapsulate an Array Sorting Algorithms, and it can be configured at object creation time or it can be configured at run time.

At run time, behavior can be added to an object, by Strategy Pattern. It is a composition based solution, delegate behavior to dynamically added objects. We have A, B and C type of behaviors and further we have A1, A2 and A3 type of behaviors. In the same type B1, B2 and B3. 

Both State and Strategy pattern provide composition and delegation based solution to provide plug-able behavior for the object. But do not confuse this with State Pattern, in which object changes its behavior depending upon its state. In Strategy pattern, some external stimulus cause the object to have any one of the available family of behaviors. This external behavior can be specified at object creation time by placing them in configuration files, in database tables, by GUI in which case it is specified by the User, by another object that is responsible to create the object, by events and delegates, by dependency injection. But in case of State Pattern, the internal state change cause the new behavior to be plugged in. So the setters methods of class plug-in the new behavior for the class. 

We define an Interface for the Family of Behaviors. For, all different behaviors we define class that extends interface. The behaviors is passed as object to the Subject Class at the time of object creation or set by setters at runtime, The behaviors class can also be specified in the configuration files or they are provided by the User at runtime by the GUI Control. 

Template method pattern

1.       If the steps and the control flow of the WORKFLOW or ALGORITHM are FIXED and DO NOT CHANGE and the underlying details of the WORKFLOW or ALGORITHM vary and implemented by the developer then this functionality is implemented by Template Method Pattern.

Repository and Unit of Work Design Pattern

1.       Repository pattern expose the underlying data source as the in-memory collection and relieves the business logic layer form the underlying details of data source. Along with Unit of work design pattern relieves business logic layer and data from the headache of Transactions, Locking, and Conflicting Updates. All things are managed behind the scenes. Different ORM solutions or Data access Libraries like Linq2Sql, N-Hibernate, ADO.NET Entity Framework, ADO.NET, and Dynamic Data provide the Unit of work mechanism. But using these Unit of work in the business logic make our BLL data source dependent. Do implement the Logical Transactions we need to implement the Unit of Work on the top of Unit of Work provided by the ORM solution.

Unit testing mocking layer, Layered architectural pattern and Interfaces

1.       Ideally, the upper layer should depend upon the interface of lower layer, so that the upper layer can be unit tested by mocking the lower layer and provide the dummy functionality. If it is not, then we are forced to provide the PRODUCTION lower layer. If by any means this PRODUCTION lower layer is not available, or it is not possible to provide that, then we can test the upper layers. For example Payment gateways cannot be test in real. Credit card transactions cannot be tested in real. We may not be provided by a SMTP server while testing. Enterprise application has many dependencies on the outer world. While in the test we are not available with those dependencies or it is not feasible to do so. Cause update in the external Database or any other department but we do not have that Database for our application. External service is down or it is under development. Or external service is secures and it could only be used in PRODUCTION scenario. Calling service is not feasible in testing environment. Enterprise service bus cannot be used in Testing Environment and we are not available with Testing ESB. 

Provider vs Adapter Design Pattern

1.       Provider pattern and Adapter pattern are same, as they adapt the different data sources APIs to be used uniformly for .NET applications. .NET provider for SQL server adapts the SQL server APIs to be used uniformly across the .NET applications. .NET provider for Oracle adapts the Oracle APIs to use uniformly for .NET application. Adapter seems to be a small concept like a class. But in case of provider, this adapter grows to full blown API or Library, therefore these are called Providers. They provide access to the particular data source.

1.       CASE 1: (Client application has upper hand) (We are coding the client application and we want to reuse the existing legacy or incompatible API or Library) Adapter or wrapper is a class that wraps a legacy or incompatible API or Library and exposes that API or Library in an interface that the client code expects. Adapt the API or Library in a way so that it could be used by client. CASE 2: (API or Library application has upper hand) (We are coding the API or Library and we want it to be reused by all future expected clients) Adapter or wrapper interface is exposed by the API or Library; all interested clients implement that interface exposed in order to use that API or Library.

Passing objects as the parameters: passing data and behavior with event handling stuff

Normally when declare a class type data member in class or when we pass parameters to a method, we assume only one possible use case of this. That is this class need some DATA it is managed like this i.e. by parameter or by declaring it as the data member. We completely ignore the BEHAVIORAL part of the object. These object are not only the DATA CONTAINERS but they carry BEHAVIOR as well. For example we can do following things with an object other then DATA

1. Receiver object can call the methods of passed object.

2. Receiver object can send method of passed object as parameter it own method or to any other object

3. Receiver object itself can subscribe one or more events of passed object and attach its event handlers to them.

4. Receiver object can make other objects to subscribe one or more events of passed and attach their event handlers them.

5. Receiver object can raise one or more events of passed object and cause functionality to be executed in all its subscribers.

6. Passed object can  consume receiver’s method as parameter to its own method or it can be passed to any other object’s method as parameter

7. Passed object can subscribe one or more events of the receiver and attach its events handlers to it.

8. There can be a complete Zig-Zag between the Passed object and Receiver object. Receiver already has the reference of the Passed object, Passed object know about the Receiver by using the THIS keyword.

9. There is always a Main program or Start up module that composes the object graph properly and wires the events among the object and inject the dependencies. The resultant object graph is the SOFTWARE that exhibit the required functionality or behavior. This object graph can be expanded by the lazy load technique. The entire object graph should not eager loaded at the start up. It makes the bulky application that takes too many spaces in memory. Also not needed functionality should be eliminated from the object graph.

10. If an object implements 5 interfaces, then it means that object has 5 different VIEWS or WINDOWS by which its data and functionality can be exposed. Or we can say, object has 5 faces or face-lets by which it can expose its functionality. This is the one use of interface. Implementing the interface means, object can be seen like that. We can hide the show the particular sub set of data and functionality by using a particular Interface.