Pages

Sunday, June 19, 2011

Likov's Substitution Principle with example in C#

Definition


Likov's Substitution Principle states that if for each object m1 of type S there is an object m2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when m1 is substituted for m2 then S is a subtype of T.


Now let’s see the simple example of LSP Violation of code
 
In this example we have one common interface “ICustomer” which is inherits to two classes i.e.
ClsPaidCustomerSalesEnity, ClsFreeCustomerSalesEnity . two different classes which set and get properties and do calculation and print invoice as per customer status
 
For ClsPaidCustomerSalesEnity we have calculated special discount and printed the Invoice with customer name and amount
 
For  ClsFreeCustomerSalesEnity we have 0 discount and in PrintInvoice we return something
throw new NotImplementedException();
 
Means nothing was implemented in this method
 
//Interface Code
public interface ICustomer
{
  string CustomerName { set; get; }
  int CustomerCode { set; get; }
  int ProductQuantity { set; get; }
  double ProductRate { set; get; }
  double CalculateDiscountRate();
  string PrintInvoice(double _amount);
}
 


//Paid Customer Code
  public class ClsPaidCustomerSalesEnity : ICustomer
    {
        private string _customername;
        private int _customercode;
        private int _productquantity;
        private double _productrate;
        public string CustomerName
        {
            set { _customername = value; }
            get { return _customername; }
        }
        public int CustomerCode
        {
            set { _customercode = value; }
            get { return _customercode; }
        }
        public int ProductQuantity
        {
            set { _productquantity = value; }
            get { return _productquantity; }
        }
        public double ProductRate
        {
            set { _productrate = value; }
            get { return _productrate; }
        }
        public  double CalculateDiscountRate()
        {
            double rate = ProductQuantity * ProductRate;
            double discountamount = 0;
            double disrate = 20;
            discountamount = (disrate / 100) * rate;
            rate = rate - discountamount;
            return rate;
        }
        public string PrintInvoice(double _amount)
        {
            return "Product Invoice For Customer " + CustomerName + " with Total Amount " + _amount;
        }
}
 


//Free Customer Code
public class ClsFreeCustomerSalesEnity : ICustomer
    {
        private string _customername;
        private int _customercode;
        private int _productquantity;
        private double _productrate;
        public string CustomerName
        {
            set { _customername = value; }
            get { return _customername; }
        }
        public int CustomerCode
        {
            set { _customercode = value; }
            get { return _customercode; }
        }
        public int ProductQuantity
        {
            set { _productquantity = value; }
            get { return _productquantity; }
        }
        public double ProductRate
        {
            set { _productrate = value; }
            get { return _productrate; }
        }
        public double CalculateDiscountRate()
        {
            return 0;
        }
        public string PrintInvoice(double _amount)
        {
            throw new NotImplementedException();
        }
    }
 
 


Both code is almost similar but only difference in implementation and inherits with common interface
Now let’s come to our window form application code
 
 
  ICustomer objIcust;
          List listcust = new List();
            objIcust = new ClsPaidCustomerSalesEnity();
            objIcust.CustomerName = "Paid Customer";
            objIcust.CustomerCode = 001;
            objIcust.ProductQuantity = 5;
            objIcust.ProductRate = 20;
            listcust.Add(objIcust);
 


            objIcust = new ClsFreeCustomerSalesEnity();
            objIcust.CustomerName = "Free Customer";
            objIcust.CustomerCode = 002;
            objIcust.ProductQuantity = 5;
            objIcust.ProductRate = 20;
            listcust.Add(objIcust);
            string printinvoice = "";
 


            foreach (ICustomer iCust in listcust)
            {
                double amount = iCust.CalculateDiscountRate();
                printinvoice = iCust.PrintInvoice(amount);
                listBox1.Items.Add("Invoice Report --> " + printinvoice);              
            }
 


Problem with this code  when loop our Icustomer  collections it will work fine with
ClsPaidCustomerSalesEnity calculates Discount Rate and and print invoice properly
 
But when it loads ClsFreeCustomerSalesEnity  CalculateDiscountRate returns 0 and for PrintInvoice it throws new NotImplemented Exception which is totally wrong and on UI we don’t need any exception error  and writing Hacks and like if conditions is not proper way of design architecture
 
This is the problem with code
 
