Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Tuesday, November 17, 2015

Anemic data models (ADM) VS Rich Data Models (RDM) in C#

What are anemic data models?
What are Rich Data models ?
Anemic data model VS Technical concerns
3 big Complaints about Anemic model
Anemic model in disguise of IOC and DI
Conclusion
Further references and reading

What are anemic data models?

Anemic in English means plain so Anemic Models means plain Models.

Plain models are classes without business logic / behaviors. For example below is a simple “Customer” model which just has the data (properties) but it does not have business logic (behavior).

class Customer
    {
        private string _CustomerName;

        public string CustomerName
        {
            get { return _CustomerName; }
            set { _CustomerName = value; }
        }
        private string _CustomerCode;

        public string CustomerCode
        {
            get { return _CustomerCode; }
            set { _CustomerCode = value; }
        }

    }

Now in real world plain models are of no use without business logic unless you are creating DTO ( data transfer objects) which are meant for different purpose. Some developers feel comfortable in pushing these actions and methods in a separate classes which are named with different vocabularies like service, façade , manager , utility etc. These plain models are then passed to these classes who run the behavior over them.

For example below is a simple service class which validates the “Customer” object and decides if the object valid or not. Putting in simple words Anemic model has behavior in separate service / utility / manager classes.

class CustomerValidationService
    {
        public bool Validate(Customer obj)
        {
            if (obj.CustomerCode.Length == 0)
            {
  return false;
            }
            if (obj.CustomerName.Length == 0)
            {
                return false;
            }
                return true;
        }
    }

What are Rich Data models ?

Rich data models have both data and behavior in the same class. Below is the RDM for the previously defined ADM. You can see the data ( CustomerCode and CustomerName) and behavior (Validate) both are part of the same model.

class Customer
    {
        private string _CustomerName;

        public string CustomerName
        {
            get { return _CustomerName; }
            set { _CustomerName = value; }
        }
        private string _CustomerCode;

        public string CustomerCode
        {
            get { return _CustomerCode; }
            set { _CustomerCode = value; }
        }

        public bool Validate()
        {
                if (CustomerCode.Length == 0)
                {
                    return false;
                }
                if (CustomerName.Length == 0)
                {
                    return false;
                }
                return true;
          
            
        }
        
    }

Anemic data model VS Technical concerns

Lot of developers confuse Technical cross cutting concerns with Anemic model. In Anemic model the behaviors in the service class is the behavior of the real world model.

Lot of developers create utility or service classes which decouple technical behavior from the model which is not anemic model. For example someone can create a “Dal” class as shown below and pass the “Customer” object to be inserted in to the database. Lot of people term this kind of approach as “Repository” pattern.

class Dal
{
        public void InsertDb(Customer obj)
        {
            // Code of ADO.NET goes here
        }
}

Now this kind of model is not anemic model. This is separating the technical behavior from the business behavior which perfectly makes sense. In the previous example we had “validate” method which actually belongs to the “Customer” model. So Anemic model are those models which have business behavior separated in a different class and not technical behavior. So the above “Dal” class is not an Anemic model.

Customer cust = new Customer();
cust.CustomerName = "Shiv";
Dal dal = new Dal();
dal.InsertDb(cust);

3 big Complaints about Anemic model

Lot of developers unknowingly follow Anemic model because of simplicity, but OOP community has the below concerns for ADM:-

  • Anemic model disrespects OOP concepts. Objects in OOP have data and behavior. Object should model real time entity. By separating the behavior we are not following OOP. With behaviors residing in a separate class it would be difficult to inherit , apply polymorphism , abstraction and so on.
     
  • Anemic models can have inconsistent states at any time. For example see the below code we have first created a valid customer object and the validation service logic ran over it and set the “IsValid” to true. So till step 1 everything is fine “IsValid” is true and in synch with the customer object data. Now somewhere down the line you can say in step 2 customer name property is set to nothing. In this step the customer object is not valid in reality but if you try to display in Step 3 it shows valid. In order words the data and the IsValid flag is not in synch
Customer obj = new Customer();
obj.CustomerName = "Shiv";
obj.CustomerCode = "1001";

CustomerValidationService validationService = new CustomerValidationService();
validationService.Validate(obj);
Console.WriteLine(obj.IsValid); // Step 1 :- till here Valid

obj.CustomerName = ""; // Step 2 :-  we made the model invalid
Console.WriteLine(obj.IsValid); // Step 3 :- but it says Still Valid

Anemic model in disguise of IOC and DI

With all respect to the views of OOP developers Anemic models exists very beautifully and amicably in the disguise of DI IOC architecture today. I personally find it very cruel to say it’s an Anti-pattern.

Consider the below scenario where we have a customer class who has different kind of discount calculations. So rather than putting the discount calculation logic inside the customer class you can inject the object from the constructor as shown in the below. In case you are new to dependency injection please read this DI IOC in C#.

class Customer
    {
        private IDiscount _Discount = null;
        public Customer(IDiscount _Dis)
        {
            _Discount = _Dis;
        }
        private string _CustomerName;

        public string CustomerName
        {
            get { return _CustomerName; }
            set { _CustomerName = value; }
        }

        public string Region { get; set; }
        public double Amount { get; set; }
        public double CalculateDiscount()
        {
            return _Discount.Calculate(this);
        }
        
    }

