SlideShare ist ein Scribd-Unternehmen logo
1 von 35
SOLID Principles
   Declan Whelan
     @dwhelan
SOLID Principles

‱ Single Responsibility Principle
‱ Open Closed Principle
‱ Liskov Substitution Principle
‱ Interface Segregation Principle
‱ Dependency Inversion Principle
Single Responsibility
        Principle


There should be one and only one
reason for a class to change.
SRP Violation
public class UserSettingService
{
  public void changeEmail(User user)
  {
    if(checkAccess(user))
    {
       //Grant option to change
    }
  }

  public boolean checkAccess(User user)
  {
    //Verify if the user is valid.
  }
}
SRP Restored
public class UserSettingService
{
  public void changeEmail(User user)
  {
    if(SecurityService.checkAccess(user))
    {
       //Grant option to change
    }
  }
}

public class SecurityService
{
  public static boolean checkAccess(User user)
  {
    //check the access.
  }
}
Open Closed Principle


Software entities should be open for
extension but closed for modification.
A Product Filter


We need a way to filter products by colour.
Class Responsibility
The classes’ responsibility is to filter
products (its job) based off the action of
filtering by colour (its behaviour).
The ProductFilter is responsible for
filtering products by colour.
Filter By Colour
public class ProductFilter
{
  public IEnumerable<Product> ByColor(IList<Product> products, ProductColor productColor)
  {
     foreach (var product in products)
     {
        if (product.Color == productColor)
            yield return product;
     }
  }
}
More Requirements!
User: We also need to filter by size.
Developer: Just size or colour and size?
User: Umm probably both.
Developer: Great!
Filter By Colour

The ProductFilter is responsible
for filtering products by colour,
size, colour and size.
public class ProductFilter
{

  {
                        Filter By Colour
  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;
      }
    }
}
OCP Filter
     public abstract class ProductFilterSpeciïŹcation
{
    public IEnumerable<Product> Filter(IList<Product> products)
    {
      return ApplyFilter(products);
    }

    protected abstract IEnumerable<Product> ApplyFilter(IList<Product> products);
}

public class ProductFilter
{
  public IEnumerable<Product> By(IList<Product> products, ProductFilterSpeciïŹcation
                                        ïŹlterSpeciïŹcation)
  {
     return ïŹlterSpeciïŹcation.Filter(products);
  }
}
OCP Filter
     public class ColorFilterSpeciïŹcation : ProductFilterSpeciïŹcation
{
    private readonly ProductColor productColor;

    public ColorFilterSpeciïŹcation(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;
      }
    }
}
Liskov Substitution
         Principle

Functions that use references to base
classes must be able to use objects of
derived classes without knowing it.
LSP Violation
    class Rectangle
{
!   protected int m_width;
!   protected int m_height;

!   public void setWidth(int width){
!   ! m_width = width;
!   }

!   public void setHeight(int height){
!   ! m_height = height;
!   }

!   public int getWidth(){
!   ! return m_width;
!   }

!   public int getHeight(){
!   ! return m_height;
!   }

!   public int getArea(){
!   ! return m_width * m_height;
!   }!
}
LSP Violation
    class Square extends Rectangle
{
!   public void setWidth(int width){
!   ! m_width = width;
!   ! m_height = width;
!   }

!   public void setHeight(int height){
!   ! m_width = height;
!   ! m_height = height;
!   }
}
LSP Violation
    class LspTest
{
!   private static Rectangle getNewRectangle()
!   {
!   ! // it can be an object returned by some factory ...
!   ! return new Square();
!   }

!   public static void main (String args[])
!   {
!   ! Rectangle r = LspTest.getNewRectangle();

!   !   r.setWidth(5);
!   !   r.setHeight(10);
!   !   // user knows that r it's a rectangle.
!   !   // It assumes that he's able to set the width and height as for the base class

!   !   System.out.println(r.getArea());
!   !   // now he's surprised to see that the area is 100 instead of 50.
!   }
}
Interface Segregation
         Principle


