SlideShare a Scribd company logo
SOLID
Principles of Object Oriented Design
Why SOLID?
SOLID is a set of five guiding principles that help developers design objects that
are easy to maintain and use.
Like many similar sets of principles in OO, SOLID is a guide not the goal.
Solid SRP
Single
Responsibility
Principle
sOolid OCP
Open /
Closed
Principle
soLid LSP
Liskov
Substitution
Principle
solId ISP
Interface
Segregation
Principle
soliD DIP
Dependency
Inversion
Principle
SRP
Single Responsibility Principle
One work at a time
“One work at a time”
● A class or module should have ONLY ONE
reason to change. Several reasons of change
may lead to several (and unwanted)
redeployments.
● Several responsibilities become coupled.
Coupled design is fragile.
SRP
Single
Responsibility
Principle
Example - Single Responsibility Principle
public class UserService
{
public void Register(string email, string password)
{
if (!ValidateEmail(email))
throw new ValidationException("Email is not an email");
var user = new User(email, password);
SendEmail(new MailMessage("mysite@nowhere.com", email) { Subject="HEllo foo" });
}
public virtual bool ValidateEmail(string email)
{
return email.Contains("@");
}
public bool SendEmail(MailMessage message)
{
_smtpClient.Send(message);
}
}
Example - Single Responsibility Principle
public class UserService
{
EmailService _emailService;
DbContext _dbContext;
public UserService(EmailService aEmailService,
DbContext aDbContext)
{
_emailService = aEmailService;
_dbContext = aDbContext;
}
public void Register(string email, string password)
{
if (!_emailService.ValidateEmail(email))
throw new ValidationException("Email is
not an email");
var user = new User(email, password);
_dbContext.Save(user);
emailService.SendEmail(new
MailMessage("myname@mydomain.com",
email)
{Subject="Hi. How are you!"});
}
}
public class EmailService
{
SmtpClient _smtpClient;
public EmailService(SmtpClient aSmtpClient)
{
_smtpClient = aSmtpClient;
}
public bool virtual ValidateEmail(string email)
{
return email.Contains("@");
}
public bool SendEmail(MailMessage message)
{
_smtpClient.Send(message);
}
}
read: http://www.objectmentor.com/resources/articles/srp.pdf
OCP
Open/Closed Principle
Open for extension / Closed for modification
Software entities (classes, modules,
functions, etc.) should be open for
extension, but closed for modification:
● A module is open if it is available for extension. For
example, it should be possible to add fields to the
data structures it contains, or new elements to the
set of functions it performs.
● A module is closed if it is available for use by other
modules. This assumes that the module has been
given a well-defined, stable description (the interface
in the sense of information hiding)
OCP
Open/
Closed
Principle
Example - Open/Closed Principle
public class ProductFilter
{
public IEnumerable<Product> ByColor(IList<Product> products, ProductColor
productColor)
{
foreach (var product in products)
{
if (product.Color == productColor)
yield return product;
}
}
public IEnumerable<Product> ByColorAndSize(IList<Product> products,
ProductColor productColor, ProductSize productSize)
{
foreach (var product in products)
{
if ((product.Color == productColor) && (product.Size == productSize))
yield return product;
}
}
public IEnumerable<Product> BySize(IList<Product> products, ProductSize productSize)
{
foreach (var product in products)
{
if ((product.Size == productSize))
yield return product;
}
}
}
Example - Open/Closed Principle
public abstract class ProductFilterSpecification
{
public IEnumerable<Product> Filter(IList<Product> products)
{
return ApplyFilter(products);
}
protected abstract IEnumerable<Product> ApplyFilter
(IList<Product> products);
}
public class ColorFilterSpecification : ProductFilterSpecification
{
private readonly ProductColor productColor;
public ColorFilterSpecification(ProductColor productColor)
{
this.productColor = productColor;
}
protected override IEnumerable<Product> ApplyFilter
(IList<Product> products)
{
foreach (var product in products)
{
if (product.Color == productColor)
yield return product;
}
}
}
public class ProductFilter
{
public IEnumerable<Product> By(IList<Product>
products, ProductFilterSpecification
filterSpecification)
{
return filterSpecification.Filter(products);
}
}
OCP using the Template Design Pattern
read: http://www.objectmentor.com/resources/articles/ocp.pdf
LSP
Liskov Substitution Principle
Subclasses should be substitutable for their base classes
● Child classes should never break the parent
class' type definitions
● The parent class should easily replace the
child class
LSP
Liskov
Substitution
Principle
Example - Liskov Substitution Principle
public interface IDuck
{
void Swim();
bool IsSwimming { get; }
}
public class OrganicDuck : IDuck
{
public void Swim()
{
//do something to swim
}
bool IsSwimming { get { /* return if the duck is
swimming */ } }
}
public class ElectricDuck : IDuck
{
bool _isSwimming;
public void Swim()
{
if (!IsTurnedOn)
throw new Exception("Duck sink!");
_isSwimming = true;
//swim logic
}
bool IsSwimming { get { return _isSwimming; } }
}
void MakeDuckSwim(IDuck duck)
{
duck.Swim(); //exception if duck is ElectricDuck
}
void MakeDuckSwim(IDuck duck)
{
if (duck is ElectricDuck)
((ElectricDuck)duck).TurnOn();
duck.Swim();
}
Example - Liskov Substitution Principle
public class Account
{
public Account(int AccountId)
{
this.Id = AccountId;
}
public virtual int Id { get; set; }
public virtual void Withdraw(int accountId, int
amount)
{
Console.WriteLine("In base withdraw");
}
}
public class SavingAccount : Account
{
public SavingAccount(int savingAccountId):
base(savingAccountId)
{
}
public override void Withdraw(int accountId,
int amount)
{
Console.WriteLine("In SavingAccount
withdraw");
}
}
public class CurrentAccount : Account
{
public CurrentAccount(int currentAccountId) :
base(currentAccountId)
{
}
public override void Withdraw(int accountId, int
amount)
{
Console.WriteLine("In CurrentAccount withdraw");
}
}
Account account = new Account(1);
account.Withdraw(acc, 100);
Account saving = new SavingAccount(2);
saving.Withdraw(saving, 100);
read:http://www.objectmentor.com/resources/articles/lsp.pdf
ISP
Interface Segregation Principle
Client Specific Interfaces
● no client should be forced to implement methods it
does not use
● split large interfaces into smaller and more specific
so the clients will know about the methods that are
interested in
● keep components focused in order to achieve low
coupling and high cohesion
● ISP is similar to SRP: one purpose => one interface!
ISP
Interface
Segregation
Principle
Example - Interface Segregation Principle
public abstract class Animal
{
public abstract void Feed();
public abstract void Groom();
}
public class Dog : Animal
{
public override void Feed()
{
//do something
}
public override void Groom()
{
// do something
}
}
public class Rattlesnake : Animal
{
public override void Feed()
{
// do something
}
public override void Groom()
{
throw new Exception("Not Implemented
yet or better Ignore!");
}
}
public interface IPet
{
void Groom();
}
public abstract class Animal
{
public abstract void Feed();
}
public class Dog : Animal, IPet
{
public override void Feed()
{
// do something
}
public void Groom()
{
// do something
}
}
public class Rattlesnake : Animal
{
public override void Feed()
{
// do something
}
}
read: http://www.objectmentor.com/resources/articles/isp.pdf
DIP
Dependency Inversion Principle
Abstractions Should Not Depend on Details
● Abstractions should not depend upon details;
● Details should depend upon abstraction
● High-level modules implement business logic in a
system (application). Low-level modules deal with
more detailed operations, in other words they may
deal with writing information to databases or passing
messages to the operating system or services.
DIP
Dependency
Inversion
Principle
Example - Dependency Inversion Principle
class Customer
{
private FileLogger obj = new FileLogger();
public virtual void Add()
{
try
{
// Database code goes here
}
catch (Exception ex)
{
obj.Handle(ex.ToString());
}
}
}
Example - Dependency Inversion Principle
interface ILogger
{
void Handle(string error);
}
class FileLogger : ILogger
{
public void Handle(string error)
{
System.IO.File.WriteAllText(@"c:Error.txt",
error);
}
}
class EverViewerLogger : ILogger
{
public void Handle(string error)
{
// log errors to event viewer
}
}
class EmailLogger : ILogger
{
public void Handle(string error)
{
// send errors in email
}
}
class Customer : IDiscount, IDatabase
{
private Ilogger obj;
public Customer(ILogger i)
{
obj = i;
}
}
read: http://www.objectmentor.com/resources/articles/dip.pdf
SOLID (review)
● S for SRP (Single responsibility principle)
A class should take care of only one responsibility.
● O for OCP (Open closed principle)
Extension should be possible without modification.
● L for LSP (Liskov substitution principle)
A parent class object should be able to refer child objects seamlessly during runtime polymorphism.
● I for ISP (Interface segregation principle)
Client should not be forced to use a interface if it does not need it.
● D for DIP (Dependency inversion principle)
High level modules should not depend on low level modules but should depend on abstraction.
Panagiotis Pnevmatikatos
pnevmap@gmail.com
Reading suggestion
Clean Code
Book by Robert Cecil Martin

More Related Content

What's hot

Clean code: SOLID
Clean code: SOLIDClean code: SOLID
Clean code: SOLID
Indeema Software Inc.
 
Solid principles
Solid principlesSolid principles
Solid principles
Toan Nguyen
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
Ionut Bilica
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
Eyal Golan
 
Solid principles
Solid principlesSolid principles
Solid principles
Monica Rodrigues
 
Solid principles
Solid principlesSolid principles
Solid principles
Dmitry Kandalov
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
NexThoughts Technologies
 
Solid Prensipleri
Solid PrensipleriSolid Prensipleri
Solid Prensipleri
Hazel Caklı
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
Pavlo Hodysh
 
Clean architecture
Clean architectureClean architecture
Clean architecture
Lieven Doclo
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design Principles
Bruno Bossola
 
Solid design principles
Solid design principlesSolid design principles
Solid design principles
Mahmoud Asadi
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
Thiago Dos Santos Hora
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
Paul Blundell
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
Neetu Mishra
 
The Single Responsibility Principle
The Single Responsibility PrincipleThe Single Responsibility Principle
The Single Responsibility Principle
Lars-Erik Kindblad
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 

What's hot (20)

Clean code: SOLID
Clean code: SOLIDClean code: SOLID
Clean code: SOLID
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Solid Prensipleri
Solid PrensipleriSolid Prensipleri
Solid Prensipleri
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design Principles
 
Solid design principles
Solid design principlesSolid design principles
Solid design principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Python SOLID
Python SOLIDPython SOLID
Python SOLID
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
 
Solid Principle
Solid PrincipleSolid Principle
Solid Principle
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
The Single Responsibility Principle
The Single Responsibility PrincipleThe Single Responsibility Principle
The Single Responsibility Principle
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 

Viewers also liked

Bahasa melayu stpm
Bahasa melayu stpmBahasa melayu stpm
What is Travel Insurance?
What is Travel Insurance?What is Travel Insurance?
What is Travel Insurance?
Insuring India
 
Unit testing
Unit testingUnit testing
Unit testing
Panos Pnevmatikatos
 
AIA Final Calendar for Women in Architecture 2015 (1)
AIA Final Calendar for Women in Architecture  2015 (1)AIA Final Calendar for Women in Architecture  2015 (1)
AIA Final Calendar for Women in Architecture 2015 (1)Amy Rogers, CCC-SLP
 
The Role of Retention Time in Untargeted Metabolomics
The Role of Retention Time in Untargeted MetabolomicsThe Role of Retention Time in Untargeted Metabolomics
The Role of Retention Time in Untargeted Metabolomics
Jan Stanstrup
 
Single responsibility principle
Single responsibility principleSingle responsibility principle
Single responsibility principle
Radu Iscu
 
Solid principles – interface segregation principle
Solid principles – interface segregation principle Solid principles – interface segregation principle
Solid principles – interface segregation principle
Nitisak Mooltreesri
 
Object Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDObject Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLID
Tom Crinson
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
Deddy Setyadi
 
SRP & OCP
SRP & OCPSRP & OCP
SRP & OCP
Phuoc Ho
 
Solid - OOD Principles
Solid - OOD PrinciplesSolid - OOD Principles
Solid - OOD Principles
Creditas
 
SOLID Architecture Overview
SOLID Architecture OverviewSOLID Architecture Overview
SOLID Architecture OverviewIrshad Peeran
 
sistem pendididkan di sabah & sarawak sejarah SEM 3
sistem pendididkan di sabah & sarawak sejarah SEM 3sistem pendididkan di sabah & sarawak sejarah SEM 3
sistem pendididkan di sabah & sarawak sejarah SEM 3
Pra-Univeristy SMK Tun Abdul Razak Selekoh
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#
Ken Burkhardt
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original Version
Philip Schwarz
 
Counting
CountingCounting
Counting
rfant
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
rainynovember12
 

Viewers also liked (20)

Bahasa melayu stpm
Bahasa melayu stpmBahasa melayu stpm
Bahasa melayu stpm
 
What is Travel Insurance?
What is Travel Insurance?What is Travel Insurance?
What is Travel Insurance?
 
Susun lapis masyarakat di negeri negeri melayu
Susun lapis masyarakat di negeri negeri melayuSusun lapis masyarakat di negeri negeri melayu
Susun lapis masyarakat di negeri negeri melayu
 
Unit testing
Unit testingUnit testing
Unit testing
 
Limits of Solidarity
Limits of SolidarityLimits of Solidarity
Limits of Solidarity
 
AIA Final Calendar for Women in Architecture 2015 (1)
AIA Final Calendar for Women in Architecture  2015 (1)AIA Final Calendar for Women in Architecture  2015 (1)
AIA Final Calendar for Women in Architecture 2015 (1)
 
myresume3
myresume3myresume3
myresume3
 
The Role of Retention Time in Untargeted Metabolomics
The Role of Retention Time in Untargeted MetabolomicsThe Role of Retention Time in Untargeted Metabolomics
The Role of Retention Time in Untargeted Metabolomics
 
Single responsibility principle
Single responsibility principleSingle responsibility principle
Single responsibility principle
 
Solid principles – interface segregation principle
Solid principles – interface segregation principle Solid principles – interface segregation principle
Solid principles – interface segregation principle
 
Object Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLIDObject Oriented Design Principles - SOLID
Object Oriented Design Principles - SOLID
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
SRP & OCP
SRP & OCPSRP & OCP
SRP & OCP
 
Solid - OOD Principles
Solid - OOD PrinciplesSolid - OOD Principles
Solid - OOD Principles
 
SOLID Architecture Overview
SOLID Architecture OverviewSOLID Architecture Overview
SOLID Architecture Overview
 
sistem pendididkan di sabah & sarawak sejarah SEM 3
sistem pendididkan di sabah & sarawak sejarah SEM 3sistem pendididkan di sabah & sarawak sejarah SEM 3
sistem pendididkan di sabah & sarawak sejarah SEM 3
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original Version
 
Counting
CountingCounting
Counting
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 

Similar to SOLID

An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
Attila Bertók
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Constanța Developers
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)
Dave Hulbert
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
Ólafur Andri Ragnarsson
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
vivek p s
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
Andy Butland
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Iakiv Kramarenko
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
Neil Crookes
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
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#
Daniel Fisher
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2
Y Watanabe
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought
 
Design Patterns
Design PatternsDesign Patterns

Similar to SOLID (20)

An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
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#
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Recently uploaded

Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
vrstrong314
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 

Recently uploaded (20)

Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 

SOLID