And your discount calculation logic is in a different class all together which takes the customer object for calculating discount.

public interface IDiscount
{
        double Calculate(Customer Cust);
}

Below are two kinds of discount calculations one is a week end discount and the other is a special discount. The week end discount does calculation as per region and week day while the special discount is a 30% flat.

Now the below classes also follow anemic model because the actions are in a different class but still its perfectly decoupled, valid and OO.

public class WeekEndDiscount : IDiscount
{
        public double Calculate(Customer Cust)
        {
            if (Cust.Region == "Asia")
            {
                if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday)
                {
                    return (Cust.Amount * 0.20);
                }
            }
            return (Cust.Amount * 0.10);
        }
    }
    public class SpecialDiscount : IDiscount
    {

        public double Calculate(Customer Cust)
        {
            return (Cust.Amount * 0.30);
        }
    }

Conclusion

  • Anemic data model is a simple plain model class with only data and behavior resides in a separate class.
  • Rich data model have both data and behavior.
  • Anemic model is criticized for not been OO , extensible , inconsistent and follows procedural programming approach.
  • Anemic model should be confused with cross cutting concern technical classes like Logging , Repository etc.
  • DI IOC indirectly forces anemic model. So Anemic model in today world is very much present in the disguise of DI IOC.

Further references and reading

I have been writing a lot on design patterns, architecture, domain driven development and so on. So below are the link feel free to read and do give feedback.

Sunday, October 25, 2015

Immutable objects in C#

Introduction


There is saying which goes “MAKE THE POT WHILE THE MUD IS WET”. Once Mud becomes dry it cannot be changed. Immutable objects walks on the similar lines. Once the object is created it cannot be modified by anyway.

What are immutable objects?

Immutable objectsare objects which once loaded cannot be changed / modified by anyway external or internal.

Where are immutable objects used?

If I put in one line Immutable objects are used for data WHICH IS STATIC. Below are some of the instances of the same.
Master data: - One of the biggest uses of immutable objects is to load master data. Master data like country,currency , region etc rarely change. So we would like to load master data once in the memory and then we do not want it to be modified.

Configuration data: - All application needs configuration data. In Microsoft world we normally store these configuration data in to Web.config or App.config file. Such kind of data is represented by objects and these data once loaded in the application memory will not change.Its again a good practice to make these kind of configuration data objects as immutable.

Singleton objects: -In applications we normally create singleton objects for shared static data. So if the shared data is not changing it’s aawesome candidate for immutable objects. In case you are new to Singleton pattern please refer this article Singleton Pattern in C#
 

How can we create immutable objects in C#?

Immutable objects can be created only from immutable classes. To create an immutable class is a three step process :-

• Step 1:- Remove the setters of the class only have getters.
The first step towards creating an immutable class is to remove the setters. As we said values of a immutable class cannot be modified EXTERNALLY or INTERNALLY. So by removing the getters any client who creates the object of this class cannot modify the data once loaded.
 


• Step 2:- Provide parameters via constructor.
We have removed the getters so there is no way to load data in to the class. So to provide data we need to create constructors with parameters via which we can pass data to the object. Below is the modified code for the same.
 



• Step 3 :- Make the variables of the property READONLY

As we said in the previous definition immutableobjects cannot be modified by ANYWAY once the data is loaded. I will go one step further and say it cannot be modified EXTERNALLY by client or INTERNALLY by the class code himself.
 

But if you see our currency class the variables can be modified after the object creation. In other words see the below class code. We have created a method in the class called as “SomeLogic”. This method is able to successfully modify the variables after the object has been created.

So the solution for the above to make the variables “READONLY”. Below is the currency class modified where the property variables are made readonly.Readonly variables can be only initialized in the constructor and later they cannot be modified.

Hope you enjoyed this short note on Immutable objects. Immutable objects is a design pattern which was first officially discussed in Java concurrency in practice book. In case you are interested to learn design pattern I would suggest creating a full blown project and starting implementing design pattern in the same.
 

You can start from the below youtube video in which I have demonstrated design pattern with a full blown project.

Thursday, April 5, 2012

11 Important Database designing rules which I follow

Introduction
Before you start reading this article let me confirm that I am not a guru in database designing. The below 11 points which are listed are points which I have learnt via projects, my own experiences and my own reading. I personally think it has helped me a lot when it comes to DB designing. Any criticism welcome.

The reason why I am writing a full blown article is, when developers sit for designing a database they tend to follow the three normal forms like a silver bullet. They tend to think normalization is the only way of designing. Due this mind set they sometimes hit road blocks as the project moves ahead.

In case you are new to normalization, then click and see 3 normal forms in action which explains all three normal forms step by step.

Said and done normalization rules are important guidelines but taking them as a mark on stone is calling for troubles. Below are my own 11 rules which I remember on the top head while doing DB design.


Courtesy: - Image from Motion pictures

Rule 1:- What is the Nature of the application(OLTP or OLAP)?
When you start your database design the first thing to analyze is what is the natureof theapplication you are designing for, is it Transactional or Analytical. You will find many developers by default applying normalization rules without thinking about the nature of the application and then later getting in to performance and customization issues. As said there are 2 kinds of applications transaction based and analytical based,let’s understand what these types are.