Clients should not be forced to depend
on interfaces that they do not use.
ISP Example
    public abstract class Animal
{
    public abstract void Feed();
}

public class Dog : Animal
{
  public override void Feed()
  {
     // do something
  }
}

public class Rattlesnake : Animal
{
  public override void Feed()
  {
     // do something
  }
}
ISP Violation
    public abstract class Animal
{
    public abstract void Feed();
    public abstract void Groom();
}

public class Rattlesnake : Animal
{
  public override void Feed()
  {
     // do something
  }

    public override void Groom()
    {
      // ignore
    }
}
ISP Restored
     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
  }
Handout
public class CustomMembershipProvider : MembershipProvider
{
  public override string ApplicationName
  {
     get
     {
        throw new Exception("The method or operation is not implemented.");
     }
     set
     {
        throw new Exception("The method or operation is not implemented.");
     }
  }

  public override bool ChangePassword(string username, string oldPassword, string
newPassword)
  {
    throw new Exception("The method or operation is not implemented.");
  }

  public override bool ChangePasswordQuestionAndAnswer(string username, string
Dependency Inversion
      Principle
High level modules should not depend
upon low level modules. Both should
depend upon abstractions.
Abstractions should not depend upon
details. Details should depend upon
abstractions.
DIP Violation
    public class OrderProcessor
{
    public decimal CalculateTotal(Order order)
    {
        decimal itemTotal = order.GetItemTotal();
        decimal discountAmount = DiscountCalculator.CalculateDiscount(order);

        decimal taxAmount = 0.0M;

        if (order.Country == "US")
            taxAmount = FindTaxAmount(order);
        else if (order.Country == "UK")
            taxAmount = FindVatAmount(order);

        decimal total = itemTotal - discountAmount + taxAmount;

        return total;
    }

    private decimal FindVatAmount(Order order)
    {
        // find the UK value added tax somehow
        return 10.0M;
    }

    private decimal FindTaxAmount(Order order)
    {
        // find the US tax somehow
        return 10.0M;
    }
}
DIP Restored
    public interface IDiscountCalculator
{
    decimal CalculateDiscount(Order order);
}

public interface ITaxStrategy
{
    decimal FindTaxAmount(Order order);
}

public class OrderProcessor
{
    private readonly IDiscountCalculator _discountCalculator;
    private readonly ITaxStrategy _taxStrategy;

    public OrderProcessor(IDiscountCalculator discountCalculator,
                          ITaxStrategy taxStrategy)
    {
        _taxStrategy = taxStrategy;
        _discountCalculator = discountCalculator;
    }

    public decimal CalculateTotal(Order order)
    {
        decimal itemTotal = order.GetItemTotal();
        decimal discountAmount = _discountCalculator.CalculateDiscount(order);
        decimal taxAmount = _taxStrategy.FindTaxAmount(order);
        decimal total = itemTotal - discountAmount + taxAmount;

        return total;
    }
}
DIP Restored
    public class DiscountCalculatorAdapter : IDiscountCalculator
{
    public decimal CalculateDiscount(Order order)
    {
        return DiscountCalculator.CalculateDiscount(order);
    }
}

public class USTaxStrategy : ITaxStrategy
{
    public decimal FindTaxAmount(Order order)
    {
    }
}

public class UKTaxStrategy : ITaxStrategy
{
    public decimal FindTaxAmount(Order order)
    {
    }
}
Reading
Clean Code: A Handbook of Agile Software
Craftsmanship Robert C. Martin

Design Patterns: Elements of Reusable Object-Oriented
Software Erich Gamma, Richard Helm, Ralph Johnson,
and John Vlissides

Agile Principles, Patterns and Practices in C#
Robert C. Martin

Lean Architecture: for Agile Software Development
James O. Coplien and Gertrud BjĂžrnvig
Photo Credits
SOLID Motivational Posters, by Derick Bailey, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.



                        http://lostechies.com/derickbailey/ïŹles/2011/03/SOLID_6EC97F9C.jpg




                        http://lostechies.com/derickbailey/ïŹles/2011/03/SingleResponsibilityPrinciple2_71060858.jpg




                        http://lostechies.com/derickbailey/ïŹles/2011/03/OpenClosedPrinciple2_2C596E17.jpg




                        http://lostechies.com/derickbailey/ïŹles/2011/03/LiskovSubtitutionPrinciple_52BB5162.jpg




                        http://lostechies.com/derickbailey/ïŹles/2011/03/InterfaceSegregationPrinciple_60216468.jpg




                        http://lostechies.com/derickbailey/ïŹles/2011/03/DependencyInversionPrinciple_0278F9E2.jpg

Weitere Àhnliche Inhalte

Was ist angesagt?

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
Sergey Karpushin
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
akbarashaikh
 

Was ist angesagt? (20)

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
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
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Solid design principles
Solid design principlesSolid design principles
Solid design principles
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design Principles
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Liscov substitution principle
Liscov substitution principleLiscov substitution principle
Liscov substitution principle
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
S.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsS.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software Architects
 
Python SOLID
Python SOLIDPython SOLID
Python SOLID
 
Becoming a better developer by using the SOLID design principles
Becoming a better developer by using the SOLID design principlesBecoming a better developer by using the SOLID design principles
Becoming a better developer by using the SOLID design principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Open Close Principle
Open Close PrincipleOpen Close Principle
Open Close Principle
 

Andere mochten auch

Andere mochten auch (16)

SOLID Principles Part 2
SOLID Principles Part 2SOLID Principles Part 2
SOLID Principles Part 2
 
Sa 006 modifiability
Sa 006 modifiabilitySa 006 modifiability
Sa 006 modifiability
 
Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)Success by Challenging Assumptions (Part 2)
Success by Challenging Assumptions (Part 2)
 
Make yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 BerlinMake yourself replaceable at DevOpsCon 2016 Berlin
Make yourself replaceable at DevOpsCon 2016 Berlin
 
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
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)Success by Challenging Assumptions (Part I)
Success by Challenging Assumptions (Part I)
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 
SOLID Principles part 2
SOLID Principles part 2SOLID Principles part 2
SOLID Principles part 2
 
