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

Last class of C#.NET Applied OOP (Batch -3)


Last class of C#.NET Applied OOP by Bangladesh Hi-Tech Park Authority at Leads Technology Limited. Conducted by me, 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();
}
}
}

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]