Microsoft Student Partner (MSP) Capacity Build up Training (Session 02)

Microsoft Student Partner (MSP) Capacity Build up Training (Session 02)
Course Title: Object Oriented Programming with C#
Venue: East West University, Dhaka, Bangladesh
Date: 11 June, 2016
Speaker / Trainer: Md. Mahedee Hasan,
Microsoft MVP, Visual Studio and Development Technologies
Software Architect, Leadsoft Bangladesh Limited

First class of C#.NET Applied OOP Training (Batch – 04)

First class of C#.NET Applied OOP Training (Batch – 04) on 27August 2015
Training Title: C#.NET Applied OOP
Organized by: Bangladesh Hi-Tech Park Authority (BHTPA) and Leads Technology Limited
Total Duration: 144 Hours
Trainer: Md. Mahedee Hasan

Open Close Principle with C#

Open Close Principle is an Object Oriented Design principle. It is first introduced by Betrand Meyer in 1988. He says “Software entities (Class, module, function etc.) should be open for extension, but closed for modification”. An entity is “Open for extension” means that its behavior can be extended to accommodate new demand. The entity is “closed for modification” means that the existing source code of the module is not changed or minimum change when making enhancement. It is clear that if a system cannot accommodate change easily, its life cycle will end fast.

Sometimes code changes introduce heavy risk. At the time of changing, you must ensure that changes will not break the system. Sometimes it takes huge regression testing. This risk can be minimized if no changes are made to existing code.

So, our intention should be writing code in such a way that new functionality should be added with minimum changes or not changes in the existing code.  It should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged. The major advantages of “open close principle” is that it undergo changes and its value will be tremendous. It required almost no regression testing.

Let’s introduce open close principle with an example. Suppose, in our application, we need a “Area calculator” which calculate area of rectangle. However, in this occasion we just create a class AreaCalculator then there will be a method RectangleArea in this class which just calculates area of rectangle. It works fine. In the middle of the application development, we need to calculate area of Triangle and Circle. In this occasion, what should we do? We just add another two method TriangleArea and CircleArea and can do the job. But several problems will arise here – for each new shape you have to add new unit of code. Developer must have to know the logic to calculate area of new shape. Adding a new shape might effect in existing functionalities. So, it will take huge cost of regression testing. This is actually violate, open close principle.

We implement the same problem abide by open close principle by the following way. Here Rectangle, Triangle and Circle class inherit the Shape class and implement CalculateArea Method. In this way, if you need to calculate area of x shape just add a class of x and then implement shape and calculate area of x without modifying exiting code.

Class diagram:

OCP class diagrm

Open Close Principle Implementation by C#:

Step 1: Create abstract Shape class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public abstract class Shape
{
public abstract double CalculateArea();
}
}

Step 2: Create Rectangle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Rectangle : Shape
{
public double Height { get; set; }
public double Width { get; set; }

public Rectangle(double height, double width)
{
this.Height = height;
this.Width = width;
}

public override double CalculateArea()
{
return Height * Width;
}
}
}

Step 3: Create Triangle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Triangle : Shape
{
public double Base { get; set; }
public double Height { get; set; }

public Triangle(double vbase, double vheight)
{
this.Base = vbase;
this.Height = vheight;
}

public override double CalculateArea()
{
return 1 / 2.0 * Base * Height;
}
}
}

Step 4: Create circle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Circle : Shape
{
public double Radius { get; set; }

public Circle(double radius)
{
this.Radius = radius;
}

public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
}

Step 5: Client class which uses Rectangle, Triangle and Circle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Program
{
public static void Main(string[] args)
{
Shape objShape = new Rectangle(20, 30);
Console.WriteLine("Area of Rectangle: " + objShape.CalculateArea());

objShape = new Triangle(20, 30);
Console.WriteLine("Area of Triangle: " + objShape.CalculateArea());

objShape = new Circle(4);
Console.WriteLine("Area of Circle: " + objShape.CalculateArea());

Console.ReadKey();
}
}
}

Abstract Class and Method with C# – A detail description

What is Abstract Class?

Abstract class is a class that has no direct instances, but its descendants may have direct instances.  An abstract class is a class that can contain abstract members, although it is not required. But any class that contains abstract member must be abstract. An abstract class can also contain non-abstract members.

An abstract method is an empty method – a method that has no implementation. Any class that implement this abstract class must implement the abstract method. We always use interface in C#, it is implicitly abstract.

Why abstract class?