Transactional: - In this kind of application your end user is more interested in CRUD i.e. Creating, reading, updating and deleting records. The official name for such kind of database is called as OLTP.

Analytical: -In these kinds of applications your end user is more interested in Analysis, reporting, forecasting etc. These kinds of databases have less number of inserts and updates. The main intention here is to fetch and analyze data as fast as possible. The official name for such kind of databases is OLAP.



So in other words if you think insert, updates and deletes are more prominent then go for normalized table design or else create a flat denormalized database structure.

Below is a simple diagram which shows how the names and address in the left hand side is a simple normalized table and by applying denormalized structure how we have created a flat table structure.


Rule 2:- Break your data in to logical pieces, make life simpler
This rule is actually the 1st rule from 1st normal formal. One of the signs of violation of this rule is if your queries are using too many string parsing functions like substring, charindexetc , probably this rule needs to be applied.

For instance you can see the below table which has student names , if you ever want to query student name who is having “Koirala” and not “Harisingh” , you can imagine what kind of query you can end up with.

So the better approach would be to break this field in to further logical pieces so that we can write clean and optimal queries.


Rule 3:- Do not get overdosed with rule 2
Developers are cute creatures. If you tell them this is the way, they keep doing it; well they overdo it leading to unwanted consequences. This also applies to rule 2 which we just talked above. When you think about decomposing, give a pause and ask yourself is it needed. As said the decomposition should be logical.

For instance you can see the phone number field; it’s rare that you will operate on ISD codes of phone number separately(Until your application demands it). So it would be wise decision to just leave it as it can lead to more complications.


Rule 4:- Treat duplicate non-uniform data as your biggest enemy
Focus and refactor duplicate data. My personal worry about duplicate data is not that it takes hard disk space, but the confusion it creates.

For instance in the below diagram you can see “5th Standard” and “Fifth standard” means the same. Now you can say due to bad data entry or poor validation the data has come in to your system. Now if you ever want toderive a report they would show them as different entities which is very confusing from end user point of view.

One of the solutions would be to move the data in to a different master table altogether and refer then via foreign keys. You can see in the below figure how we have created a new master table called as “Standards” and linked the same using a simple foreign key.

Rule 5:- Watch for data separated by separators.
The second rule of 1st normal form says avoid repeating groups. One of the examples of repeating groups is explained in the below diagram. If you see the syllabus field closely, in one field we have too much data stuffed.These kinds of fields are termed as “Repeating groups”. If we have to manipulate this data, the query would be complex and also I doubt performance of the queries.

These kinds of columns which have data stuffed with separator’s need special attention and a better approach would be to move that field to a different table and link the same with keys for better management.

So now let’s apply the second rule of 1st normal form “Avoid repeating groups”. You can see in the above figure I have created a separate syllabus table and then made a many-to-many relationship with the subject table.

With this approach the syllabus field in the main table is no more repeating and having data separators.

Rule 6:- Watch for partial dependencies.

Watch for fields which are depending partially on primary keys. For instance in the above table we can see primary key is created on roll number and standard. Now watch the syllabus field closely. Syllabus field is associated with a standard and not with a student directly (roll number).

Syllabus is associated with the standard in which the student is studying and not directly with the student. So if tomorrow we want to update syllabus we have to update for each student which is pain staking and not logical. It makes more sense to move these fields out and associate them with the standard table.

You can see how we have move the syllabus field and attached the same to standards table.

This rule is nothing but second normal form “All keys should depend on the full primary key and not partially”.

Rule 7:- Choose derived columns preciously

If you are working on OLTP applications must be getting rid of derive columns would be good thought, until there is some pressing reason of performance. In case of OLAP where we do lot of summations, calculations these kinds of fields are necessary to gain performance.

In the above figure you can see how average field is dependent on marks and subject. This is also one of form of redundancy. So for such kind of fields which are derived from other fields give a thought are they really necessary.

This rule is also termed as 3rd normal form “No columns should depend on other non-primary key columns”. My personal thought is do not apply this rule blindly see the situation; it’s not that redundant data is always bad. If the redundant data is calculative data , see the situation and then decide do you want to implement the third normal form.

Rule 8:- Do not be hard on avoidingredundancy, if performance is the key

Do not make it a strict rule that you will always avoid redundancy. If there is a pressing need of performance think about de-normalization. In normalization you need to make joins with many table and in denormalization the joins reduces and thus increasing performance.

Rule 9:- Multidimensional data is a different beast altogether
OLAP projects mostly deal with multidimensional data. For instance you can see the below figure, you would like to get sales as per country, customer and date. In simple words you are looking at sales figure which have 3 intersections of dimension data.


For such kind of situations a dimension and fact design is a better approach. In simple words you can create a simple central sales fact table which has the sales amount field and he makes a connection with all dimension tables using a foreign key relationship.


Rule 10:- Centralize name value table design
Many times I have come across name value tables. Name and value tables means it has key and some data associated with the key. For instance in the below figure you can see we have currency table and country table. If you watch the data closely they actually only have Key and value.

For such kind of table creating one central table and differentiating the data by using a type field makes more sense.

Rule 11:- For unlimited hierarchical data self-reference PK and FK
Many times we come across data with unlimited parent child hierarchy. For instance consider a Multi-level marketing scenario where one sales person can have multiple sales people below them. For such kind of scenarios using a self-referencing primary key and foreign key will help to achieve the same.