As it says it Free Customer code like paid customer code but unlike paid customer code there is not implementation of DiscountRate and Print Invoice method
 
 
So now let’s see the solution for above code using Likov's Substitution Principle
 


A simple solutions but Customer Type i.e. paid customer class and free customer are not same difference in discount rate and print invoice implementation
 
 
If it looks like a duck, quacks like a duck, but needs batteries - wrong abstraction


So we need to create different interface for paid customer and for free customer
 
 
   public interface IFreeCustomer
    {
        string CustomerName { set; get; }
        int CustomerCode { set; get; }
        int ProductQuantity { set; get; }
        double ProductRate { set; get; }
    }
 


//use this for paid customer for printing invoice
    public interface IPaidPrintCustomer
    {
        string CustomerName { set; get; }
        int CustomerCode { set; get; }
        int ProductQuantity { set; get; }
        double ProductRate { set; get; }
        double CalculateDiscountRate();
        string PrintInvoice(double _amount);
    }
 


public class ClsPaidCustomerSalesEnity : IPaidPrintCustomer
{
//do the implementation as same as we did for customer
}
 


  public class ClsFreeCustomerSalesEnity : IFreeCustomer
  {
//do the implementation as same as we did for customer
  }
 


Then create separate objects and call it in UI
So Problem is solved successfully

Saturday, June 18, 2011

Open Closed Principle with real world example in C#

Definition
In object-oriented programming (OOPS), the open closed principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification


A class should be closed for modifications but their functions or methods can be altered for further open extension


The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged


Now lets see simple real time scenario of Open Closed Principle Violation or Bad Code


Lets consider a simple windows form application of Customer Sales Entity with customer Status as declared with enumeration (Enum)


Enum = Enum stores the constant values.Enums are strongly typed constants.


Customer Name , Customer Code , Product Quantity , Product Rate and with a simple method Calculate Discount
We have Customer Type like Silver, Gold customer which is declared in enum .


For each different customer type we had different discount facility over total amount


Now as you can see we just coded CustomerSalesEntity with set get properties and with Calculate Discount Implementation
 


class ClsCustomerSalesEnity {
public enum CustomerStatus{
Silver,
Gold
}
private string _customername;
private int _customercode;
private int _productquantity;
private double _productrate;
private CustomerStatus _customertype;
public string CustomerName
{
set { _customername = value; }
get { return _customername; }
}
public int CustomerCode
{
set { _customercode = value; }
get { return _customercode; }
}
public CustomerStatus CustomerType
{
set { _customertype = value; }
get { return _customertype; }
}
public int ProductQuantity
{
set { _productquantity = value; }
get { return _productquantity; }
}
public double ProductRate
{
set { _productrate = value; }
get { return _productrate; }
}
public double CalculateDiscountRate()
{
double rate = ProductQuantity * ProductRate;
double discountamount = 0;
double disrate = 0;
if (CustomerType == CustomerStatus.Silver)
{
disrate = 5;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
}
if (CustomerType == CustomerStatus.Gold)
{
disrate = 20;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
}
return rate;
}
}


As per code when you at the CalculateDiscountRate() method there we distinguish customer type (Silver,Gold) discount rate with if condition
 


