Showing posts with label OOPs. Show all posts
Showing posts with label OOPs. Show all posts

Saturday, June 15, 2013

When to Use Inheritance?

Reference: http://msdn.microsoft.com/en-us/library/27db6csx%28v=vs.90%29.aspx
Inheritance is a useful programming concept, but it is easy to use inappropriately. Often interfaces do the job better. This topic and When to Use Interfaces help you understand when each approach should be used.
Inheritance is a good choice when:
<![if !supportLists]>·         <![endif]>Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
<![if !supportLists]>·         <![endif]>You can reuse code from the base classes.
<![if !supportLists]>·         <![endif]>You need to apply the same class and methods to different data types.
<![if !supportLists]>·         <![endif]>The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
<![if !supportLists]>·         <![endif]>You want to make global changes to derived classes by changing a base class.
These considerations are discussed in order below.

Inheritance and "Is a" Relationships


Two ways to show class relationships in object-oriented programming are "is a" and "has a" relationships. In an "is a" relationship, the derived class is clearly a kind of the base class. For example, a class named PremierCustomer represents an "is a" relationship with a base class named Customer because a premier customer is a customer. However, a class named CustomerReferral represents a "has a" relationship with the Customer class because a customer referral has a customer, but a customer referral is not a kind of customer.
Objects in an inheritance hierarchy should have an "is a" relationship with their base class because they inherit the fields, properties, methods, and events defined in the base class. Classes that represent a "has a" relationship with other classes are not suited to inheritance hierarchies because they may inherit inappropriate properties and methods. For example, if the CustomerReferral class were derived from the Customer class discussed previously, it might inherit properties that make no sense, such as ShippingPrefs and LastOrderPlaced. "Has a" relationships such as this should be represented using unrelated classes or interfaces. The following illustration shows examples of both "is a" and "has a" relationships.

Base Classes and Code Reuse


Another reason to use inheritance is the advantage of code reuse. Well-designed classes can be debugged once and used over and over as a basis for new classes.
A common example of effective code reuse is in connection with libraries that manage data structures. Suppose, for example, that you have a large business application that manages several kinds of in-memory lists. One is an in-memory copy of your customer database, read in from a database at the beginning of the session for speed. The data structure might look something like the following:
VB
Class CustomerInfo
    Protected PreviousCustomer As CustomerInfo
    Protected NextCustomer As CustomerInfo
    Public ID As Integer 
    Public FullName As String 
 
    Public Sub InsertCustomer(ByVal FullName As String)
        ' Insert code to add a CustomerInfo item to the list. 
    End Sub 
 
    Public Sub DeleteCustomer()
        ' Insert code to remove a CustomerInfo item from the list. 
    End Sub 
 
    Public Function GetNextCustomer() As CustomerInfo
        ' Insert code to get the next CustomerInfo item from the list. 
        Return NextCustomer
    End Function 
 
    Public Function GetPrevCustomer() As CustomerInfo
        'Insert code to get the previous CustomerInfo item from the list. 
        Return PreviousCustomer
    End Function 
End Class
Your application may also have a similar list of products the user has added to a shopping cart list, as shown in the following code fragment:
VB
Class ShoppingCartItem
    Protected PreviousItem As ShoppingCartItem
    Protected NextItem As ShoppingCartItem
    Public ProductCode As Integer 
    Public Function GetNextItem() As ShoppingCartItem
        ' Insert code to get the next ShoppingCartItem from the list. 
        Return NextItem
    End Function 
End Class
You can see a pattern here: two lists behave the same way (insertions, deletions, and retrievals) but operate on different data types. Maintaining two code bases to perform essentially the same functions is not efficient. The most efficient solution is to factor out the list management into its own class, and then inherit from that class for different data types:
VB
Class ListItem
    Protected PreviousItem As ListItem
    Protected NextItem As ListItem
    Public Function GetNextItem() As ListItem
        ' Insert code to get the next item in the list. 
        Return NextItem
    End Function 
    Public Sub InsertNextItem()
        ' Insert code to add a item to the list. 
    End Sub 
 
    Public Sub DeleteNextItem()
        ' Insert code to remove a item from the list. 
    End Sub 
 
    Public Function GetPrevItem() As ListItem
        'Insert code to get the previous item from the list. 
        Return PreviousItem
    End Function 
