0% found this document useful (0 votes)
5 views

NET

The document outlines the SOLID principles of object-oriented programming, including the Single Responsibility Principle, Open Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. Each principle is defined, explained with examples, and discussed in terms of problems and solutions related to software design. The document emphasizes the importance of these principles in creating maintainable and flexible code.

Uploaded by

Danh Truong Quoc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

NET

The document outlines the SOLID principles of object-oriented programming, including the Single Responsibility Principle, Open Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. Each principle is defined, explained with examples, and discussed in terms of problems and solutions related to software design. The document emphasizes the importance of these principles in creating maintainable and flexible code.

Uploaded by

Danh Truong Quoc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

SOLID OOP

Huan
AGENDA
❖ The Single Responsibility Principle

❖ The Open Closed Principle

❖ The Liskov Substitution Principle

❖ The Interface Segregation Principle

❖ The Dependency Inversion Principle

❖ The Don't Repeat Yourself Principle


SRP PRICIPLE
❖ SRP Defined

❖ Cohesion and coupling

❖ Responsibilities are axes of change

❖ Example
SRP PRICIPLE
SRP Defined

Every object should have a single responsibility, and that


responsibility should be entirely encapsulated by the class

There should never be more than one reason for a class to


change
SRP PRICIPLE
Cohesion & Coupling

Cohesion
How strongly-related and focused are the various responsibilities of a
module

Coupling
The degree to which each program module relies on each one of the
other modules
SRP PRICIPLE
Cohesion & Coupling
SRP PRICIPLE
Cohesion & Coupling
SRP PRICIPLE
Responsibility 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.
SRP PRICIPLE
Example
Process

1. Credit Order
Retail
• Checkout
• Payment- Credit Card
2. Cash Order
• Checkout Operations
Order 1. Checkout
2. Payment
3. Notify Customer
4. Reserve
Process
Inventory
Online 1. Online Order
• Checkout
• Payment - Credit Card
• Notify Customer
• Reserve Inventory
SRP PRICIPLE
Example
SRP PRICIPLE
Example
SRP PRICIPLE
Example - Problems

1. Cash Transactions Don't Need Credit Card Processing


2. Point of Sale Transactions Don't Need Inventory
Reservations
• Store inventory is updated separately in our system
3. Point of Sale Transactions Don't Need Email Notifications
• The customer doesn't provide an email
• The customer knows immediately that the order was a success

4. Any change to notifications, credit card processing, or


inventory management will affect Order as well as the Web and
Point of Sale implementations of Order
SRP PRICIPLE
Example - Solution
SRP PRICIPLE
How to separate design of object

Service 1 Service 2

Object

Applications UI
The OCP Principle

❖ OCP Defined

❖ Change behavior without changing code?

❖ Demo

❖ When do we apply OCP?


OCP PRICIPLE
OCP Defined

The Open/Closed Principle states that software


entities (Classes, Modules, Functions, etc.) should be
open for extension, but closed for modification.
Wikipedia
OCP PRICIPLE
OCP Defined

Open to extension
New behavior can be added in the future.

Closed to Modification
Changes to source or binary code are not required.
OCP PRICIPLE
OCP Defined
⮚ A module will be said to be open if it is still 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 will be said to be 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).

⮚ A class is closed, since it may be compiled, stored in a library, baselined,


and used by client classes. But it is also open, since any new class may
use it as parent, adding new features. When a descendant class is
defined, there is no need to change the original or to disturb its clients
OCP PRICIPLE
Change behavior without changing
code?
Rely on abstractions

No limit to variety of implementations each abstractions

In .NET, abstractions include:


• Interfaces
• Abstract Base Classes

In procedural code, some level of OCP can be achieved via


parameters
OCP PRICIPLE
Demo
Attributes Order Item

1. Order Items 1. Type


2. Amount – By Formula

Cart

Operations

1. Total Amount Sum Amount of All


Items
OCP PRICIPLE
Demo
OCP PRICIPLE
Problems Demo

Adding new rules require changes to the calculator 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
OCP PRICIPLE
Solutions Demo

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
• Implementation utilise Inheritance/ Client utilises Composition
OCP PRICIPLE
Solutions- Composition / Strategy Pattern Demo
Cart
Attributes
1. Calculator – Object
2. Order Items - Objects
Operations
Calculator
1. Total Amount
Attributes
1. Price Rules – Objects
Operations
1. Calculate Price – By Price Rule

Price Rule

Operations
1. Is Match – By Order Item (_Type)
2. Calculate Price – By Order Item
OCP PRICIPLE
Solutions- Composition / Strategy Pattern Demo
OCP PRICIPLE
Solutions- Composition / Strategy Pattern Demo
OCP PRICIPLE
Signal
Object M1
Attributes
Object M Operations
1. RunType
Attributes Type A Object M3
Operations
1. RunType Attributes
+ Type A Operations
+ Type B 1. RunType
…….. Object M2 Type N
+ Type N Attributes
Operations
1. RunType
Type B
OCP PRICIPLE
When do we apply OCP?
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

There Ain’t No Such Thing As A Free Lunch


OCP adds complexity to design
No design can be closed against all changes
The LSP Principle

❖ LSP Defined

❖ Demo
⮚ Problems
⮚ Solution

