SlideShare una empresa de Scribd logo
1 de 67
Object Oriented Design
Principles with C#
Part – I
Md. Mahedee Hasan
Software Architect
Leadsoft Bangladesh Limited
Linkedin: http://www.linkedin.com/in/mahedee
Blog: http://mahedee.net/
http://mahedee.blogspot.com/
1MAHEDEE.NET
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.
– Everyone defines some principles in their lives like
• "I never lie“
• “I never drink alcohol”
– He/she follow these principles to make his/her life easy
– How will he/she stick to these principles is up to the individual.
MAHEDEE.NET 3
What is Object Oriented Design Principle?
• What is Object Oriented Design?
– It’s a process of planning a software system where objects will
interact with each other to solve specific problems
– The saying goes, "Proper Object oriented design makes a developer's
life easy, whereas bad design makes it a disaster.“
• What is Object Oriented Design Principles?
– Is the process of planning software system using some guideline or
principles where object will interact with best possible way.
– Benefit
• It will make developer life easy.
• It will make software more manageable.
MAHEDEE.NET 4
SOLID Object Oriented Design Principles
• Introduced by by Mr. Robert Martin (commonly known as
Uncle Bob)
• Acronyms of five principles
o S-SRP - Single responsibility Principle
o O-OCP - Open-closed Principle
o L-LSP - Liskov substitution Principle
o I-ISP - Interface segregation Principle
o D-DIP - Dependency inversion Principle
MAHEDEE.NET 5
More Principles
• More principles other than those categorized by Uncle Bob
– Program to Interface Not Implementation.
– Don't Repeat Yourself.
– Encapsulate What Varies.
– Depend on Abstractions, Not Concrete classes.
– Least Knowledge Principle.
– Favor Composition over Inheritance.
– Hollywood Principle.
– Apply Design Pattern wherever possible.
– Strive for Loosely Coupled System.
– Keep it Simple and Sweet / Stupid. (KISS)
MAHEDEE.NET 6
SRP– Single Responsibility Principle
MAHEDEE.NET 7
SRP – Single Responsibility Principle
The Single Principle states that
Every object should have a single responsibility and
that responsibility should be entirely encapsulated
by the class. - Wikipedia
There should never be one reason for a class to
change. – Robert C. “Uncle Bob” Martin
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” different modules are interconnected
– Or, the degree to which each program module relies on each one of the
other module
Strive for low Coupling and High Cohesion!
MAHEDEE.NET 10
Responsibilities are Axes of Change
• Requirements changes typically map to responsibilities
• More responsibilities == More likelihood of change
• Having multiple responsibilities within a class couples
together these responsibilities
• The more classes a change affects, the more likely the
change will introduce errors.
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
• Now it’s up to us how we achieve this.
• One thing we can do is create three different classes
– Employee – Contains Properties (Data)
– EmployeeDB – Does database operations
– EmplyeeReport – Does report related tasks
Solutions which will not Violate SRP …
MAHEDEE.NET 15
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
}
}
Can a single class can have multiple methods?
MAHEDEE.NET 16
Yes,
A class may have more than one method.
A method will have single responsibility.
Summery
MAHEDEE.NET 17
• “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
OCP – Open Close Principle
MAHEDEE.NET 18
OCP – Open Close Principle
The Open Close Principle states that
Software entities (classes, modules, functions, etc.)
should be open for extension, but closed for
modification - Wikipedia
First introduced by Betrand Meyer in 1988
MAHEDEE.NET 19
Real world example
MAHEDEE.NET 20
What is OCP?
MAHEDEE.NET 21
• Open for extension
– Its behavior can be extended to accommodate new demand.
• Close for modification
– The existing source code of the module is not changed or
minimum change when making enhancement
Change behavior without changing code?
MAHEDEE.NET 22
• 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
The Problem
MAHEDEE.NET 23
• Adding new rules require changes to every time
• Each change can introduce bugs and requires re-testing,
etc.
• We want to avoid introducing changes that cascade
through many modules in our application
• Writing new classes is less likely to introduce problems
– Nothing depends on new classes (yet)
– New classes have no legacy coupling to make them hard to
design or test
Three Approaches to Achieve OCP
MAHEDEE.NET 24
• Parameters (Procedural Programming)
– Allow client to control behavior specifics via a parameter
– Combined with delegates/lambda, can be very powerful approach
• Inheritance / Template Method Pattern
– Child types override behavior of a base class (or interface)
• Composition / Strategy Pattern
– Client code depends on abstraction
– Provides a “plug in” model
– Implementations utilize Inheritance; Client utilizes
Composition
Demo of OCP
MAHEDEE.NET 25
Implementation of OCP
MAHEDEE.NET 26
OCP Implementation
MAHEDEE.NET 27
public abstract class Shape
{
public abstract double CalculateArea();
}
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;
}
}
OCP Implementation …
MAHEDEE.NET 28
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;
}
}
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;
}
}
When do you apply OCP?
MAHEDEE.NET 29
• Experience Tells You
– If you know from your own experience in the problem domain that
a particular class of change is likely to recur, you can apply OCP
up front in your design
• Don’t apply OCP at first
• If the module changes once, accept it.
• If it changes a second time, refactor to achieve OCP
Summery
MAHEDEE.NET 30
• OCP yields flexibility, reusability, and maintainability
• Know which changes to guard against, and resist
premature abstraction
LSP – Liskov Substitution Principle
MAHEDEE.NET 31
LSP – Liskov Substitution Principle
The Liskov Substitution Principle states that
Subtypes must be substitutable for their base types.
- Agile Principles, Patterns, and Practices in C#
Named for Barbara Liskov, who first described the
principle in 1988
MAHEDEE.NET 32
Real World Example
MAHEDEE.NET 33
Substitutability
• Child classes must not:
– Remove base class behavior
– Violate base class invariants
• In general must not require calling code to know they are
different from their base type
MAHEDEE.NET 34
Demo of LSP
MAHEDEE.NET 35
Implementation of LSP
MAHEDEE.NET 36
public abstract class Shape
{
public abstract int Area();
}
public class Squre : Shape
{
public int SideLength;
public override int Area()
{
return SideLength * SideLength;
}
}
public class Rectangle : Shape
{
public int Height { get; set; }
public int Width { get; set; }
public override int Area()
{
return Height * Width;
}
}
Implementation of LSP…
MAHEDEE.NET 37
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]);
}
Summery
• Extension of open close principle
• LSP allows for proper use of polymorphism
• Produces more maintainable code
• Remember IS-SUBSTITUTABLE-FOR instead of IS-A
MAHEDEE.NET 38
ISP– Interface Segregation principle
MAHEDEE.NET 39
ISP– Interface Segregation principle
The Interface Segregation Principle states that
Clients should not be forced to depend on the
methods they do not use.
Corollary : Prefer small, cohesive interface to fat interfaces
MAHEDEE.NET 40
ISP - Real world example
MAHEDEE.NET 41
What is ISP?
• Many client specific interfaces are better than one
general purpose interface
• The dependency of one class to another one should
depend on the smallest possible interface
• In simple words, if your interface is fat, break it
into multiple interfaces.
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()
{/*...............*/}
public void GenerateESICReport()
{/*...............*/}
public void GenerateResourcePerformanceReport()
{/*...............*/}
public void GenerateProjectSchedule()
{/*...............*/}
public void GenerateProfitReport()
{/*...............*/}
}
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
The Dependency Inversion Principle states that
"High level modules should not depend upon low
level modules. Both should depend on abstractions.“
Abstraction should not depends on details. Details
should depend on abstractions.
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
• Use interface depends on
– Business logic depends on
• Infrastructure
• Utility
• Data access
• Static method are used for convenience or as façade layer
• Class instantiation / call stack logic is scattered through out
all modules
– Violation of Single Responsibilities principle
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
– “Don’t call us; we’ll 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)
• Consider if only one method has the dependency, otherwise
prefer constructor injection
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;
public OnlineOrder(Cart cart,
PaymentDetails paymentDetails,
IPaymentProcessor paymentProcessor,
IReservationService reservationService,
INotificationService notificationService)
: base(cart)
{
_paymentDetails = paymentDetails;
_paymentProcessor = paymentProcessor;
_reservationService = reservationService;
_notificationService = notificationService;
}
//……..
}
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 man’s dependency injection” or “poor man’s IoC”
• Main
– You can manually instantiate whatever is needed in your application’s
startup routine or main() method
• IoC Container
– Use an “Inversion of Control” Container
MAHEDEE.NET 63
IOC Container
• Responsible for object graph instantiation
• Initiated at application startup via code or configuration
• Managed interfaces and the implementation to be used are
Registered with the container
• Dependencies on interfaces are Resolved at application
startup or runtime
MAHEDEE.NET 64
Example IOC Container in .NET
• Microsoft Unity
• StructureMap
• Ninject
• Windsor
• Funq / Munq
MAHEDEE.NET 65
66MAHEDEE.NET
SL Version Modification Description Update date
1 1.0 Initial creation 21/02/2014
MAHEDEE.NET 67
Modification History