End Class
The ListItem class needs only to be debugged once. Then you can build classes that use it without ever having to think about list management again. For example:
VB
Class CustomerInfo
    Inherits ListItem
    Public ID As Integer 
    Public FullName As String 
End Class 
Class ShoppingCartItem
    Inherits ListItem
    Public ProductCode As Integer 
End Class
Although inheritance-based code reuse is powerful tool, it also has associated risks. Even the best-designed systems sometimes change in ways the designers could not foresee. Changes to an existing class hierarchy can sometimes have unintended consequences; some examples are discussed in "The Fragile Base Class Problem," in Base Class Design Changes After Deployment.

Interchangeable Derived Classes


Derived classes in a class hierarchy can sometimes be used interchangeably with their base class, a process called inheritance-based polymorphism. This approach combines the best features of interface-based polymorphism with the option of reusing or overriding code from a base class.
An example where this can be useful is in a drawing package. For example, consider the following code fragment, which does not use inheritance:
VB
Sub Draw(ByVal Shape As DrawingShape, ByVal X As Integer, _
    ByVal Y As Integer, ByVal Size As Integer)
 
    Select Case Shape.type
        Case shpCircle
            ' Insert circle drawing code here. 
        Case shpLine
            ' Insert line drawing code here. 
    End Select 
End Sub
This approach poses some problems. If someone decides to add an ellipse option later, it will be necessary to alter the source code; it is possible that your target users will not even have access to your source code. A more subtle problem is that drawing an ellipse requires another parameter (ellipses have both a major and a minor diameter) that would be irrelevant to the line case. If someone then wants to add a polyline (multiple connected lines), then another parameter would be added, and it would be irrelevant to the other cases.
Inheritance solves most of these problems. Well-designed base classes leave the implementation of specific methods up to the derived classes, so that any kind of shape can be accommodated. Other developers can implement methods in derived classes by using the documentation for the base class. Other class items (such as the x- and y-coordinates) can be built into the base class because all descendants use them. For example, Draw could be a MustOverride method:
VB
MustInherit Class Shape
    Public X As Integer 
    Public Y As Integer 
    MustOverride Sub Draw()
End Class
Then you could add to that class as appropriate for different shapes. For example, a Line class might only need a Length field:
VB
Class Line
    Inherits Shape
    Public Length As Integer 
    Overrides Sub Draw()
        ' Insert code here to implement Draw for this shape. 
    End Sub 
End Class
This approach is useful because other developers, who do not have access to your source code, can extend your base class with new derived classes as needed. For example, a class named Rectangle could be derived from the Line class:
VB
Class Rectangle
    Inherits Line
    Public Width As Integer 
    Overrides Sub Draw()
        ' Insert code here to implement Draw for the Rectangle shape. 
    End Sub 
End Class
This example shows how you can move from general-purpose classes to very specific classes by adding implementation details at each level.
At this point it might be good to reevaluate if the derived class truly represents an "is a" relationship, or instead is a "has a" relationship. If the new rectangle class is just composed of lines, then inheritance is not the best choice. However, if the new rectangle is a line with a width property, then the "is a" relationship is maintained.

Shallow Class Hierarchies


Inheritance is best suited for relatively shallow class hierarchies. Excessively deep and complex class hierarchies can be difficult to develop. The decision to use a class hierarchy involves weighing the benefits of using a class hierarchy against complexity. As a general rule, you should limit hierarchies to six levels or fewer. However, the maximum depth for any particular class hierarchy depends on a number of factors, including the amount of complexity at each level.

Global Changes to Derived Classes Through the Base Class


