OOP Principles PDF
OOP Principles PDF
Principles with C#
Part I
MAHEDEE.NET 1
Contents
Introduction
What is Object Oriented Design Principle?
SOLID Object Oriented Design Principles
SRP Single Responsibility Principle
OCP Open Close Principle
LSP Liskov Substitution Principle
ISP - Interface Segregation principle
DIP Dependency Inversion Principle
MAHEDEE.NET 2
Introduction
What is Principles?
Do these and you will achieve this.
How you will do it is up to you.
MAHEDEE.NET 3
What is Object Oriented Design Principle?
MAHEDEE.NET 4
SOLID Object Oriented Design Principles
MAHEDEE.NET 5
More Principles
MAHEDEE.NET 6
SRP Single Responsibility Principle
MAHEDEE.NET 7
SRP Single Responsibility Principle
MAHEDEE.NET 8
Real World Example
MAHEDEE.NET 9
Cohesion and Coupling
Cohesion
How closely related methods and class level variables are in a
class.
Or, How strongly related or focused are various responsibilities of a
module
Coupling
The notion of coupling attempts to capture this concept of how
strongly dierent modules are interconnected
Or, the degree to which each program module relies on each one of the
other module
MAHEDEE.NET 10
Responsibilities are Axes of Change
MAHEDEE.NET 11
Have a look on the following class !
MAHEDEE.NET 12
Demo of SRP
MAHEDEE.NET 13
Solutions which will not Violate SRP
MAHEDEE.NET 14
Solutions which will not Violate SRP
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNo { get; set; }
}
public class EmployeeDB
{
public void Insert(Employee e)
{
//Database Logic written here
}
public Employee Select()
{
return new Employee();
//Database Logic written here
}
}
public class EmployeeReport
{
public void GenerateReport(Employee e)
{
//Set report formatting
}
}
MAHEDEE.NET 15
Can a single class can have multiple methods?
Yes,
A class may have more than one method.
MAHEDEE.NET 16
Summery
a reason to change
Multiple small interfaces (follow ISP) can help to
achieve SRP
Following SRP leads to lower coupling and
higher cohesion
Many small classes with distinct responsibilities
result in a more flexible design
MAHEDEE.NET 17
OCP Open Close Principle
MAHEDEE.NET 18
OCP Open Close Principle
MAHEDEE.NET 19
Real world example
MAHEDEE.NET 20
What is OCP?
MAHEDEE.NET 21
Change behavior without changing code?
Rely on abstractions
No limit to variety of implementations of each
abstraction
In .NET, abstractions include:
Interfaces
Abstract Base Classes
In procedural code, some level of OCP can be achieved via
parameters
MAHEDEE.NET 22
The Problem
MAHEDEE.NET 23
Three Approaches to Achieve OCP
MAHEDEE.NET 24
Demo of OCP
MAHEDEE.NET 25
Implementation of OCP
MAHEDEE.NET 26
OCP Implementation
public abstract class Shape
{
public abstract double CalculateArea();
}
MAHEDEE.NET 27
OCP Implementation
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;
}
}
MAHEDEE.NET 28
When do you apply OCP?
MAHEDEE.NET 29
Summery
MAHEDEE.NET 30
LSP Liskov Substitution Principle
MAHEDEE.NET 31
LSP Liskov Substitution Principle
MAHEDEE.NET 32
Real World Example
MAHEDEE.NET 33
Substitutability
MAHEDEE.NET 34
Demo of LSP
MAHEDEE.NET 35
Implementation of LSP
public abstract class Shape
{
public abstract int Area();
MAHEDEE.NET 36
Implementation of LSP
Testing LSP
[TestMethod]
public void SixFor2x3Rectange()
{
var myRectangle = new Rectangle { Height = 2, Width = 3 };
Assert.AreEqual(6, myRectangle.Area());
}
[TestMethod]
public void NineFor3x3Squre()
{
var squre = new Squre { SideLength = 3 };
Assert.AreEqual(9, squre.Area());
}
[TestMethod]
public void TwentyFor4x5ShapeAnd9For3x3Squre()
{
var shapes = new List<Shape>
{
new Rectangle{Height = 4, Width = 5},
new Squre{SideLength = 3}
};
var areas = new List<int>();
#region problem
//So you are following both polymorphism and OCP
#endregion
foreach (Shape shape in shapes)
{
areas.Add(shape.Area());
}
Assert.AreEqual(20, areas[0]);
Assert.AreEqual(9, areas[1]);
}
MAHEDEE.NET 37
Summery
MAHEDEE.NET 38
ISP Interface Segregation principle
MAHEDEE.NET 39
ISP Interface Segregation principle
MAHEDEE.NET 40
ISP - Real world example
MAHEDEE.NET 41
What is ISP?
MAHEDEE.NET 42
Demo of ISP
MAHEDEE.NET 43
ISP Violation
public interface IReportBAL
{
void GeneratePFReport();
void GenerateESICReport();
void GenerateResourcePerformanceReport();
void GenerateProjectSchedule();
void GenerateProfitReport();
}
public class ReportBAL : IReportBAL
{
public void GeneratePFReport()
{/*...............*/}
public void GenerateESICReport()
{/*...............*/}
public void GenerateResourcePerformanceReport()
{/*...............*/}
public void GenerateProjectSchedule()
{/*...............*/}
public void GenerateProfitReport()
{/*...............*/}
}
MAHEDEE.NET 44
ISP Violation
public class EmployeeUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
}
}
public class ManagerUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport ();
objBal.GenerateProjectSchedule ();
}
}
MAHEDEE.NET 45
ISP Violation
public class AdminUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport();
objBal.GenerateProjectSchedule();
objBal.GenerateProfitReport();
}
}
MAHEDEE.NET 46
Refactoring code following ISP
public interface IEmployeeReportBAL
{
void GeneratePFReport();
void GenerateESICReport();
}
public interface IManagerReportBAL : IEmployeeReportBAL
{
void GenerateResourcePerformanceReport();
void GenerateProjectSchedule();
}
public interface IAdminReportBAL : IManagerReportBAL
{
void GenerateProfitReport();
}
MAHEDEE.NET 47
Refactoring code following ISP
public class ReportBAL : IAdminReportBAL
{
public void GeneratePFReport()
{/*...............*/}
MAHEDEE.NET 48
Refactoring code following ISP
public class EmployeeUI
{
public void DisplayUI()
{
IEmployeeReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
}
}
MAHEDEE.NET 49
Refactoring code following ISP
public class ManagerUI
{
public void DisplayUI()
{
IManagerReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport ();
objBal.GenerateProjectSchedule ();
}
}
MAHEDEE.NET 50
Refactoring code following ISP
public class AdminUI
{
public void DisplayUI()
{
IAdminReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport();
objBal.GenerateProjectSchedule();
objBal.GenerateProfitReport();
}
}
MAHEDEE.NET 51
DIP Dependency Inversion principle
MAHEDEE.NET 52
DIP Dependency Inversion principle
MAHEDEE.NET 53
DIP Dependency Inversion principle
MAHEDEE.NET 54
What are dependencies?
Framework
Third party libraries
Database
File System
Email
The new keyword
System resources (clock) etc.
MAHEDEE.NET 55
Traditional Programming and dependencies
High level module call low level module
MAHEDEE.NET 56
Problem for dependencies
Tight coupling
No way to change implementation details
OCP Violation
Difficult to test
MAHEDEE.NET 57
Solution : Dependency Injection
Dependency Injection is a technique that is used to allow
calling code to inject the dependencies a class needs when it
is instantiated.
The Hollywood Principle
Dont call us; well call you
Three Primary Techniques
Constructor Injection
Property Injection
Parameter Injection
Other methods exist as well
MAHEDEE.NET 58
Constructor Injection
Dependencies are passed in via constructor
Pros
Classes self-document what they need to perform their work
Works well with or without a container
Classes are always in a valid state once constructed
Cons
Constructors can have many parameters/dependencies (design smell)
Some features (e.g. Serialization) may require a default constructor
Some methods in the class may not require things other methods
require (design smell)
MAHEDEE.NET 59
Property Injection
Dependencies are passed in via a property
Also known as setter injection
Pros
Dependency can be changed at any time during object lifetime
Very flexible
Cons
Objects may be in an invalid state between construction and setting of
dependencies via setters
Less intuitive
MAHEDEE.NET 60
Parameter Injection
Dependencies are passed in via a method parameter
Pros
Most granular
Very flexible
Requires no change to rest of class
Cons
Breaks method signature
Can result in many parameters (design smell)
MAHEDEE.NET 61
Constructor Injection
public class OnlineOrder : Order
{
private readonly INotificationService _notificationService;
private readonly PaymentDetails _paymentDetails;
private readonly IPaymentProcessor _paymentProcessor;
private readonly IReservationService _reservationService;
MAHEDEE.NET 62
Where do we instantiate objects ?
Applying Dependency Injection typically results in many
interfaces that eventually need to be instantiated
somewhere but where?
Default Constructor
You can provide a default constructor that news up the instances you
expect to typically need in your application
Referred to as poor mans dependency injection or poor mans IoC
Main
You can manually instantiate whatever is needed in your applications
startup routine or main() method
IoC Container
Use an Inversion of Control Container
MAHEDEE.NET 63
IOC Container
Responsible for object graph instantiation
MAHEDEE.NET 64
Example IOC Container in .NET
Microsoft Unity
StructureMap
Ninject
Windsor
Funq / Munq
MAHEDEE.NET 65
MAHEDEE.NET 66