❖ LSP Smells
LSP PRICIPLE
LSP Defined

The Liskov Substitution Principle states that


Subtypes must be substitutable for their base types.
LSP PRICIPLE
Substitutability

Child classes must not:


• Remove base class behavior
• Violate base class invariants

And in general must not require calling code to know


they are different from their base type.
LSP PRICIPLE
Inheritance and the IS-A
Relationship

Native OOP teaches use of IS-A to describe child classes’


relationship to base classes

LSP suggests that IS-A should be replaced with


IS-SUBSTITUTABLE-FOR
LSP PRICIPLE
Invariants
Consist of reasonable assumptions of behavior by clients
Can be expressed as preconditions and post-conditions for
methods
Frequently, unit tests are used to specify expected behavior
of a method or class

Design By Contract is a technique that makes defining these


pre- and post-conditions explicit within code itself.

To follow LSP, derived classes must not violate any


constraints defined (or assumed by clients) on the base classes
LSP PRICIPLE
Demo

In Math: Square is a Rectangle


LSP PRICIPLE
Demo
Rectangle Square
Attributes Attributes
1. Width 1. Width
2. Height 2. Height Square = Rectangle ?
Operations Operations
1. Areas 1. Areas
(Width*Height) (Height*Height) A Square is a Rectangle

A Square is not substitutable for a Rectangle ?


LSP PRICIPLE
The Problems s

Non-substitutable code breaks polymorphism

Client code expects child classes to work in place of their base


classes

“Fixing” substitutability problems by adding if-then or switch


statements quickly becomes a maintenance nightmare (and
violates OCP)
LSP PRICIPLE
Solutions
Shape (Abstract)
Operations
1. Areas

Rectangle Square
Attributes Attributes
1. Width 1. Height
2. Height Operations
Operations 1. Areas
1. Areas (Height*Height)
(Width*Height)
LSP PRICIPLE
LSP Violation Smells
The ISP Principle

The Interface Segregation


Principle
❖ ISP Defined

❖ Demo
⮚ Problems
⮚ Solutions

❖ ISP Smells

❖ When do we fix ISP?

❖ ISP Tips
ISP Principle

ISP Defined

The Interface Segregation Principle states that Clients


should not be forced to depend on methods they do not
use.
Agile Principles, Patterns, and Practices in C#
ISP Principle

ISP Defined
ISP Principle

Demo
ISP Principle

Demo
ISP Principle

Demo
ISP Principle

Problems Demo

AboutPage simply needs ApplicationName and AuthorName

Forced to deal with huge ConfigurationSettings class

Forced to deal with actual configuration files

Interface Segregation violations result in classes that depend


on things they do not need, increasing coupling and reducing
flexibility and maintainability
ISP Principle

Solutions Demo
ISP Principle

Solutions
ISP Principle

IPS Smells
Unimplemented interface methods

Client references a class but only uses small portion of it


ISP Principle

When do we fix ISP?


Once there is pain
• If there is no pain, there’s no problem to address.

If you find yourself depending on a “fat” interface you own


• Create a smaller interface with just what you need
• Have the fat interface implement your new interface
• Reference the new interface with your code

If you find “fat” interfaces are problematic but you do not own
them
• Create a smaller interface with just what you need
• Implement this interface using an Adapter that implements the full
interface
ISP Principle

ISP Tips
Keep interfaces small, cohesive, and focused
• Don’t force client code to depend on things it doesn’t need

Whenever possible, let the client define the interface

Whenever possible, package the interface with the client


• Alternately, package in a third assembly client and implementation
both depend upon
▪ Last resort: Package interfaces with their implementation
The DI Principle
The Dependency Inversion
Principle
❖ DI Defined

❖ Demo
⮚ Problems
⮚ Solutions

❖ Dependency Injection

❖ DIP Smells

❖ ISP Tips
DI Principle
DI Defined

High-level modules should not depend on low-level


modules. Both should depend on abstractions.

Abstractions should not depend on details. Details


should depend on abstractions.
Agile Principles, Patterns, and Practices in
C#
DI Principle
What are dependencies
• Framework
• Third Party Libraries
• Database
• File System
• Email
• Web Services
• System Resources (Clock)
• Configuration
• The new Keyword
• Static methods
• Thread.Sleep
• Random
DI Principle
Traditional Program and
Dependencies
High Level Modules Call Low Level Modules

User Interface depends on


Business Logic depends on
• Infrastructure
• Utility
• Data Access

Static methods are used for convenience or as Façade layers

Class instantiation/Call stack logic is scattered through all


modules
Violation of Single Responsibility Principle
DI Principle
Demo
DI Principle
Demo
DI Principle
Problems
Order has hidden dependencies:
• MailMessage
• SmtpClient
• InventorySystem
• PaymentGateway
• Logger
• DateTime.Now

Result
• Tight coupling
• No way to change implementation details (OCP violation)
• Difficult to test
DI Principle
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.

Three Primary Techniques


• Constructor Injection
• Property Injection
• Parameter Injection
DI Principle
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)
DI Principle
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
DI Principle
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
DI Principle
Solutions

Extract Dependencies into Interfaces

Inject implementations of interfaces into Order

Reduce Order’s responsibilities (apply SRP)


Thank You

Q&A

You might also like