SOLID Principles part 1
SOLID Principles part 1SOLID Principles part 1
SOLID Principles part 1
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design Patterns
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHP
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Aggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community dayAggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community day
 
Design Thinking is Killing Creativity
Design Thinking is Killing CreativityDesign Thinking is Killing Creativity
Design Thinking is Killing Creativity
 

Ähnlich wie Solid principles

SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Chris Weldon
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
Antoine Sabot-Durand
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
SOLID - Not Just a State of Matter, It's Principles for OO Propriety
SOLID - Not Just a State of Matter, It's Principles for OO ProprietySOLID - Not Just a State of Matter, It's Principles for OO Propriety
SOLID - Not Just a State of Matter, It's Principles for OO Propriety
Chris Weldon
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
Samir Talwar
 

Ähnlich wie Solid principles (20)

SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
DotNet Conference: code smells
DotNet Conference: code smellsDotNet Conference: code smells
DotNet Conference: code smells
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
CodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPigCodingSerbia2014-JavaVSPig
CodingSerbia2014-JavaVSPig
 
Functional Programming with C#
Functional Programming with C#Functional Programming with C#
Functional Programming with C#
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
SOLID - Not Just a State of Matter, It's Principles for OO Propriety
SOLID - Not Just a State of Matter, It's Principles for OO ProprietySOLID - Not Just a State of Matter, It's Principles for OO Propriety
SOLID - Not Just a State of Matter, It's Principles for OO Propriety
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
 