This article is not meant to say that do not follow normal forms , but do not follow them blindly , look at your project nature and type of data you are dealing with.

Out of full respect, below is a video which explains 3 normal forms step by step using a simple school table.



You can also visit my site for step by step videos on Design Patterns, UML, SharePoint 2010, .NET Fundamentals, VSTS, UML, SQL Server, MVC and lot more.

Visit for more authors blog on .NET Interview questions

Thursday, April 7, 2011

.NET and Java J2EE Design pattern interview question: - What is the difference between Facade and Mediator pattern?

Answer:
Facade Design pattern

  1. Aims at simplifying interface.

  2. Existence of façade is not known to sub-system.

  3. Intermediates between client and sub stem.

Mediator Design pattern


  1. Aims at simplifying object interaction.

  2. Existence of mediator is known to objects since they interact using
    the same.

  3. Intermediates between various objects which want to interact.
Regards,

Do visit our .NET design pattern and Java J2EE design pattern interview questions.

Friday, March 25, 2011

Design pattern interview questions :- Which design patterns have you used in your project ?

Answer:

First thing what ever you say , for heaven sake do not say we had used all design patterns ;-) . Look at your project and see which design pattern have you used. Almost all projects use design patterns knowingly or unknowingly , until the project is complete disorganized.

While explaining do ensure to make a 1 line comment atleast to say why that design pattern was used.

Below goes a decent answer of explaining things collectively. Please note answer will change as per your project implementation.

In my current project we had used MVC, Singleton, factory , iterator and template pattern.

My project was tier architecture, divided in to 3 main sections, UI, Business layer and data access layer.

At the presentation level we had used MVC pattern, so the UI and model was separated using controller class.

To share common data across all tiers we had used the singleton pattern.

Factory classes where used between each layer for decoupling and centralizing object creation to avoid code complication.

Iterator pattern was used to browse through middle tier objects thus providing a tight encapsulation.

The middle tier objects and their child objects where standardized using template pattern for consistent vocabulary and naming convention for business objects.

Watch the below design pattern video which explains factory pattern.



Regards,

Please click here to see .NET interview questions and J2EE design pattern questions

Saturday, March 5, 2011

C# Interview Questions:-What is MVVM ( Model view view model) Design pattern ?

C# Interview Questions:-What is MVVM ( Model view view model) Design pattern?


Answers

This is a good c# interview questions which is asked around design pattern.

MVVM is a UI design pattern. The main use of this pattern to remove UI cluttered code like bindings , synchronization etc.

In this pattern we create a extra class called as view model or model which acts as a bridge between model and view. The view sends the actions and data to the model view class who in turns sends the data to model. Any changes in the model is replicated or informed to the UI using the INotifyPropertyChanged interface.


Regards,

View my 21 important C#Interview Questions and Answers

Saturday, September 12, 2009

Design pattern – Inversion of control and Dependency injection

Introduction

In this section we will discuss about how IOC and DI can help us build loosely coupled software architecture. I am not sure should we call this a design pattern or more of a approach. If you search around the web you will see lot of controversy on whether IOC is a design pattern or not. From my point of view it is a design pattern as it solves a problem context.
It would be great to see actual architectures implementing IOC using container oriented approaches. I am sure it will change the way we think about interaction between components.
Please feel free to download my free 500 question and answer videos which covers Design Pattern, UML, Function Points, Enterprise Application Blocks, OOP'S, SDLC, .NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ, SilverLight, .NET Best Practices @ these videos http://www.questpond.com/
So let us understand in detail about IOC and DI.


Design pattern – Inversion of control and Dependency injection


The Problem – Tight Coupling

Before even we get in to abbreviation of IOC and DIP, let’s first understand the problem. Consider the below example we have a customer class which contains an address class object. The biggest issue with the code is tight coupling between classes. In other words the customer class depends on the address object. So for any reason address class changes it will lead to change and compiling of ‘ClsCustomer’ class also. So let’s put down problems with this approach:
  • The biggest problem is that customer class controls the creation of address object.
  • Address class is directly referenced in the customer class which leads to tight coupling between address and customer objects.
  • Customer class is aware of the address class type. So if we add new address types like home address, office address it will lead to changes in the customer class also as customer class is exposed to the actual address implementation.

    Figure: - Problems of IOC
So if for any reason the address object is not able to create the whole customer class will fail in the constructor initialization itself.

Solution

Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. The main problem roots from the customer class creating the address object. If we are able to shift this task / control of object creation from the customer class to some other entity we have solved our problem. In other sentence if we are able to invert this control to a third party we have found our solution. So the solution name is IOC (Inversion of control).

Principles of IOC

The basic principle of IOC stands on the base of Hollywood principle (response given to amateurs auditioning in Hollywood):

Do not call us we will call you

Translating to bollywood (for struggling actors)


Aap Mauke ko mat bulao, mauka aap ke paas ayega – Hindi conversion ?

In other words it like address class saying to the customer class, do not create me I will create myself using some one else.

There are two principles of IOC:
  • Main classes aggregating other classes should not depend on the direct implementation of the aggregated classes. Both the classes should depend on abstraction. So the customer class should not depend directly on the address class. Both address and customer class should depend on an abstraction either using interface or abstract class.
  • Abstraction should not depend on details, details should depend on abstraction.