Sample
public enum CustomerStatus
{
Silver,
Gold
}
If (CustomerType == CustomerStatus.Silver {
disrate = 5;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
}
if (CustomerType == CustomerStatus.Gold)
{
disrate = 20;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
}
 


This code looks perfect we create dll and ship this application as per our client requirement


Then you must me thinking what the problem was?


The problem is that consider that our Client wants add new category or new customer type (Customer Bronze) then we might need to modify existing class and where ever we use this class everywhere we to need to modifications simply means just to modify a full application then deploy again. Again and again for any Clients changes we need to modify existing code / class


The Code was not designed properly here where OCP violates


Just Testing Purpose


On Windows form.cs on button click just add this code
ClsCustomerSalesEnity objCustomerEntity = new ClsCustomerSalesEnity();
objCustomerEntity.CustomerCode = Convert.ToInt16(textBox1.Text);
objCustomerEntity.CustomerName = textBox2.Text;
objCustomerEntity.CustomerType = (ClsCustomerSalesEnity.CustomerStatus)Enum.Parse(typeof(ClsCustomerSalesEnity.CustomerStatus), textBox3.Text, true);
;
objCustomerEntity.ProductQuantity = Convert.ToInt16(textBox4.Text);
objCustomerEntity.ProductRate = Convert.ToDouble(textBox5.Text);
label7.Text = Convert.ToString(objCustomerEntity.CalculateDiscountRate());
 
 
 


Now let’s see solutions for above Code
Now we need to make our CutomerSalesEntity flexible so that It  cannot be modified further but can open for an extension
 


Step 1
We give abstract keyword to our CutomerSalesEntity class


Step 2
Method or property which we think or designed in that way to be altered in future or can be flexible for extension  (Need to be keep abstract or virtual )
 


Here I will give abstract keyword to method CalculateDiscountRate()
 


Now lets see the following code
public abstract class ClsCustomerSalesEnity
{
private string _customername;
private int _customercode;
private int _productquantity;
private double _productrate;
public string CustomerName
{
set { _customername = value; }
get { return _customername; }
}
public int CustomerCode
{
set { _customercode = value; }
get { return _customercode; }
}
public int ProductQuantity
{
set { _productquantity = value; }
get { return _productquantity; }
}
public double ProductRate
{
set { _productrate = value; }
get { return _productrate; }
}
public abstract double CalculateDiscountRate();
}
 


This is our Fix CustomerSalesEntity class which in further now going to be modified but yes will be open for extension
 


Now assume that we want to add new customer Type (say gold customer)


For that we will be creating new class clsGoldCustomerSalesEntity and inheriting from


ClsCustomerSalesEnity


public class clsGoldCustomerSalesEntity : ClsCustomerSalesEnity
{
public override double CalculateDiscountRate()
{
double rate = ProductQuantity * ProductRate;
double discountamount = 0;
double disrate = 20;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
return rate;
}
}
 


Again if want to add new customer we will be doing same procedure
 


public class clsSilverSalesEntity : ClsAbstractCustomerSalesEnity
{
public override double CalculateDiscountRate()
{
double rate = ProductQuantity * ProductRate;
double discountamount = 0;
double disrate = 5;
discountamount = (disrate / 100) * rate;
rate = rate - discountamount;
return rate;
}
}
 


So as you can see that Our CustomerSalesEntity class is open for extension but closed for modification
Here OCP rules fulfills solution

Monday, December 27, 2010

Send Free New Year SMS - atsms4u

Send Free New Year SMS

Atsms4u wishes you Happy New Year 2011

Celebrate Your New Year Festival by Sending Free SMS Any Where in India on New Year 2011 via atsms4u

After the celebration of Christmas and when Santa Clause is gone in just 7 days we have New Year with lots of New Happiness, New Hope, New Fun, New Dream, New Blessings….A New Day to start our work, our studies, our achievements and goals, our life with a new style

Lets make this new year 2011 some more special than 2010, lets spread more love, lets spread more happiness, lets come forward with helping hands for those needy people, lets do something different andf special which makes other feel better and happy, lets not hurt our friends, relatives and loved ones, lets not cheat, lie, steal or do some wrong things, lets be kind and merciful to others, lets not be angry or fall into temper, lets not fight and shout, lets be humble, have fun, enjoy each moment and always have a smiling face.  Even though you cant get a good marks in studies, good job, good salary and even though your condition is same as it was in last year but at least change your behavior your nature and these all things will follow you, because God is with you always

ATSMS4U presents simple and cool way to make you and your Friends always in touch. You just need to register yourself in www.atsms4u.com login and Send Free SMS to your Friends, Relatives and Loved Ones you know all over India… Keep in touch with your SMS…Keep in touch with ATSMS4U…Your New Friend of 2011.

Send Free New Year SMS of 200 Characters to any mobile phone all over India.

Send New Year sms to your friends and relatives.

Wish happiness, prosperity and great joys of coming New Year

ATSMS4U.COM provides you a Simple and Easy User Interface for Sending Quick New Year SMS.

Wednesday, December 15, 2010

Send Free Christmas SMS - atsms4u

Send Free Christmas SMS


Celebrate Your Christmas Festival by Sending Free SMS Any Where in India


We Celebrate Christmas On 25th December.

Send Free Christmas SMS of 200 Characters to any mobile phone all over India.

On 25th December, a Day to remember, a Day to praise, a Day to be Happy, a Day to sing, a Day to dance, a Day of blessing, a Day of GOD, Jesus Christ who came to this world for us.

Out in the fields, an angel of the Lord appeared to the shepherds who were tending their flocks of sheep by night. The angel announced that the Savior had been born in the town of David.

Suddenly a great host of heavenly beings appeared with the angels and began singing praises to God. As the angelic beings departed, the shepherds decided to travel to Bethlehem and see the Christ-child.

ATSMS4U.COM provides you a Simple and Easy User Interface for Sending Quick Christmas SMS.

So this is how it goes on and we the Team ATSMS4U celebrate this day with Great Passion and Happiness.

Then within a week we have a New Year coming, as Night Ends and Day Follows, as Sorrows leaves us and Happiness enters, as Questions goes and Answers comes in, as Darkness ends and Light flashes, as Old dies and New take Birth, We have a new start, new hope, new day to start all over again.

Simply a New Start which says life has given us one more chance to gain which we lost in last year or to achieve which is just a dream.

You can also Send Free SMS  to more than one Mobile Number,Create Contact List and Groups which helps you to have your own Phone book or Phone Directory.

Set Schedule message at your Time and It will be sent to that Number even if you are not online.

Many Categories of message’s like Friendship, Love, Shayari, Joke, Fun, Valentine and Many more instant Season free messages available in Quick Free SMS Template.

Enjoy your Christmas and New Year with ATSMS4U by sending Free Christmas SMS of 200 Characters.

please visit www.atsms4u.com

Friday, December 3, 2010

Top 10 Interview Questions on OOPS

Top 10 .Net Interview Questions and Answers on OOPS

1. What is an Object in OOPS?
An object is a software bundle of variables and related methods. Objects are related to real life scenario. Class is the general thing and object is the specialization of general thingObjects is instance of classes.




Declaration of an Object in OOPs
ClassName objectName=new ClassName();
E.g.: Person objPerson= new Person();
An object is characterized by concepts like:
•            Attribute
•             Behavior
•             Identity




2.   What is an Attribute in OOPs?
•        Attributes define the characteristics of a class.
•        The set of values of an attribute of a particular object is called its state.
•        In Class Program attribute can be a string or it can be a integer



3.    What is a Behavior in OOPS?
•        Every object has behavior
•        In C#, behaviors of objects are written in methods.
•        If a behavior of an object needs to be performed, then the corresponding method is called.




4.    What is an Identity in OOPS?
•        Each time an object is created the object identity is been defined.
•        This identity is usually created using an identifier which is derived from the type of item


 
5.     What is Encapsulation in OOPS?
•        Encapsulation is one of the fundamental principles of object-oriented programming.
•        Encapsulation is a process of hiding all the internal details of an object from the outside world
•        Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
•        Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class
•        Encapsulation gives us maintainability, flexibility and extensibility to our code.
•        Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.
•        Encapsulation provides a way to protect data from accidental corruption
•        Encapsulation hides information within an object
•        Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods
•        Encapsulation gives you the ability to validate the values before the object user change or obtain the value
•        Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.


There are two ways to create a validation process.
1.            Using Assessors and Mutators
2.            Using properties


Benefits of Encapsulation
•  In Encapsulation fields of a class can be read-only or can be write-only
•  A class can have control over in its fields
•  A class can change data type of its fields anytime but users of this class do not need to change any code



6.  What is Inheritance in OOPS?
•    Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (concept) of object-oriented programming
•   Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes
•  The Class whose methods and variables are defined is called super class or base class
•  The Class that inherits methods and variables are defined is called sub class or derived class
•  Sometimes base class known as generalized class and derived class known as specialized class
•   Keyword to declare inheritance is “:” (colon) in visual c#


Benefits of using Inheritance
•    Once a behavior (method) or property is defined in a super class(base class),that behavior  or property is automatically inherited by all subclasses (derived class).
•     Code reusability increased through inheritance
•     Inheritance provide a clear model structure which is easy to understand without much complexity
•   Using inheritance, classes become grouped together in a hierarchical tree structure
•   Code are easy to manage and divided into parent and child classes



7. What is Polymorphism in OOPS?
•    Polymorphism is one of the primary characteristics (concept) of object-oriented programming
•   Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details
•    Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form
•    Polymorphism is the ability to process objects differently depending on their data types
•    Polymorphism is the ability to redefine methods for derived classes.


Types of Polymorphism
•   Compile time Polymorphism
•    Run time Polymorphism


8. What is Compile Time Polymorphism in OOPS?
•   Compile time Polymorphism also known as method overloading
•    Method overloading means having two or more methods with the same name but with different signatures


9. What is Run Time Polymorphism in OOPS?
•  Run time Polymorphism also known as method overriding
•  Method overriding means having two or more methods with the same name , same signature but with different implementation


10. What is Access Modifier in OOPS?
Access modifiers determine the extent to which a variable or method can be accessed from another class or object
The following five accessibility levels can be specified using the access modifiers
•  Private
•  Protected
•  Internal
•  Protected internal
•  Public

Tuesday, November 30, 2010

Questpond .Net Interview Questions on Garbage Collection

Garbage Collection in .Net

.Net Framework's -Memory Management Garbage Collector which manages allocation and release of memory from application.Now developers no need to worry about memory allocated for each object which is created on application . garbage collector automatically manages memory on application

I would like share this horrible experience which I faced in one of the big IT multinational company. Even though I have 8 years of experience, I flunked very badly and I flunked due to 1 topic "Garbage collector". I hope the below discussion will help some one down the line when facing c sharp and dot net interviews. I just hope dot net interviews get more matured down the line and ask practical questions rather than asking questions which we do not use on day to day to basis.
The interviewer started with a basic question which I knew pretty well
What is a garbage collector?
Garbage collector is a background process which checks for unused objects in the application and cleans them up.
After that answer my guess was the interviewer will not probe more....but fate turned me down , came the bouncer.
What are generations in garbage collector?
Generation define the age of the object.
Well i did not answer the question , i have just written down by searching in google....
How many types of Generations are there in GC garbage collector?
There are 3 generations gen 0 , gen 1 and gen 2.
Then came a solid tweak questions which i just slipped by saying Yes...
Does garbage collector clean unmanaged objects ?
No.
Then came the terror question...which i never knew...
When we define clean up destructor , how does it affect garbage collector?
If you define clean up in destructor garbage collector will take more time to clean up the objects and more and more objects are created in Gen 2..
How can we overcome the destructor problem ?
By implementing "Idisposable" interface.
The above question was tricky , you can search in google for finalize and dispose patterns.
Where do we normally put unmanaged code clean up?.
In finalize a.k.a destructor.
One thing i learnt from this interview experience is one thing but we also should know core concepts in detail to crack Dot net interviews .
By ShivPrasad Koirala
For more Queries please visit : http://www.questpond.com

Thursday, November 25, 2010

C# and .NET interview questions and answers around global assembly cache (GAC)

C# and .NET interview questions and answers around global assembly cache (GAC)

for more visit :www.questpond.com


One of the most asked questions in .NET interviews are around assembly and GAC. Most of the times .NET developers get confused with these questions. Below are some of the question which keeps coming from GAC perspective.

Interviewer normally starts with what is GAC?
GAC is a central repository folder where you can share your DLL among different applications running in the same computer. So for example you have accounting and invoicing application running in the same computer and both these application need some common utility like the logging DLL then you need to register them in GAC and share them.

If you are able to answer the top interview questions the next question can be on versioning.
If we have different versions of DLL in GAC how can the application identify them?

This is done by using binding redirect and specifying older version and new version value. So which ever version you put in the new version will be used by the application.
The other question can come from the perspective of how you can register a DLL in GAC. Interviewer expectation is that you do not just talk about GACUTIL but you need talk more realistic.

What are the various ways by which you can register a DLL in GAC?

We can use the GACUTIL tool to register the DLL in GAC.

But when we talk about application they have 100 of DLL’s so how feasible is GACUTIL tool?

We need to create installation package which will register the DLL in GAC.

If we do not have strong name can assembly be registered in GAC?
This is again a catchy question which is testing do you know the pre-requisites to register DLL in GAC. No, you cannot register DLL in GAC without strong names.

How do we create strong named DLL?

By using SN.EXE or by going to the project properties and making the assembly string named.

So next time you face a question in GAC in C# and .NET interviews understand the above twist and twirls. Happy job hunting.