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.

Strategy Design Pattern with C#

Strategy design pattern is a behavioral design pattern. It is a particular software design pattern where algorithms are selected at runtime.

According to the book of Design Pattern (Gang of Four) – “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. “

The key phrases of definition are “Family of algorithms”, “encapsulate”, and “interchangeable”. Actually, Strategy Pattern encapsulates a collection of functions that do similar yet not identical jobs. Client is not bound to call fixed methods; rather it can change its strategy dynamically at run time. Client don’t call any methods directly by instantiating concrete classes. It sets its strategy via context class.

There are three main parts in strategy pattern:

  1. Strategy – An interface that defines how the algorithm will be called.
  2. Concrete Strategy – The implementation of the strategy.
  3. Context – It holds the concrete strategy.

StrategyPattern

Implementation:

Suppose you have two lists of items. Item here integer numbers. Now, if you want to search an item from either of the lists. You can use either one of the algorithms from Linear Search or Binary search. Since binary search algorithm cannot search data without sorted list, we take here a sorted list. Now the strategy of client to use which one – Binary search or linear search. Let’s implement the problem by strategy pattern using c#.

Step 1: Create an Interface for Strategy

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

namespace StrategyPattern
{
///
/// Strategy defines how algorithm will be called
///

public interface ISearchStrategy
{
int Search(int[] list, int item);
}
}

Step 2: Create concrete strategy (Linear Search)

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

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 3: Create concrete strategy (Binary Search)

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

namespace StrategyPattern
{
///
/// Concrete strategy(Binary Search Algorithm)
///

public class BinarySearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Binary Search");

int beg = 0;
int end = list.Count() - 1;
int mid = (int)((beg + end)/2);
int position = 0;

while (beg <= end && list[mid] != item)
{
if(item < list[mid])
end = mid - 1;
else
beg = mid + 1;

mid = (int)((beg + end)/2);
}

if (list[mid] == item)
position = mid;
else
position = 0;

return position;
}

#endregion
}
}

Step 4: Create a context class

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

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 5: Client class to demonstrate strategy pattern

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

namespace StrategyPattern
{
///
/// Client class
///

class Program
{
static void Main(string[] args)
{

int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

//Instance of context to follow different strategies
SearchList objSearchList = new SearchList();

objSearchList.SetSearchStrategy(new BinarySearch());
objSearchList.Search(sortedList, 4);

objSearchList.SetSearchStrategy(new LinearSearch());
objSearchList.Search(sortedList, 7);

Console.ReadLine();
}
}
}

Output:
output_strategyPattern

Properties a short explanation using C#

What Are Properties?

  • Properties are methods that protect access to class members.
  • Properties are class members that provide access to elements of an object or class.
  • Protect access to the state of object.
  •  It likes fields, but they operate much like methods.
  • The get and set statements are called accessors.
  • Fields can’t be used in Interfaces so properties are the solution.

Syntax:

        private double balance;
        public double Balance
        {
            get
            {
                return balance;
            }
            set
            {
                balance = value;
            }
        }

Example:

    public class Employee
    {
        private double salary;
        private double taxRate = 0.05;
        

        public string Name { get; set; }
        public double YearOfExp { get; set; }

        public double YearlyMedicalAllowance {get; private set;}

        public Employee()
        {
            this.YearlyMedicalAllowance = 30000;
        }

        public double Salary
        {
            get { return salary; }
            set {
                if (value > 200000)
                    salary = value - value * taxRate;
                else
                    salary = 5000;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee objEmployee = new Employee();
            objEmployee.Name = "Rafiqul Islam";
            objEmployee.YearOfExp = 7;
            objEmployee.Salary = 5000;
            
            Console.WriteLine(objEmployee.Name);
            Console.WriteLine("Salary: " + objEmployee.Salary);
            Console.WriteLine("Yearly Madical Allowance" + objEmployee.YearlyMedicalAllowance);

            Console.ReadLine();
        }
    }

Static Constructor and C# implementation

Static Constructor

  • Instance constructors are used to initialize an object
  • Static constructors are used to initialize a class
  • Will only ever be executed once
  • Run before the first object of that type is created.
  • Have no parameter
  • Do not take an access modifier
  • May co-exist with a class constructor

Syntax:

        class Lion
        {
            static Lion()
            {
                // class-specific initialization
            }
        }

Example:


class RandomNumberGenerator
{
private static Random randomNumber;
public static string AuthorName { get; set; }

public RandomNumberGenerator(String msg)
{
Console.WriteLine(msg);
//Constructor for object
}

//Static constructor
static RandomNumberGenerator()
{
AuthorName = “Mahedee Hasan”;
randomNumber = new Random();
}

public int Next()
{
return randomNumber.Next();
}
}

class Program
{
static void Main(string[] args)
{
RandomNumberGenerator randomNumber
= new RandomNumberGenerator(“Generate 10 Random Number”);

for (int i = 0; i < 10; i++) { Console.WriteLine(randomNumber.Next()); } Console.WriteLine(“Author Name: ” + RandomNumberGenerator.AuthorName); Console.ReadKey(); } } [/csharp]