Figure: - IOC framework
Figure ‘IOC framework’ shows how we can achieve this decoupling. The simplest way would be to expose a method which allows us to set the object. Let the address object creation be delegated to the IOC framework. IOC framework can be a class, client or some kind of IOC container. So it will be two step procedure IOC framework creates the address object and passes this reference to the customer class.

Ways of implementing IOC

Ok, now we know the problem, let’s try to understand the broader level solution. Let’s look at how we implement the solution for IOC. IOC is implemented using DI (Dependency injection). We have discussed on a broader level about how to inject the dependency in the previous sections. In this section we will dive deeper in to other ways of implementing DI.


Figure: - IOC and DI
Figure ‘IOC and DI’ shows how IOC and DI are organized. So we can say IOC is a principle while DI is a way of implementing IOC. In DI we have four broader ways of implementing the same:
  • Constructor way
  • Exposing setter and getter
  • Interface implementation
  • Service locator

In the further sections we will walkthrough the same in more detail.

Constructor Methodology

In this methodology we pass the object reference in the constructor itself. So when the client creates the object he passes the object in the constructor while the object is created. This methodology is not suited for client who can only use default constructors.


Figure: - Constructor based DI

Setter and Getter

This is the most commonly used DI methodology. The dependent objects are exposed through set/get methods of classes. The bad point is because the objects are publicly exposed it breaks the encapsulation rule of object oriented programming.


Figure: - Getter and Setter

Interface based DI

In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. You can see in figure ‘Interface based DI’ we have implemented an interface ‘IAddressDI’ which has a ‘setAddress’ method which sets the address object. This interface is then implemented in the customer class. External client / containers can then use the ‘setAddress’ method to inject the address object in the customer object.


Figure: - Interface based DI

Service Locator

The other way to inject dependency is by using service locator. Your main class which will aggregate the child object will use the service locator to obtain instance of the address object. The service locator class does not create instances of the address object, it provides a methodology to register and find the services which will help in creating objects.


Figure: - Service locator

Implementing the DI

Now that we know the various types of DI to implement IOC. Its time to understand how we can actually implement these DI’s.

What is wrong with DI FACTORY?

The first thing which clicks to mind is, can't we achieve all the above things using factory. The main problem is all about one class doing the creational activity of its contained objects which leads to heavy coupling. Introducing factory can solve that to a great extent.

Here are the issues with factory which makes us force to think about some other solutions:
  • Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
  • Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.

  • Factories are custom: - They are very much custom to a particular implementation.

  • Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

The container way

A container is an abstraction responsible for object management, instantiation and configuration. So you can configure the objects using the container rather than writing client code like factory patterns to implement object management. There are many containers available which can help us manage dependency injection with ease. So rather than writing huge factory codes container identifies the object dependencies and creates and injects them in appropriate objects.


Figure: - Container in action
So you can think about container as a mid man who will register address and customer objects as separate entity and later the container creates the customer and address object and injects the address object in the customer. So you can visualize the high level of abstraction provided by containers.

What we will do is cover the customer and address example using one of the container Windsor container, you can get more details about the container here.

Implementation using Windsor

The first thing we do is create the address interface and create the concrete class from this interface. Interface will be an entity to use for injection rather than concrete objects, so that we deal with more abstraction rather than concrete implementation.


Figure: - Address interface
In the customer class we have passed the object through the constructor.


Figure: - Customer class
If we are said to write the client code. , it would be something as shown in figure ‘Client code’. In step 1 we create a concrete object and point the implementation to the interface IAddress. In step 2 we pass the interface object to customer class constructor while creating the object.


Figure: - Client code
Ok, now lets see how this will work if we use the Windsor container. Figure ‘Windsor container’ shows how it looks like. So step 1 creates the Windsor container object. Step 2 and 3 register the types and concrete objects in the container. Step 4 requests the container to create the customer object. In this step the container resolves and set the address object in the constructor. Step 5 releases the customer object.


Figure: - Windsor container
Ok, guys understood, the above code is more complicated than the client code. In actual implementation using the container we never use client code, rather we use config files. You can see from figure ‘Creating using config files’ we have better flexibility to add more objects. The XmlInterpreter object helps to read the config file to register the objects in the container. Using the container.resolve method we have finally created the customer object. So the container plays the mediator role of understanding the customer object and then injecting the address object in the customer object through the constructor. In config file we need to define all the components in the components section.


Figure: - Creating using config files


References

Hanselman has given a list of containers useful link to visit:
http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx
http://msdn.microsoft.com/en-us/magazine/cc163739.aspx
http://msdn.microsoft.com/en-us/library/cc707905.aspx
http://www.devx.com/Java/Article/27583/0/page/2

Tuesday, September 8, 2009

Design Pattern Interview Questions - Part 4

Introduction

This article is the Part 4 of the Design Pattern. Please feel free to download my free 500 question and answer ebook which covers .NET, ASP.NET, SQL Server, WCF, WPF, WWF @ http://www.questpond.com/
You can visit and download the complete architecture Interview questions PDF which covers SOA, UML, Design patterns, Togaf, OOPs etc

Happy job hunting......
You can download the software architecture interview questions PDF Download Software Architecture Interview Questions

Design Pattern Interview Questions - Part 4


(A) Can you explain bridge pattern?