One of the most powerful features of inheritance is the ability to make changes in a base class that propagate to derived classes. When used carefully, you can update the implementation of a single method, and dozens—or even hundreds—of derived classes can use the new code. However, this can be a dangerous practice because such changes may cause problems with inherited classes designed by other people. Care must be taken to ensure that the new base class is compatible with classes that use the original. You should specifically avoid changing the name or type of base class members.
Suppose, for example, that you design a base class with a field of type Integer to store zip code information, and other developers have created derived classes that use the inherited zip code field. Suppose further that your zip code field stores five digits, and the post office has expanded zip codes with a hyphen and four more digits. In a worst-case scenario, you could modify the field in the base class to store a 10-character string, but other developers would need to change and recompile the derived classes to use the new size and data type.
The safest way to change a base class is to simply add new members. For example, you could add a new field to store the additional four digits in the zip code example discussed previously. That way, client applications can be updated to use the new field without breaking existing applications. The ability to extend base classes in an inheritance hierarchy is an important benefit that does not exist with interfaces.

Saturday, July 30, 2011

What are Static Constructors and how Static Constructors are invoked?

Static Constructors: A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Example :-


OUTPUT of above code :


NOTE : Static Constructors doesn't take any Access Modifier. This is rule. By default is private.

    class A
    {
        /// <summary>
        /// Static Constructors doesn't take any Access Modifier. This is rule.
        /// </summary>
        static A()
        {
            Console.WriteLine("A : Static Constructor.");
        }

       /// <summary>
        /// Default Constructor
        /// </summary>
        public A()
        {
            Console.WriteLine("A : Default Constructor.");
        }
    }

When we have static constructors in our class then it would be called first.
There can be several scenarios with static constructors.

1.       If we have static and default constructors in same class then first Static constructor would be called then Default.
2.       If we have three classes A,B,C have static constructors and are inherited in such a way C:B:A, then constructors would be invoked in following sequence :-
a.       Default Constructors would be called in A:B:C sequence. Rule is, first base class default constructor will call then derived class default constructor.
b.      Static Constructors would be called in C:B:A sequence. (Opposite to invocation of Default Constructors.). Rule is, first derived class static constructor will be called then base class static constructor.

Here is the example of the same.
Making object of class C all constructors would get invoked. First all static constructors then default constructors.


Hence we can say that :-
1.       For static constructor : First derived class static constructor will be called then base class static constructor.
2.       For default constructor : First base class default constructor will call then derived class default constructor.

Another example: 




Friday, July 29, 2011

What are association, aggregation and composition in OOPs?

Association

Association is a relationship where all object have their own life cycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own life cycle. Both can create and delete independently.
Points:
  • Is a Relationship between objects.
  • Objects have independent life cycles.
  • There is no owner.
  • Objects can create and delete independently.

Aggregation

Aggregation is a specialize form of Association where all object have their own life cycle but there is ownership and child object cannot belongs to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.
Points:
  • Specialize form of Association.
  • has-a relationship between objects
  • Object have independent life-cycles
  • Parent-Child relationship

On the other hand aggregation relation just represents reference between classes. For example consider Employee and contact information. Blow diagram represents the UML



The above UML describes Aggregation relation which mentions that Employee refers to Address. And life time of Address is not managed by Employee. It is like "Employee has a Address". Let us see how it can be implemented in C#.

public class Address
{
 . . .
}

public class Employee

{

     private Address address;

     public Employee(Address address)

     {

         this.address = address;

     }

     . . .

}

Composition

Composition is again specialize form of Aggregation. It is a strong type of Aggregation. Child object does not have their life cycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will automatically delete.
Points:
  • Specialize form of Aggregation.
  • Strong Type of Aggregation.
  • Parent-Child relationship.
  • Only parent object has independent life-cycle.

Lets take a simple example of Cycle. Cycle should contain 2 tyres and if we convert it to logical model below is the UML diagram




The above UML describes that Cycle contains 2 Tyres and the life time of each Tyre is maintained by Cycle. It is like "Tyre is Part Of Cycle". Let us see how it can be implemented in C#.