Más contenido relacionado

La actualidad más candente (20)

SOLID principles
SOLID principlesSOLID principles
SOLID principles
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Solid principles
Solid principlesSolid principles
Solid principles
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
Java interface
Java interfaceJava interface
Java interface
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Design principle vs design patterns
Design principle vs design patternsDesign principle vs design patterns
Design principle vs design patterns
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 

Destacado

Destacado (6)

MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Generic Repository Pattern with ASP.NET MVC and EF
Generic Repository Pattern with ASP.NET MVC and EFGeneric Repository Pattern with ASP.NET MVC and EF
Generic Repository Pattern with ASP.NET MVC and EF
 
Introduction to OMNeT++
Introduction to OMNeT++Introduction to OMNeT++
Introduction to OMNeT++
 
Introduction to TFS 2013
Introduction to TFS 2013Introduction to TFS 2013
Introduction to TFS 2013
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 

Similar a Oop principles

Similar a Oop principles (20)

Solid principle
Solid principleSolid principle
Solid principle
 
Solid principles
Solid principlesSolid principles
Solid principles
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
Solid
SolidSolid
Solid
 
L07 Design Principles
L07 Design PrinciplesL07 Design Principles
L07 Design Principles
 
SOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User GroupSOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User Group
 
DesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatternsDesignPrinciples-and-DesignPatterns
DesignPrinciples-and-DesignPatterns
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Solid principes
Solid principesSolid principes
Solid principes
 