3. ОбъДĐșты, Đșлассы Đž паĐșДты ĐČ Java
3. ОбъДĐșты, Đșлассы Đž паĐșДты ĐČ Java3. ОбъДĐșты, Đșлассы Đž паĐșДты ĐČ Java
3. ОбъДĐșты, Đșлассы Đž паĐșДты ĐČ Java
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
барас ОлДĐșŃĐžĐœ - Sculpt! Your! Tests!
барас ОлДĐșŃĐžĐœ  - Sculpt! Your! Tests!барас ОлДĐșŃĐžĐœ  - Sculpt! Your! Tests!
барас ОлДĐșŃĐžĐœ - Sculpt! Your! Tests!
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
 
SOLID Principles
SOLID PrinciplesSOLID Principles
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...
 
Đ‘ĐŸŃ€Đ”ĐŒŃŃ с NPE ĐČĐŒĐ”ŃŃ‚Đ” с Kotlin, ПаĐČДл йацĐșох ХбДрйДх
Đ‘ĐŸŃ€Đ”ĐŒŃŃ с NPE ĐČĐŒĐ”ŃŃ‚Đ” с Kotlin, ПаĐČДл йацĐșох ĐĄĐ±Đ”Ń€ĐąĐ”Ń…Đ‘ĐŸŃ€Đ”ĐŒŃŃ с NPE ĐČĐŒĐ”ŃŃ‚Đ” с Kotlin, ПаĐČДл йацĐșох ХбДрйДх
Đ‘ĐŸŃ€Đ”ĐŒŃŃ с NPE ĐČĐŒĐ”ŃŃ‚Đ” с Kotlin, ПаĐČДл йацĐșох ХбДрйДх
 

Mehr von Declan Whelan

Mehr von Declan Whelan (18)

Technical debt is a systemic problem - not a personal failing
Technical debt is a systemic problem - not a personal failingTechnical debt is a systemic problem - not a personal failing
Technical debt is a systemic problem - not a personal failing
 
From Technical Debt to Technical Health
From Technical Debt to Technical HealthFrom Technical Debt to Technical Health
From Technical Debt to Technical Health
 
effective agile adoption
effective agile adoptioneffective agile adoption
effective agile adoption
 
Big Balls of Mud
Big Balls of MudBig Balls of Mud
Big Balls of Mud
 
Navigating Organizational Change
Navigating Organizational ChangeNavigating Organizational Change
Navigating Organizational Change
 
Simple Design
Simple DesignSimple Design
Simple Design
 
Domain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with RailsDomain Driven Design and Hexagonal Architecture with Rails
Domain Driven Design and Hexagonal Architecture with Rails
 
Win Win Conversations
Win Win ConversationsWin Win Conversations
Win Win Conversations
 
Agile 2012 Simple Design Applied
Agile 2012 Simple Design AppliedAgile 2012 Simple Design Applied
Agile 2012 Simple Design Applied
 
Releasing your teams energy through 'pull' conversations
Releasing your teams energy through 'pull' conversationsReleasing your teams energy through 'pull' conversations
Releasing your teams energy through 'pull' conversations
 
Specification by Example
Specification by ExampleSpecification by Example
Specification by Example
 
Learning is Key to Agile Success: Agile Vancouver 2010
Learning is Key to Agile Success: Agile Vancouver 2010Learning is Key to Agile Success: Agile Vancouver 2010
Learning is Key to Agile Success: Agile Vancouver 2010
 
Agile learning agile 2010
Agile learning agile 2010Agile learning agile 2010
Agile learning agile 2010
 
Agile Learning (60 minute version)
Agile Learning (60 minute version)Agile Learning (60 minute version)
Agile Learning (60 minute version)
 
Cuke2Beer
Cuke2BeerCuke2Beer
Cuke2Beer
 
Agile Learning from Agile 2009
Agile Learning from Agile 2009Agile Learning from Agile 2009
Agile Learning from Agile 2009
 