Bridge pattern helps to decouple abstraction from implementation. With this if the implementation changes it does not affect abstraction and vice versa. Consider the figure ‘Abstraction and Implementation’. The switch is the abstraction and the electronic equipments are the implementations. The switch can be applied to any electronic equipment, so the switch is an abstract thinking while the equipments are implementations.

Figure: - Abstraction and Implementation
Let’s try to code the same switch and equipment example. First thing is we segregate the implementation and abstraction in to two different classes. Figure ‘Implementation’ shows how we have made an interface ‘IEquipment’ with ‘Start()’ and ‘Stop()’ methods. We have implemented two equipments one is the refrigerator and the other is the bulb.

Figure :- Implementation
The second part is the abstraction. Switch is the abstraction in our example. It has a ‘SetEquipment’ method which sets the object. The ‘On’ method calls the ‘Start’ method of the equipment and the ‘off’ calls the ‘stop’.
Figure: - Abstraction
Finally we see the client code. You can see we have created the implementation objects and the abstraction objects separately. We can use them in an isolated manner.
Figure :- Client code using bridge


(A) Can you explain composite pattern?

GOF definition :- A tree structure of simple and composite objects
Many times objects are organized in tree structure and developers have to understand the difference between leaf and branch objects. This makes the code more complex and can lead to errors.
For example below is a simple object tree structure where the customer is the main object which has many address objects and every address object references lot of phone objects.


Figure: - General Process
Now let’s say you want to insert the complete object tree. The sample code will be something as shown below. The code loops through all the customers, all addresses inside the customer object and all phones inside the address objects. While this loop happens the respective update methods are called as shown in the below code snippet.
foreach (Customer objCust in objCustomers)
{
objCust.UpDateCustomer();
 foreach (Address oAdd in objCust.Addresses)
 {
  oAdd.UpdateAddress();
 }
   foreach (Phone ophone in oAdd.Phones)
   {
     ophone.UpDatePhone();
   }
}

The problem with the above code is that the update vocabulary changes for each object. For customer its ‘UpdateCustomer’ , for address its ‘UpdateAddress’ and for phone it is ‘UpdatePhone’. In other words the main object and the contained leaf nodes are treated differently. This can lead to confusion and make your application error prone.
The code can be cleaner and neat if we are able to treat the main and leaf object uniformly. You can see in the below code we have created an interface (IBusinessObject) which forces all the classes i.e. customer, address and phone to use a common interface. Due to the common interface all the object now have the method name as “Update”.
foreach (IBusinessObject ICust in objCustomers)
{
ICust.Update();
  foreach (IBusinessObject Iaddress in ((Customer)(ICust)).ChildObjects)
   {
     Iaddress.Update();
foreach (IBusinessObject iphone in ((Address)(Iaddress)).ChildObjects)
      {
         iphone.Update();
}
   }
}
In order to implement composite pattern first create an interface as shown in the below code snippet.
public interface IBusinessObject
{
        void Update();
        bool isValid();
        void Add(object o);

}

Force this interface across all the root objects and leaf / node objects as shown below.
public class Customer : IBusinessObject
    {

        private List<Address> _Addresses;
        public IEnumerable<Address> ChildObjects
        {
            get
            {
                return (IEnumerable<Address>)_Addresses;
            }
        }
        public void Add(object objAdd)
        {
            _Addresses.Add((Address) objAdd);
        }
        public void Update()
        {
  
        }
        public bool isValid()
        {
            return true;
        }
}
Force the implementation on the address object also.
public class Address : IBusinessObject
    {
        private List<Phone> _Phones;

        public IEnumerable<Phone> ChildObjects
        {
            get
            {
                return (IEnumerable<Phone>)_Phones.ToList<object>();
            }
        }

        public void Add(object objPhone)
        {
            _Phones.Add((Phone)objPhone);
        }



        public void Update()
        {
 
        }

        public bool isValid()
        {
            return true;
        }


    }
Force the implementation on the last node object i.e. phone.
public class Phone : IBusinessObject
    {
        public void Update()
        {}
        public bool isValid()
        {return true;}
        public void Add(object o)
        {
            // no implementaton
        }
    }

(I) Can you explain decorator pattern?

Punch :- Decorator pattern adds dynamically stacked behavior thus helping us to change the behavior of the object on runtime.
There are situations where we would like to add dynamic stacked behavior to a class on runtime.
The word stack is an important word to note. For instance consider the below situation where a hotel sells bread meals. They have four important products and the order can be placed using the below combination:-
  • Simple bread.
  • Bread with Chicken.
  • Bread with drinks
  • Bread with chicken and drinks.
In other words the order process behavior and the cost of the order changes on runtime depending on the type of the combination.

Figure: -
Below is a simple order with only bread which has two functions ‘prepare’ and ‘calculatecost’. We would like to add new products to this basic bread order dynamically on runtime depending on what the customer wants.
Below is a simple interface which every order will have i.e. Prepare and CalculateCost.
interface IOrder
{
string Prepare();
double CalculateCost();
}
The base product is the bread which implements the Iorder interface. We would like to add new products to the bread order and change the behavior of the complete order.
public class OrderBread : IOrder
    {
        public string Prepare()
        {
            string strPrepare="";
            strPrepare = "Bake the bread in oven\n";
            strPrepare = strPrepare + "Serve the bread";
            return strPrepare;
        }

        public double CalculateCost()
        {
            return 200.30;
        }
    }