public class Tyre
{
 . . .
}

public class Cycle

{

    Tyre[] tires = new Tyre[]{new Tyre(), new Tyre()};

    .......

}

Have a grate day.

Encapsulation vs abstractions

“Abstraction and encapsulation are not synomous,” says P.J. Plauger in Programming on Purpose.



Encapsulation is information hiding. In other words: "Information hiding allows for implementation of a feature to change without affecting other parts that are depending on it.”
Encapsulation is a process where you group all data and methods (way to process data) together under an umbrella. This is a kind of normalization that we do on the object and its behavior.
Also, Encapsulation can be defined as the procedure of packing data and operations that operate on them into a single entity. This means that to access data, certain predetermined methods should be used. In other words, the data contained are not directly accessible. This ensures that data integrity is preserved because the user is unable to directly approach and modify the data as he / she wants. Users will receive or will the data values ​​only by methods that are publicly available to users.


Abstraction: Look at it as “what” the method or a module does not “how” it does it.
Definition: “The notion abstraction is to distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language.”
Abstraction is the way to hide complex implementation from outer world. For example: List.Sort() will sort the list and will give back the sorted list. User need not to worry about what algorithm the Sort() function has used. Object oriented programming/language offers this kind of abstraction.
Abstraction is the process of separating the details of presentation of the implementation details. This is done so that the developer is relieved of the complex details about implementation. The programmer can instead concentrate on the presentation or details of behavior of the entity. In simple terms, the abstraction focuses how a certain entity can be used rather than how it is executed. The abstraction hides the implementation details essentially, that even if the implementation methodology completely changes the time, the programmer should not worry how it would affect his program.

·         Encapsulation protects abstraction.
·         Encapsulation is the bodyguard, Abstraction is the VIP.
S.No.
Abstraction
Encapsulation
1
VIP
Assistant
2
Technically abstraction is like use of methods in a class by creating an object of that class, and u no need to know how the these methods are defined and worked
Encapsulation keeps code and data, it manipulates, safe from the outside code, i.e. it work like a wrapper for the inside code.
3
Abstraction is showing only essential details.
Encapsulation is hiding the working of abstraction in a class or template
4
Example:
A real world example, consider u have setup a big building(say a company), the details regarding materials used to build (glass, bricks), type of work, manager of the company, number of floors, design of the building, cost of the building etc. can be classified as ABSTRACTION.
Whereas, type of glass or bricks (grey one or red one) used, who all work for which all departments n how they work, cost of each and every element in the building etc. comes under Data ENCAPSULATION.
5
Outer layout, used in terms of design.
Inner layout, used in terms of implementation.
6
Abstraction provides business value; encapsulation "protects" these abstractions. If a developer provides a good abstraction, users won't be tempted to peek at the object's internal mechanisms. Encapsulation is simply a safety feature.
Encapsulation provides the explicit boundary between an object's abstract interface (its abstraction) and its internal implementation details.
7
In order to process something from the real world we have to extract the essential characteristics of that object.

Data abstraction can be viewed as the process of refining away the unimportant details of an object, so that only the useful characteristics that define it remain. Evidently, this is task specific.
Encapsulation is one step beyond abstraction. Whilst abstraction involves reducing a real world entity to its essential defining characteristics, encapsulation extends this idea by also modeling and linking the functionality of that entity. Encapsulation links the data to the operations that can be performed upon the data.

Abstraction has the methods which will be common for all the derived class would need. It contains the skeleton which needs to be implemented by the derived class also, which will be declared as abstract method.

Example:

abstract class CurryBase
{
public abstract void doCurryMasala();
}

public class FishCurry : CurryBase
{
public void doCurryMasala()
{
// Add Fish Curry specific contents also.
}
}
Encapsulation is basically, wrapping up of data members and methods.
As you said, You hide the data for security such as making the variables as private, and expose the property to access the private data which would be public. So, when you access the property you can validate the data and set it.

Example:

Class Demo
{
private int _mark;

public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Have a nice day ahead.