Pages

SPONSORED

Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Custom Entity Classes

There are too many discussions on multiple sites on why custom entities, custom entites vs data sets etc. In my view every solution has its own advantages and disadvantages. However in this blog, i prefer to discuss on custom entities and i speak in favour of custom entities.

What are custom Entities?
Custom entities are objects, just like some other objects which represent the business domain. They map the data to our application business. If i have to explain in simple .Net terms, custom entities are classes which have properties. This is typically used in n tier architecture.

For example, if we are developing an application on online shopping we can have entity like product which becomes our class. It can have properties like product name, cost, discount, size, weight etc.

'Visual Basic .NET
Public Class Product
#Region "Fields and Properties"
 Private _weight As Integer
 Private _productName As String
 Private _size As Integer
 Public Property Size() As Integer
  Get
   Return _size
  End Get
  Set(ByVal Value As Integer)
    _size = Value
  End Set
 End Property
 Public Property ProductName() As String
  Get
   Return _productName
  End Get
  Set(ByVal Value As String)
   _productName = Value
  End Set
 End Property
 Public Property Weight() As Integer
  Get
   Return _weight
  End Get
  Set(ByVal Value As Integer)
   _weight = Value
  End Set
 End Property
#End Region

#Region "Constructors"
 Public Sub New()
 End Sub
 Public Sub New( name As String, size As Integer, weight as Integer)
  Me.ProductName = name
  Me.Size = size
  Me.Weight = weight
 End Sub
#End Region
End Class

Why Custom Entities?
Custom entities are -

·         Object oriented. DataSets are not object oriented. We cannot add functionality to it. For example, if we need to change the format of some string before displaying on the screen, we will need to do it every time we display. If we use custom entity we can do this in the setter of the corresponding property.
·         More maintainable. Datasets lack abstraction which means they are tightly coupled with data model. If we use them in presentation layer and column definition changes from back end we will need to make changes to all our layers. This makes enhancements and bug fix difficult.
·         Strongly Typed. What i mean is, they are detected during compile time as we will have the entity class defined with us. DataSets are weakly types and any errors in them are detected only during run time.
·         More Secure. If we are sharing our API with any third party developers, it is better we do not expose our underlying structure. Custom Entity hide our data model and show only the business view of it. Hence it is mostly preferred when we have web services. Another point to note here is that the datasets are not optimised on serialization as well.
·         Developer Friendly. Custom Entities will get the help if intellisense and become easier to code. We don’t even need to track the column index or names, all are business friendly.

Decision to use custom entity or datasets should not be based on the theoretical concepts we read. Multiple factors must be considered like memory available, objects created etc. No design can be tagged good or bad. Good design is the one which considers all the functional and non functional aspects around the application.

Abstract class and Interface

Abstract Class
Abstract class is a class which cannot be instantiated. We need to inherit this class and then instantiate the child class. Abstract class always acts as base class and contains one or more abstract or non abstract methods. An abstract method is a method that has only definition but not implementation. The child class must provide the definition for all the abstract method of its parent. However if it does not provide the implementation then the child class too must be declared abstract.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

Example
Consider implementing the shapes available under Insert > Shape option of a word document. Some of the properties like fill, border, line style etc are common among all shapes. However other properties must be implemented separately.


We create an abstract class Shape. It is declared abstract as we do not intend to instantiate as shape in general makes no sense. Then create sub classes rectangle, triangle, circle etc.

Interface
Interfaces are used to separate implementation and definitions. It comes to use when the implementations need to be interchangeable and also in cases where the implementation changes frequently.

Interfaces define a generic template and just have method declaration and might contain properties. These method declarations are implicitly public and abstract. Interfaces cannot be instantiated. Interfaces can inherit other interfaces.

A class can implement the interface and implement the methods as per requirement. Each class which implements the interface can implement the method in its own way and can reflect the expected behaviour as per requirement.

In case the class does not implement all the methods from the interface then the class must be declared abstract. This class must be further extended to sub class and implementation must be provided in that sub class. This sub class can be later instantiated and put into use.