The purpose of an abstract class is to act as a base class. It is not possible to instantiate an abstract class directly, nor can an abstract class be sealed. Often we need a class that contains methods that must be implemented by all derived classes but not by the base class itself. By this, actually we force the programmer to implement base class methods. Think a simple scenario. Suppose we want to develop a banking software. Here a common entity is account information. There are many type of account like savings account,  current account e.t.c in bank. In every account two things is common that is deposit and withdraw. So we can create a Account class as base class which must have this two method deposit and withdraw and it will be abstract method and the Account class will be abstract class. So, you can say – why its will be abstract class and abstract method? Answer of the first question is if there is any abstract member in the class, the class must be abstract. Answer of the second question, in every type of accounts two things is common deposit and withdraw but their way of transaction may be different. We just want to enforce the programmer to implement the methods if the create any class by inheriting the Account class

Syntax

The syntax for creating an abstract method is – use the abstract modifier with the name of the method and the parameters, followed by a semicolon by keeping it empty. It will be look like this.

[access-modifiers] abstract return-type method-name ([parameters]) ;

Example:

The following example shows how to create an abstract class Account with two abstract methods Deposit and Withdraw.

public abstract class Account
{
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

The benefit of creating abstract methods is that it enables you to add methods to your base class that subsequently must be implemented by all derived classes, but the implementation details for these methods do not have to be defined in the base class.

Override the abstract class
When a derived class inherits an abstract method from an abstract class, it must override the abstract methods. This requirement is enforced at compile time.
The following example shows how a SavingsAccount class, which is derived from Account, uses the override keyword to implement the Deposit and Withdraw method. Here first (Account) class is base class and second (SavingsAccount) is derived class.

///
/// Base class
///
public abstract class Account
{
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

///
/// Derived class
///
public class SavingsAccount : Account
{

//override the base class
public override string Deposit(double money)
{
return "AC type savings: Deposit transaction done sucessfully";
}

public override string Withdraw(double money)
{
return "AC type savings: Withdraw transaction done sucessfully";
}
}

After creating instance of SavingsAccount, if you call Deposit and withdraw method you will see the following output:
AC type savings: Deposit transaction done sucessfully
AC type savings: Withdraw transaction done sucessfully

Abstract class with virtual method:
You can also create an abstract class that contains virtual methods, as shown in the following example:

///
/// Base class
///

public abstract class Account
{
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

In this case, a derived class does not have to provide an implementation of the BankName method because BankName is defined as virtual. Therefore, I say the important thing again, if you have a generic method that is common to all derived classes, and you want to force each derived class to implement the method, you must define the method as abstract in the base class.

Difference between an abstract method & virtual method:

Virtual method has an implementation and provides the derived class with the option of overriding it. Abstract method does not provide an implementation and forces the derived class to override the method.

Abstract Properties:

Properties may also be declared as abstract. Same as abstract method, to declare an abstract property, specify the property name and the accessors that the derived property should implement.
Example:

///
/// Base class
///

public abstract class Account
{
//Abastract property
public abstract string AccountNo { get; set; }

//Virtual Method
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

Total Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
* Author : Md. Mahedee Hasan
* Create Date : 14/04/2012
* web : mahedee.blogspot.com
*/

namespace ConsoleProgram
{

///
/// Base class
///

public abstract class Account
{
//Abastract property
public abstract string AccountNo { get; set; }

//Virtual Method
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

//Abstract Method
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

///
/// Derived class
///

public class SavingsAccount : Account
{
private string acccNo;

//override the base class
public override string Deposit(double money)
{
return "AC type savings: Deposit transaction done sucessfully";
}

public override string Withdraw(double money)
{
return "AC type savings: Withdraw transaction done sucessfully";
}

//Override base class property
public override string AccountNo
{
get
{
return acccNo;
}
set
{
acccNo = value;
}
}
}

///
/// Main class
///

class Program
{
///
/// Main Method
///
///

static void Main(string[] args)
{
SavingsAccount objSavingsAccount = new SavingsAccount();
objSavingsAccount.BankName();
objSavingsAccount.AccountNo = "0110";
Console.WriteLine("Account Number: " + objSavingsAccount.AccountNo);
string msg = objSavingsAccount.Deposit(1000);
Console.WriteLine(msg);
msg = objSavingsAccount.Deposit(500);
Console.WriteLine(msg);

}
}
}

Output:
Welcome to ABC Bank Limited
Account Number: 0110
AC type savings: Deposit transaction done sucessfully
AC type savings: Deposit transaction done sucessfully

At a glance:
· An abstract class is a generic base class.
– Contains abstract methods that must be implemented by the derived class.
· Cannot create instance of abstract class.
· Abstract class can contain no abstract members.