Agile, Tdd And .Net
Agile, Tdd And .NetAgile, Tdd And .Net
Agile, Tdd And .Net
 
Agile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile TesterAgile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile Tester
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

KĂŒrzlich hochgeladen (20)

Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Solid principles

  • 1. SOLID Principles Declan Whelan @dwhelan
  • 2.
  • 3. SOLID Principles ‱ Single Responsibility Principle ‱ Open Closed Principle ‱ Liskov Substitution Principle ‱ Interface Segregation Principle ‱ Dependency Inversion Principle
  • 4.
  • 5. Single Responsibility Principle There should be one and only one reason for a class to change.
  • 6. SRP Violation public class UserSettingService {   public void changeEmail(User user)   {     if(checkAccess(user))     {        //Grant option to change     }   }   public boolean checkAccess(User user)   {     //Verify if the user is valid.   } }
  • 7. SRP Restored public class UserSettingService {   public void changeEmail(User user)   {     if(SecurityService.checkAccess(user))     {        //Grant option to change     }   } } public class SecurityService {   public static boolean checkAccess(User user)   {     //check the access.   } }
  • 8.
  • 9. Open Closed Principle Software entities should be open for extension but closed for modification.
  • 10. A Product Filter We need a way to filter products by colour.
  • 11. Class Responsibility The classes’ responsibility is to filter products (its job) based off the action of filtering by colour (its behaviour). The ProductFilter is responsible for filtering products by colour.
  • 12. Filter By Colour public class ProductFilter { public IEnumerable<Product> ByColor(IList<Product> products, ProductColor productColor) { foreach (var product in products) { if (product.Color == productColor) yield return product; } } }
  • 13. More Requirements! User: We also need to filter by size. Developer: Just size or colour and size? User: Umm probably both. Developer: Great!
  • 14. Filter By Colour The ProductFilter is responsible for filtering products by colour, size, colour and size.
  • 15. public class ProductFilter { { Filter By Colour 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; } } }
  • 16. OCP Filter public abstract class ProductFilterSpeciïŹcation { public IEnumerable<Product> Filter(IList<Product> products) { return ApplyFilter(products); } protected abstract IEnumerable<Product> ApplyFilter(IList<Product> products); } public class ProductFilter { public IEnumerable<Product> By(IList<Product> products, ProductFilterSpeciïŹcation ïŹlterSpeciïŹcation) { return ïŹlterSpeciïŹcation.Filter(products); } }
  • 17. OCP Filter public class ColorFilterSpeciïŹcation : ProductFilterSpeciïŹcation { private readonly ProductColor productColor; public ColorFilterSpeciïŹcation(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; } } }
  • 18.
  • 19. Liskov Substitution Principle Functions that use references to base classes must be able to use objects of derived classes without knowing it.
  • 20. LSP Violation class Rectangle { ! protected int m_width; ! protected int m_height; ! public void setWidth(int width){ ! ! m_width = width; ! } ! public void setHeight(int height){ ! ! m_height = height; ! } ! public int getWidth(){ ! ! return m_width; ! } ! public int getHeight(){ ! ! return m_height; ! } ! public int getArea(){ ! ! return m_width * m_height; ! }! }
  • 21. LSP Violation class Square extends Rectangle { ! public void setWidth(int width){ ! ! m_width = width; ! ! m_height = width; ! } ! public void setHeight(int height){ ! ! m_width = height; ! ! m_height = height; ! } }
  • 22. LSP Violation class LspTest { ! private static Rectangle getNewRectangle() ! { ! ! // it can be an object returned by some factory ... ! ! return new Square(); ! } ! public static void main (String args[]) ! { ! ! Rectangle r = LspTest.getNewRectangle(); ! ! r.setWidth(5); ! ! r.setHeight(10); ! ! // user knows that r it's a rectangle. ! ! // It assumes that he's able to set the width and height as for the base class ! ! System.out.println(r.getArea()); ! ! // now he's surprised to see that the area is 100 instead of 50. ! } }
  • 23.
  • 24. Interface Segregation Principle Clients should not be forced to depend on interfaces that they do not use.
  • 25. ISP Example public abstract class Animal { public abstract void Feed(); } public class Dog : Animal { public override void Feed() { // do something } } public class Rattlesnake : Animal { public override void Feed() { // do something } }
  • 26. ISP Violation public abstract class Animal { public abstract void Feed(); public abstract void Groom(); } public class Rattlesnake : Animal { public override void Feed() { // do something } public override void Groom() { // ignore } }
  • 27. ISP Restored 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 }
  • 28. Handout public class CustomMembershipProvider : MembershipProvider { public override string ApplicationName { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new Exception("The method or operation is not implemented."); } public override bool ChangePasswordQuestionAndAnswer(string username, string
  • 29.
  • 30. Dependency Inversion Principle High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
  • 31. DIP Violation public class OrderProcessor { public decimal CalculateTotal(Order order) { decimal itemTotal = order.GetItemTotal(); decimal discountAmount = DiscountCalculator.CalculateDiscount(order); decimal taxAmount = 0.0M; if (order.Country == "US") taxAmount = FindTaxAmount(order); else if (order.Country == "UK") taxAmount = FindVatAmount(order); decimal total = itemTotal - discountAmount + taxAmount; return total; } private decimal FindVatAmount(Order order) { // find the UK value added tax somehow return 10.0M; } private decimal FindTaxAmount(Order order) { // find the US tax somehow return 10.0M; } }
  • 32. DIP Restored public interface IDiscountCalculator { decimal CalculateDiscount(Order order); } public interface ITaxStrategy { decimal FindTaxAmount(Order order); } public class OrderProcessor { private readonly IDiscountCalculator _discountCalculator; private readonly ITaxStrategy _taxStrategy; public OrderProcessor(IDiscountCalculator discountCalculator, ITaxStrategy taxStrategy) { _taxStrategy = taxStrategy; _discountCalculator = discountCalculator; } public decimal CalculateTotal(Order order) { decimal itemTotal = order.GetItemTotal(); decimal discountAmount = _discountCalculator.CalculateDiscount(order); decimal taxAmount = _taxStrategy.FindTaxAmount(order); decimal total = itemTotal - discountAmount + taxAmount; return total; } }
  • 33. DIP Restored public class DiscountCalculatorAdapter : IDiscountCalculator { public decimal CalculateDiscount(Order order) { return DiscountCalculator.CalculateDiscount(order); } } public class USTaxStrategy : ITaxStrategy { public decimal FindTaxAmount(Order order) { } } public class UKTaxStrategy : ITaxStrategy { public decimal FindTaxAmount(Order order) { } }
  • 34. Reading Clean Code: A Handbook of Agile Software Craftsmanship Robert C. Martin Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides Agile Principles, Patterns and Practices in C# Robert C. Martin Lean Architecture: for Agile Software Development James O. Coplien and Gertrud BjĂžrnvig
  • 35. Photo Credits SOLID Motivational Posters, by Derick Bailey, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License. http://lostechies.com/derickbailey/ïŹles/2011/03/SOLID_6EC97F9C.jpg http://lostechies.com/derickbailey/ïŹles/2011/03/SingleResponsibilityPrinciple2_71060858.jpg http://lostechies.com/derickbailey/ïŹles/2011/03/OpenClosedPrinciple2_2C596E17.jpg http://lostechies.com/derickbailey/ïŹles/2011/03/LiskovSubtitutionPrinciple_52BB5162.jpg http://lostechies.com/derickbailey/ïŹles/2011/03/InterfaceSegregationPrinciple_60216468.jpg http://lostechies.com/derickbailey/ïŹles/2011/03/DependencyInversionPrinciple_0278F9E2.jpg

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n