  • 1. SOLID Principles of Object Oriented Design
  • 2. Why SOLID? SOLID is a set of five guiding principles that help developers design objects that are easy to maintain and use. Like many similar sets of principles in OO, SOLID is a guide not the goal.
  • 9. “One work at a time” ● A class or module should have ONLY ONE reason to change. Several reasons of change may lead to several (and unwanted) redeployments. ● Several responsibilities become coupled. Coupled design is fragile. SRP Single Responsibility Principle
  • 10. Example - Single Responsibility Principle public class UserService { public void Register(string email, string password) { if (!ValidateEmail(email)) throw new ValidationException("Email is not an email"); var user = new User(email, password); SendEmail(new MailMessage("mysite@nowhere.com", email) { Subject="HEllo foo" }); } public virtual bool ValidateEmail(string email) { return email.Contains("@"); } public bool SendEmail(MailMessage message) { _smtpClient.Send(message); } }
  • 11. Example - Single Responsibility Principle public class UserService { EmailService _emailService; DbContext _dbContext; public UserService(EmailService aEmailService, DbContext aDbContext) { _emailService = aEmailService; _dbContext = aDbContext; } public void Register(string email, string password) { if (!_emailService.ValidateEmail(email)) throw new ValidationException("Email is not an email"); var user = new User(email, password); _dbContext.Save(user); emailService.SendEmail(new MailMessage("myname@mydomain.com", email) {Subject="Hi. How are you!"}); } } public class EmailService { SmtpClient _smtpClient; public EmailService(SmtpClient aSmtpClient) { _smtpClient = aSmtpClient; } public bool virtual ValidateEmail(string email) { return email.Contains("@"); } public bool SendEmail(MailMessage message) { _smtpClient.Send(message); } } read: http://www.objectmentor.com/resources/articles/srp.pdf
  • 12. OCP Open/Closed Principle Open for extension / Closed for modification
  • 13. Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification: ● A module is open if it is available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs. ● A module is closed if it is available for use by other modules. This assumes that the module has been given a well-defined, stable description (the interface in the sense of information hiding) OCP Open/ Closed Principle
  • 14. Example - Open/Closed Principle public class ProductFilter { public IEnumerable<Product> ByColor(IList<Product> products, ProductColor productColor) { foreach (var product in products) { if (product.Color == productColor) yield return product; } } public IEnumerable<Product> ByColorAndSize(IList<Product> products, ProductColor productColor, ProductSize productSize) { foreach (var product in products) { if ((product.Color == productColor) && (product.Size == productSize)) yield return product; } } public IEnumerable<Product> BySize(IList<Product> products, ProductSize productSize) { foreach (var product in products) { if ((product.Size == productSize)) yield return product; } } }
  • 15. Example - Open/Closed Principle public abstract class ProductFilterSpecification { public IEnumerable<Product> Filter(IList<Product> products) { return ApplyFilter(products); } protected abstract IEnumerable<Product> ApplyFilter (IList<Product> products); } public class ColorFilterSpecification : ProductFilterSpecification { private readonly ProductColor productColor; public ColorFilterSpecification(ProductColor productColor) { this.productColor = productColor; } protected override IEnumerable<Product> ApplyFilter (IList<Product> products) { foreach (var product in products) { if (product.Color == productColor) yield return product; } } } public class ProductFilter { public IEnumerable<Product> By(IList<Product> products, ProductFilterSpecification filterSpecification) { return filterSpecification.Filter(products); } } OCP using the Template Design Pattern read: http://www.objectmentor.com/resources/articles/ocp.pdf
  • 16. LSP Liskov Substitution Principle Subclasses should be substitutable for their base classes
  • 17. ● Child classes should never break the parent class' type definitions ● The parent class should easily replace the child class LSP Liskov Substitution Principle
  • 18. Example - Liskov Substitution Principle public interface IDuck { void Swim(); bool IsSwimming { get; } } public class OrganicDuck : IDuck { public void Swim() { //do something to swim } bool IsSwimming { get { /* return if the duck is swimming */ } } } public class ElectricDuck : IDuck { bool _isSwimming; public void Swim() { if (!IsTurnedOn) throw new Exception("Duck sink!"); _isSwimming = true; //swim logic } bool IsSwimming { get { return _isSwimming; } } } void MakeDuckSwim(IDuck duck) { duck.Swim(); //exception if duck is ElectricDuck } void MakeDuckSwim(IDuck duck) { if (duck is ElectricDuck) ((ElectricDuck)duck).TurnOn(); duck.Swim(); }
  • 19. Example - Liskov Substitution Principle public class Account { public Account(int AccountId) { this.Id = AccountId; } public virtual int Id { get; set; } public virtual void Withdraw(int accountId, int amount) { Console.WriteLine("In base withdraw"); } } public class SavingAccount : Account { public SavingAccount(int savingAccountId): base(savingAccountId) { } public override void Withdraw(int accountId, int amount) { Console.WriteLine("In SavingAccount withdraw"); } } public class CurrentAccount : Account { public CurrentAccount(int currentAccountId) : base(currentAccountId) { } public override void Withdraw(int accountId, int amount) { Console.WriteLine("In CurrentAccount withdraw"); } } Account account = new Account(1); account.Withdraw(acc, 100); Account saving = new SavingAccount(2); saving.Withdraw(saving, 100); read:http://www.objectmentor.com/resources/articles/lsp.pdf
  • 21. ● no client should be forced to implement methods it does not use ● split large interfaces into smaller and more specific so the clients will know about the methods that are interested in ● keep components focused in order to achieve low coupling and high cohesion ● ISP is similar to SRP: one purpose => one interface! ISP Interface Segregation Principle
  • 22. Example - Interface Segregation Principle public abstract class Animal { public abstract void Feed(); public abstract void Groom(); } public class Dog : Animal { public override void Feed() { //do something } public override void Groom() { // do something } } public class Rattlesnake : Animal { public override void Feed() { // do something } public override void Groom() { throw new Exception("Not Implemented yet or better Ignore!"); } } public interface IPet { void Groom(); } public abstract class Animal { public abstract void Feed(); } public class Dog : Animal, IPet { public override void Feed() { // do something } public void Groom() { // do something } } public class Rattlesnake : Animal { public override void Feed() { // do something } } read: http://www.objectmentor.com/resources/articles/isp.pdf
  • 23. DIP Dependency Inversion Principle Abstractions Should Not Depend on Details
  • 24. ● Abstractions should not depend upon details; ● Details should depend upon abstraction ● High-level modules implement business logic in a system (application). Low-level modules deal with more detailed operations, in other words they may deal with writing information to databases or passing messages to the operating system or services. DIP Dependency Inversion Principle
  • 25. Example - Dependency Inversion Principle class Customer { private FileLogger obj = new FileLogger(); public virtual void Add() { try { // Database code goes here } catch (Exception ex) { obj.Handle(ex.ToString()); } } }
  • 26. Example - Dependency Inversion Principle interface ILogger { void Handle(string error); } class FileLogger : ILogger { public void Handle(string error) { System.IO.File.WriteAllText(@"c:Error.txt", error); } } class EverViewerLogger : ILogger { public void Handle(string error) { // log errors to event viewer } } class EmailLogger : ILogger { public void Handle(string error) { // send errors in email } } class Customer : IDiscount, IDatabase { private Ilogger obj; public Customer(ILogger i) { obj = i; } } read: http://www.objectmentor.com/resources/articles/dip.pdf
  • 27. SOLID (review) ● S for SRP (Single responsibility principle) A class should take care of only one responsibility. ● O for OCP (Open closed principle) Extension should be possible without modification. ● L for LSP (Liskov substitution principle) A parent class object should be able to refer child objects seamlessly during runtime polymorphism. ● I for ISP (Interface segregation principle) Client should not be forced to use a interface if it does not need it. ● D for DIP (Dependency inversion principle) High level modules should not depend on low level modules but should depend on abstraction.