We can alter the bread order dynamically using decorator pattern. To implement decorator pattern is a 5 steps process.
Step1:- Create a decorator class which aggregates the object / interface for which we need to add the behavior dynamically.
abstract class OrderDecorator : IOrder
    {
        protected IOrder Order;
   . . . . .
   . . . . .
   . . . . .

    }
This decorator class will house the object and any method calls to the main object will first invoke all the housed objects and then the main object.
So for instance if you are calling the prepare method, this decorator class will invoke all the prepare methods of the housed object and then the final prepare method. You can see how the output changes when decorator comes in to picture.


Figure: -

Step 2: - The housed object/ interface pointer needs to be initialized. We can do the same by using various means for the sample below we will just expose a simple constructor and pass the object to the constructor to initialize the housed object.
abstract class OrderDecorator : IOrder
    {
        protected IOrder Order;
   public OrderDecorator(IOrder oOrder)
        {
            Order = oOrder;
        }
   . . . . .

    }
Step 3: - We will implement the Iorder interface and invoke the house object methods using the virtual methods. You can see we have created virtual methods which invoke the house object methods.
abstract class OrderDecorator : IOrder
    {
        protected IOrder Order;

        public OrderDecorator(IOrder oOrder)
        {
            Order = oOrder;
        }
        public virtual string Prepare()
        {
            return Order.Prepare();
        }

        public virtual double CalculateCost()
        {
            return Order.CalculateCost();
        }
    }
Step 4: - We are done with the important step i.e. creating the decorator. Now we need to create dynamic behavior object which can be added to the decorator to change object behavior on runtime.
Below is a simple chicken order which can be added to the bread order to create a different order all together called as chicken + bread order. The chicken order is created by inheriting from the order decorator class.
Any call to this object first invokes custom functionality of order chicken and then invokes the housed object functionality. For instance you can see When prepare function is called it first called prepare chicken functionality and then invokes the prepare functionality of the housed object.
The calculate cost also adds the chicken cost and the invokes the housed order cost to sum up the total.
class OrderChicken : OrderDecorator
    {
        public OrderChicken(IOrder oOrder) : base(oOrder)
        {
        }

         public override string Prepare()
        {
            return base.Prepare() +  PrepareChicken();
        }
        private string PrepareChicken()
        {
            string strPrepare = "";
            strPrepare = "\nGrill the chicken\n";
            strPrepare = strPrepare + "Stuff in the bread";
            return strPrepare;
        }
        public override double CalculateCost()
        {
            return base.CalculateCost() + 300.12;
        }
    }
Same way we can also prepare order drinks.
class OrderDrinks : OrderDecorator
    {
        public OrderDrinks(IOrder oOrder)
            : base(oOrder)
        {

        }
        public OrderDrinks()
        {
        }
public override string Prepare()
        {

            return base.Prepare() + PrepareDrinks();
        }
        private string PrepareDrinks()
        {
            string strPrepare = "";
            strPrepare = "\nTake the drink from freezer\n";
            strPrepare = strPrepare + "Serve in glass";
            return strPrepare;
        }

        public override double CalculateCost()
        {
            return base.CalculateCost() + 10.12;
        }
    }
Step 5:- The final step is see the decorator pattern in action. So from the client side you can write something like this to create a bread order.
IOrder Order =new OrderBread();
Console.WriteLine(Order.Prepare());
Order.CalculateCost().ToString();
Below is how the output will be displayed for the above client call.
Order 1 :- Simple Bread menu
Bake the bread in oven
Serve the bread
200.3
If you wish to create the order with chicken, drink and bread, the below client code will help you with the same.
Order = new OrderDrinks(new OrderChicken(new OrderBread()));
Order.Prepare();
Order.CalculateCost().ToString();
For the above code below is the output which combines drinks + chicken + bread.
Order 2 :- Drinks with chicken and bread
Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
Take the drink from freezer
Serve in glass
510.54
In other words you can now attach these behaviors to the main object and change the behavior of the object on runtime.
Below are different order combination we can generate , thus altering the behavior of the order dynamically.
Order 1 :- Simple Bread menu
Bake the bread in oven
Serve the bread
200.3


Order 2 :- Drinks with chicken and bread
Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
Take the drink from freezer
Serve in glass
510.54


Order 3 :- Chicken with bread
Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
500.42


Order 4 :- drink with simple bread
Bake the bread in oven
Serve the bread
Take the drink from freezer
Serve in glass
210.42

(A) Can you explain Façade pattern?

Façade pattern sits on the top of group of subsystems and allows them to communicate in a unified manner
Figure: - Façade and Subsystem
Figure ‘Order Façade’ shows a practical implementation of the same. In order to place an order we need to interact with product, payment and invoice classes. So order becomes a façade which unites product, payment and invoice classes.

Figure: - Order Facade
Figure ‘façade in action’ shows how class ‘clsorder’ unifies / uses ‘clsproduct’,’clsproduct’ and ‘clsInvoice’ to implement ‘PlaceOrder’ functionality.


Figure :- Façade in action

Note:- You can find the façade code in the ‘façade pattern’ folder.


(A) Can you explain chain of responsibility ( COR)?