OO Design Principles
OO Design PrinciplesOO Design Principles
OO Design Principles
 
SOLID design
SOLID designSOLID design
SOLID design
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 
Clean code: SOLID (iOS)
Clean code: SOLID (iOS)Clean code: SOLID (iOS)
Clean code: SOLID (iOS)
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-Present
 
Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1Episode 21 - Design Pattern 1
Episode 21 - Design Pattern 1
 

Más de Md. Mahedee Hasan

Chatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUISChatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUISMd. Mahedee Hasan
 
Chatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot FrameworkChatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot FrameworkMd. Mahedee Hasan
 
Introduction to Windows 10 IoT Core
Introduction to Windows 10 IoT CoreIntroduction to Windows 10 IoT Core
Introduction to Windows 10 IoT CoreMd. Mahedee Hasan
 
Whats new in visual studio 2017
Whats new in visual studio 2017Whats new in visual studio 2017
Whats new in visual studio 2017Md. Mahedee Hasan
 
Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017Md. Mahedee Hasan
 
Exciting features in visual studio 2017
Exciting features in visual studio 2017Exciting features in visual studio 2017
Exciting features in visual studio 2017Md. Mahedee Hasan
 
The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#Md. Mahedee Hasan
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkMd. Mahedee Hasan
 
Feature and Future of ASP.NET
Feature and Future of ASP.NETFeature and Future of ASP.NET
Feature and Future of ASP.NETMd. Mahedee Hasan
 