Interface definition
public interface Shape
{
//Can have any function which a shape required to be implemented
function area();
}

Implementing the interface
public circle implements shape
{
//Implement the area as required for circle
Function area()
{
                    //calculate area of circle
}
}


The below link has detailed explanation on when to use abstract class and interfaces

 

Composition and Aggregation

Composition
Composition expresses relationship between objects. It is an association in which one class belongs to a collection. The containing object is responsible for the life time of the object it holds within it. The containing object cannot exist without the main object. It expresses the “has a” relationship among the objects

Example:  Office has a reception, Student has a name, Car has a tyre etc.

Aggregation
It is relationship which is just a reference between objects. The objects are independent of each other.

Example: Chair and person, Chair does not own the person.
Employee and address, address stays even after employee is destroyed.

The table below lists the key differences between composition and aggregation

Composition
Aggregation
Relationship where a part cannot exist without whole
Relationship where a part can exist without whole
Stronger relationship
Weaker relationship
Main object owns the containing objects
Objects are independent of each other
Main object instantiated the containing objects
Objects within the relationship are instantiated independently
Containing objects are destroyed when main object is destroyed
If one object is destroyed other object can survive.




What do you mean by Encapsulation?

As the name suggests Encapsulation means keeping all the objects data is contained together within the object. Data of object here refers to its variables and methods. Object hides the inner implementation from the outside view. Encapsulation controls interactions of objects. It prevents object interaction in unexpected way. This improves code modularity as well as improves application security.
 
Encapsulation Example


Class Product{
private double cost = 0.0;

public void setCost(double cost){
if(cost > 0)
this.cost = cost;
else
throw new Exception("No negative Values for Cost");
}

public int getCost(){
return cost;
}
}

The sample code above shows how the value of cost of the product is controlled. The value of cost can be set only via setCost method which takes care to avoid negative values to be set for the variable.Secure member can be modified in this manner and can be helful to control the code from insecure access.

Access modifiers are keywords used to specify the declared accessibility of a member or a type. The following are access modifiers for C++, C# and Java.
C# and C++
Public: All Objects can access it.
Protected: Access is limited to members of the same class or descendants.
Private: Access is limited to members of the same class.
Internal: Access is limited to the current assembly.
Protected Internal: Access is limited to the current assembly or types derived from the containing class.

The first 3 access levels are available both in C# and C++. But the last 2 are available only in C#.

Java
Public: All Objects can access it.
Protected: Access is limited to members of other classes within the same package or descendants.
Private: Access is limited to members of the same class.
No Modifier: Access is limited to the current package.

Benefits
Maintainability: Encapsulation helps increases the maintainability of the code and reduces the refactoring effort.
Security: It increases security by avoiding objects interaction in unexpected way. This will protect the variables from unaccepted values.

Static Blocks or Static Constructors

As the name suggests static blocks are used to initialise the static fields of the class.

·         These blocks or methods get executed only once for a class.
·         They are executed even before the constructors are executed.
·         The static fields with initializes in declaration will get executed before the  static blocks.
·         They are triggered when any of the following events occur:
o   An instance of the class is created.
o   If any of the static members of the class is accessed.


 The implementation of this is slightly different in Java and C#.

In Java
All blocks that are declared static are executed when a class is loaded. Static blocks in Java do not have a function name.

public class StaticBlockExample {
public static final int abc = 20;
public static final int def;

//Static block to initialise the static variable def
static {
          if(abc == 20)
def = 10;
else
def = 15;
}
//Constructor gets executed after static block is executed
public StaticBlockExample (){}
}


In C#
Static blocks are called as Static Constructors in C#. They are declared using static constructor declarations.

public class StaticBlockExample
{
static int abc = 20;
static int def;

  static StaticBlockExample ()
  {
if(abc == 20)
def = 10;
else
def = 15;
   }
}

What do you mean by Inheritance?

Inheritance is a process through which one object can inherit the characteristics of another object. This is similar to the parent-child relationship in real time scenario where a child can inherit the characteristics of parent.