Chain of responsibility is used when we have series of processing which will be handled by a series of handler logic. Let’s understand what that means. There are situations when a request is handled by series of handlers. So the request is taken up by the first handler, he either can handle part of it or can not, once done he passes to the next handler down the chain. This goes on until the proper handler takes it up and completes the processing.

Figure: - Concept of Chain of Responsibility

Let’s try to understand this concept by a small sample example. Consider figure ‘Sample example’ where we have some logic to be processed. So there are three series of processes which it will go through. So process 1 does some processing and passes the same to process 2. Process 2 does some kind of processing and passed the same to process 3 to complete the processing activity.
Figure: - Sample example
Figure ‘class diagram for COR’ the three process classes which inherit from the same abstract class. One of the important points to be noted is that every process points to the next process which will be called. So in the process class we have aggregated one more process object called as ‘objProcess’. Object ‘ObjProcess’ points to next process which should be called after this process is complete.
Figure: - Class diagram for COR
Now that we have defined our classes its time to call the classes in the client. So we create all the process objects for process1 , process2 and process3. Using the ‘setProcess’ method we define the link list of process objects. You can see we have set process2 as a link list to process1 and process2 to process3. Once this link list is established we run the process which in turn runs the process according to the defined link list.
Figure: - COR client code
Note :- You can get the code for the same in C# in ‘ChainOfResponsibility’ folder.


(I) Can you explain proxy pattern?

Proxy fundamentally is a class functioning as in interface which points towards the actual class which has data. This actual data can be a huge image or an object data which very large and can not be duplicated. So you can create multiple proxies and point towards the huge memory consuming object and perform operations. This avoids duplication of the object and thus saving memory. Proxies are references which points towards the actual object.
Figure ‘Proxy and actual object’ shows how we have created an interface which is implemented by the actual class. So the interface ‘IImageProxy’ forms the proxy and the class with implementation i.e. ‘clsActualImage’ class forms the actual object. You can see in the client code how the interface points towards the actual object.

Figure: - Proxy and actual object
The advantages of using proxy are security and avoiding duplicating objects which are of huge sizes. Rather than shipping the code we can ship the proxy, thus avoiding the need of installing the actual code at the client side. With only the proxy at the client end we ensure more security. Second point is when we have huge objects it can be very memory consuming to move to those large objects in a network or some other domain. So rather than moving those large objects we just move the proxy which leads to better performance.
Note :- You can get the proxy code in the ‘Proxy Pattern’ folder.


(B) Can you explain template pattern?

Template pattern is a behavioral pattern. Template pattern defines a main process template and this main process template has sub processes and the sequence in which the sub processes can be called. Later the sub processes of the main process can be altered to generate a different behavior.
Punch :- Template pattern is  used in scenarios where we want to create  extendable behaviors in generalization and specialization relationship.
For example below is a simple process to format data and load the same in to oracle. The data can come from various sources like files, SQL server etc. Irrespective from where the data comes, the overall general process is to load the data from the source, parse the data and then dump the same in to oracle.

Figure: - General Process
Now we can alter the general process to create a CSV file load process or SQL server load process by overriding ‘Load’ and ‘Parse’ sub process implementation.

Figure: - Template thought Process
You can see from the above figure how we have altered ‘Load’ and ‘Parse’ sub process to generate CSV file and SQL Server load process. The ‘Dump’ function and the sequence of how the sub processes are called are not altered in the child processes.
In order to implement template pattern we need to follow 4 important steps:-
  1. Create the template or the main process by creating a parent abstract class.
  2. Create the sub processes by defining abstract methods and functions.
  3. Create one method which defines the sequence of how the sub process methods will be called. This method should be defined as a normal method so that we child methods cannot override the same.
  4. Finally create the child classes who can go and alter the abstract methods or sub process to define new implementation.
public abstract class GeneralParser
    {
        protected abstract void Load();

        protected abstract void Parse();
        protected virtual void Dump()
        {
            Console.WriteLine("Dump data in to oracle");
        }
        public void Process()
        {
            Load();
            Parse();
            Dump();
        }
    }
The ‘SqlServerParser’ inherits from ‘GeneralParser’ and overrides the ‘Load’ and ‘Parse’ with SQL server implementation.
public class SqlServerParser : GeneralParser
    {
        protected override void Load()
        {
            Console.WriteLine("Connect to SQL Server");
        }
        protected override void Parse()
        {
            Console.WriteLine("Loop through the dataset");
        }

    }
The ‘FileParser’ inherits from General parser and overrides the ‘Load’ and ‘Parse’ methods with file specific implementation.
public class FileParser : GeneralParser
    {
        protected override void Load()
        {
            Console.WriteLine("Load the data from the file");
        }
        protected override void Parse()
        {
            Console.WriteLine("Parse the file data");
        }

    }
From the client you can now call both the parsers.
FileParser ObjFileParser = new FileParser();
ObjFileParser.Process();
Console.WriteLine("-----------------------");
SqlServerParser ObjSqlParser = new SqlServerParser();
ObjSqlParser.Process();
Console.Read();
The outputs of both the parsers are shown below.
Load the data from the file
Parse the file data
Dump data in to oracle
-----------------------
Connect to SQL Server
Loop through the dataset
Dump data in to oracle

Other Interview question PDF's

.NET Interview Question PDF