C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3Md. Mahedee Hasan
 

Más de Md. Mahedee Hasan (12)

Azure Machine Learning
Azure Machine LearningAzure Machine Learning
Azure Machine Learning
 
Chatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUISChatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUIS
 
Chatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot FrameworkChatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot Framework
 
ASP.NET MVC Zero to Hero
ASP.NET MVC Zero to HeroASP.NET MVC Zero to Hero
ASP.NET MVC Zero to Hero
 
Introduction to Windows 10 IoT Core
Introduction to Windows 10 IoT CoreIntroduction to Windows 10 IoT Core
Introduction to Windows 10 IoT Core
 
Whats new in visual studio 2017
Whats new in visual studio 2017Whats new in visual studio 2017
Whats new in visual studio 2017
 
Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017
 
Exciting features in visual studio 2017
Exciting features in visual studio 2017Exciting features in visual studio 2017
Exciting features in visual studio 2017
 
The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
 
Feature and Future of ASP.NET
Feature and Future of ASP.NETFeature and Future of ASP.NET
Feature and Future of ASP.NET
 
C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3
 

Último

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Último (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Oop principles

  • 1. Object Oriented Design Principles with C# Part – I Md. Mahedee Hasan Software Architect Leadsoft Bangladesh Limited Linkedin: http://www.linkedin.com/in/mahedee Blog: http://mahedee.net/ http://mahedee.blogspot.com/ 1MAHEDEE.NET
  • 2. 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
  • 3. Introduction • What is Principles? – Do these and you will achieve this. • How you will do it is up to you. – Everyone defines some principles in their lives like • "I never lie“ • “I never drink alcohol” – He/she follow these principles to make his/her life easy – How will he/she stick to these principles is up to the individual. MAHEDEE.NET 3
  • 4. What is Object Oriented Design Principle? • What is Object Oriented Design? – It’s a process of planning a software system where objects will interact with each other to solve specific problems – The saying goes, "Proper Object oriented design makes a developer's life easy, whereas bad design makes it a disaster.“ • What is Object Oriented Design Principles? – Is the process of planning software system using some guideline or principles where object will interact with best possible way. – Benefit • It will make developer life easy. • It will make software more manageable. MAHEDEE.NET 4
  • 5. SOLID Object Oriented Design Principles • Introduced by by Mr. Robert Martin (commonly known as Uncle Bob) • Acronyms of five principles o S-SRP - Single responsibility Principle o O-OCP - Open-closed Principle o L-LSP - Liskov substitution Principle o I-ISP - Interface segregation Principle o D-DIP - Dependency inversion Principle MAHEDEE.NET 5
  • 6. More Principles • More principles other than those categorized by Uncle Bob – Program to Interface Not Implementation. – Don't Repeat Yourself. – Encapsulate What Varies. – Depend on Abstractions, Not Concrete classes. – Least Knowledge Principle. – Favor Composition over Inheritance. – Hollywood Principle. – Apply Design Pattern wherever possible. – Strive for Loosely Coupled System. – Keep it Simple and Sweet / Stupid. (KISS) MAHEDEE.NET 6
  • 7. SRP– Single Responsibility Principle MAHEDEE.NET 7
  • 8. SRP – Single Responsibility Principle The Single Principle states that Every object should have a single responsibility and that responsibility should be entirely encapsulated by the class. - Wikipedia There should never be one reason for a class to change. – Robert C. “Uncle Bob” Martin MAHEDEE.NET 8
  • 10. 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” different modules are interconnected – Or, the degree to which each program module relies on each one of the other module Strive for low Coupling and High Cohesion! MAHEDEE.NET 10
  • 11. Responsibilities are Axes of Change • Requirements changes typically map to responsibilities • More responsibilities == More likelihood of change • Having multiple responsibilities within a class couples together these responsibilities • The more classes a change affects, the more likely the change will introduce errors. MAHEDEE.NET 11
  • 12. Have a look on the following class ! MAHEDEE.NET 12
  • 14. Solutions which will not Violate SRP MAHEDEE.NET 14 • Now it’s up to us how we achieve this. • One thing we can do is create three different classes – Employee – Contains Properties (Data) – EmployeeDB – Does database operations – EmplyeeReport – Does report related tasks
  • 15. Solutions which will not Violate SRP … MAHEDEE.NET 15 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 } }
  • 16. Can a single class can have multiple methods? MAHEDEE.NET 16 Yes, A class may have more than one method. A method will have single responsibility.
  • 17. Summery MAHEDEE.NET 17 • “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
  • 18. OCP – Open Close Principle MAHEDEE.NET 18
  • 19. OCP – Open Close Principle The Open Close Principle states that Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification - Wikipedia First introduced by Betrand Meyer in 1988 MAHEDEE.NET 19
  • 21. What is OCP? MAHEDEE.NET 21 • Open for extension – Its behavior can be extended to accommodate new demand. • Close for modification – The existing source code of the module is not changed or minimum change when making enhancement
  • 22. Change behavior without changing code? MAHEDEE.NET 22 • 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
  • 23. The Problem MAHEDEE.NET 23 • Adding new rules require changes to every time • Each change can introduce bugs and requires re-testing, etc. • We want to avoid introducing changes that cascade through many modules in our application • Writing new classes is less likely to introduce problems – Nothing depends on new classes (yet) – New classes have no legacy coupling to make them hard to design or test
  • 24. Three Approaches to Achieve OCP MAHEDEE.NET 24 • Parameters (Procedural Programming) – Allow client to control behavior specifics via a parameter – Combined with delegates/lambda, can be very powerful approach • Inheritance / Template Method Pattern – Child types override behavior of a base class (or interface) • Composition / Strategy Pattern – Client code depends on abstraction – Provides a “plug in” model – Implementations utilize Inheritance; Client utilizes Composition
  • 27. OCP Implementation MAHEDEE.NET 27 public abstract class Shape { public abstract double CalculateArea(); } 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; } }
  • 28. OCP Implementation … MAHEDEE.NET 28 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; } } 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; } }
  • 29. When do you apply OCP? MAHEDEE.NET 29 • Experience Tells You – If you know from your own experience in the problem domain that a particular class of change is likely to recur, you can apply OCP up front in your design • Don’t apply OCP at first • If the module changes once, accept it. • If it changes a second time, refactor to achieve OCP
  • 30. Summery MAHEDEE.NET 30 • OCP yields flexibility, reusability, and maintainability • Know which changes to guard against, and resist premature abstraction
  • 31. LSP – Liskov Substitution Principle MAHEDEE.NET 31
  • 32. LSP – Liskov Substitution Principle The Liskov Substitution Principle states that Subtypes must be substitutable for their base types. - Agile Principles, Patterns, and Practices in C# Named for Barbara Liskov, who first described the principle in 1988 MAHEDEE.NET 32
  • 34. Substitutability • Child classes must not: – Remove base class behavior – Violate base class invariants • In general must not require calling code to know they are different from their base type MAHEDEE.NET 34
  • 36. Implementation of LSP MAHEDEE.NET 36 public abstract class Shape { public abstract int Area(); } public class Squre : Shape { public int SideLength; public override int Area() { return SideLength * SideLength; } } public class Rectangle : Shape { public int Height { get; set; } public int Width { get; set; } public override int Area() { return Height * Width; } }
  • 37. Implementation of LSP… MAHEDEE.NET 37 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]); }
  • 38. Summery • Extension of open close principle • LSP allows for proper use of polymorphism • Produces more maintainable code • Remember IS-SUBSTITUTABLE-FOR instead of IS-A MAHEDEE.NET 38
  • 39. ISP– Interface Segregation principle MAHEDEE.NET 39
  • 40. ISP– Interface Segregation principle The Interface Segregation Principle states that Clients should not be forced to depend on the methods they do not use. Corollary : Prefer small, cohesive interface to fat interfaces MAHEDEE.NET 40
  • 41. ISP - Real world example MAHEDEE.NET 41
  • 42. What is ISP? • Many client specific interfaces are better than one general purpose interface • The dependency of one class to another one should depend on the smallest possible interface • In simple words, if your interface is fat, break it into multiple interfaces. MAHEDEE.NET 42
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. Refactoring code following ISP … public class ReportBAL : IAdminReportBAL { public void GeneratePFReport() {/*...............*/} public void GenerateESICReport() {/*...............*/} public void GenerateResourcePerformanceReport() {/*...............*/} public void GenerateProjectSchedule() {/*...............*/} public void GenerateProfitReport() {/*...............*/} } MAHEDEE.NET 48
  • 49. Refactoring code following ISP … public class EmployeeUI { public void DisplayUI() { IEmployeeReportBAL objBal = new ReportBAL(); objBal.GenerateESICReport(); objBal.GeneratePFReport(); } } MAHEDEE.NET 49
  • 50. 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
  • 51. 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
  • 52. DIP – Dependency Inversion principle MAHEDEE.NET 52
  • 53. DIP – Dependency Inversion principle The Dependency Inversion Principle states that "High level modules should not depend upon low level modules. Both should depend on abstractions.“ Abstraction should not depends on details. Details should depend on abstractions. MAHEDEE.NET 53
  • 54. DIP – Dependency Inversion principle MAHEDEE.NET 54
  • 55. What are dependencies? • Framework • Third party libraries • Database • File System • Email • The new keyword • System resources (clock) etc. MAHEDEE.NET 55
  • 56. Traditional Programming and dependencies • High level module call low level module • Use interface depends on – Business logic depends on • Infrastructure • Utility • Data access • Static method are used for convenience or as façade layer • Class instantiation / call stack logic is scattered through out all modules – Violation of Single Responsibilities principle MAHEDEE.NET 56
  • 57. Problem for dependencies • Tight coupling • No way to change implementation details – OCP Violation • Difficult to test MAHEDEE.NET 57
  • 58. 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 – “Don’t call us; we’ll call you” • Three Primary Techniques – Constructor Injection – Property Injection – Parameter Injection • Other methods exist as well MAHEDEE.NET 58
  • 59. 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
  • 60. 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
  • 61. 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) • Consider if only one method has the dependency, otherwise prefer constructor injection MAHEDEE.NET 61
  • 62. Constructor Injection public class OnlineOrder : Order { private readonly INotificationService _notificationService; private readonly PaymentDetails _paymentDetails; private readonly IPaymentProcessor _paymentProcessor; private readonly IReservationService _reservationService; public OnlineOrder(Cart cart, PaymentDetails paymentDetails, IPaymentProcessor paymentProcessor, IReservationService reservationService, INotificationService notificationService) : base(cart) { _paymentDetails = paymentDetails; _paymentProcessor = paymentProcessor; _reservationService = reservationService; _notificationService = notificationService; } //…….. } MAHEDEE.NET 62
  • 63. 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 man’s dependency injection” or “poor man’s IoC” • Main – You can manually instantiate whatever is needed in your application’s startup routine or main() method • IoC Container – Use an “Inversion of Control” Container MAHEDEE.NET 63
  • 64. IOC Container • Responsible for object graph instantiation • Initiated at application startup via code or configuration • Managed interfaces and the implementation to be used are Registered with the container • Dependencies on interfaces are Resolved at application startup or runtime MAHEDEE.NET 64
  • 65. Example IOC Container in .NET • Microsoft Unity • StructureMap • Ninject • Windsor • Funq / Munq MAHEDEE.NET 65
  • 67. SL Version Modification Description Update date 1 1.0 Initial creation 21/02/2014 MAHEDEE.NET 67 Modification History