Inheritence  helps in setting up relationships among objects and can help in reusing of code. Implementations of the parent can be simply inherited by the child. The child need not re-implement the functionality unless any change in behaviour is expected.This also impleves maintainability by avoiding duplication of code and hence reduces defects as well as development time. This in turn can improve code quality.

In inheritance, objects are defined by classes. The existing class is also called as– super class, parent class, base class and ancestral class. The inherited class is called as – sub class, child class, heir class or derived class.

 
Inheritence can be depicted by a simpe example -
To represent different kinds of geometric shapes, such as circles or rectangles programmatically we can use inheritance. We can create separate classes for each shape, but these different kinds of shapes share a number of things in common. We can define a type called "Shapes" to represent any of these different kinds of figures (circles or rectangles). We could then say that circles and rectangles are a kind of figure. A given type includes all of the record components specific to it, plus all the record components of its ancestors, so a square has all the information a rectangle would.

We'll also need to define some operations on these types, such as "Draw", "Area", and "Perimeter". Each calculated in a different way for each of the shape. Pictorial representation of this example is shown below.



Inheritance Example
 
 
We have seen how and when to use inheritence. We have also discussed its advantages. This does not mean that we implement inheritence in all scenarios. Do not use inheritence just for the sake of reuse. Avoid using it if there is no sub type relationship. Overuse of implementation inheritance can break all the subclasses, if the superclass is modified. Use composition for code reuse in such cases.

Quality of code can be achieved when the developer is smart enough to decide on the feature to put into use from OOP.

What do you mean by Polymorphism?

 Polymorphism, as the name suggest represents many forms.["Poly" means many, and "morph" means form].Polymorphism allows methods to behave differenlty in different situations depending on the input/scenario.The polymorphic method methods behaves in the same consistent manner with all the communicating objects even though their implementations varies.

In polymorphism the behaviour of method is decided during run time depending on the type of input passed to the method. The process used by object-oriented programming languages to implement polymorphism is called dynamic binding.


Polymorphism Example
 Polymorphism can be implemented with inheritence. Base class must have virtual methods defined and implemented. Child Class can override these virtual methods by providing their own implementation as per requirement.During run time the complier decides the implemetation to be executed depending upon the type of the object requesting the execution. Thus calling the method of the base class causes the execution of the required child class.

Visit http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C
for more details on implementation and real time examples on Polymorphism.

Note : In C#, every type is polymorphic. This is because all types, including user-defined types is inherited from Object.

Why do we need object oriented programming?

The Object Oriented Programming Languages directly represent the real life objects like Automobile, Flower, Pen etc. The most used  and powerful features of OO programming are polymorphism, inheritance and encapsulation.
[Tip to remember : PIE - Polymorphism, Inheritence and Encapsulation.].

Benefits of OOP

Reusable: Using the concept of inheritance the implementation of other class can be used. For example, if we have a to create classes for birds, we can have a prent class Bird which can implement functionality fly(). This functionality remains same for all child bird classes which inherit the parent class Bird.

Simple: OOP represents the real life objects. This real mapping easy understanding, reduction of complexity and makes the program structure simpler.

Modular: Usage of objects, classes etc helps in clubbing the relevent functinality together. This helps in easy understanding if the system and also makes the implementation independent of each other. This makesThis in turn will make it very easy to modify the system when required.  
Maintainable: It becomes very easy to make minor changes to the system as this approach is modular and is loosely coupled. The entire system need not be modified to incorporate the changes and hence reduces the development time.
Extensible: It is specified that the system becomes loosely coupled. This makes it easy to plug in more features to the system. This way we can extend the application to provide more features to the user. 
Summary
Considering the above points we can conclude that using OOP can definetly help us in providing quality code. This can be achieved as we will be able to reuse the code which helps us avoid code and test the reuse sections. This not only helps us in reducing the defects but can also reduces the development time.

Maintainence of the application becomes very easy as OOP is more extensible, reusable and modular.