SlideShare a Scribd company logo
1 of 39
SOLID principles
What makes a good software?
Promote object orient programming
and design
Promote code reuse
Prevent duplicated code
Promote adaptive software
development
Keep things simple + YAGNI
Basic principles
• Degree to which each program
module relies on each one of
the other modules.
Coupling
• Degree to which elements
belong together.
Cohesion
• Make objects interchangeable,
and guards their states from
invalid changes
Encapsulation
Cohesion levels
WORST
• Coincidental  Logical  Temporal
• Procedural  Communicational
• Sequencial
BEST
• Functional
Coupling
public void DoSomething() {
// Go get some configuration
int threshold =
int.Parse(ConfigurationManager.AppSettings["thr
eshold"]);
string connectionString =
ConfigurationManager.AppSettings["connectionSt
ring"];
string sql =
@"select * from things
size > ";
sql += threshold;
using (SqlConnection connection =
new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new
SqlCommand(sql, connection);
using (SqlDataReader reader =
command.ExecuteReader()) {
while (reader.Read()) {
string name = reader["Name"].ToString();
string destination =
reader["destination"].ToString();
// do some business logic in here
doSomeBusinessLogic(name, destination,
connection);
} ….} }
Coupling
public void DoSomething() {
// Go get some configuration
int threshold =
int.Parse(ConfigurationManager.AppSettings["thr
eshold"]);
string connectionString =
ConfigurationManager.AppSettings["connectionSt
ring"];
string sql =
@"select * from things
size > ";
sql += threshold;
using (SqlConnection connection =
new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new
SqlCommand(sql, connection);
using (SqlDataReader reader =
command.ExecuteReader()) {
while (reader.Read()) {
string name = reader["Name"].ToString();
string destination =
reader["destination"].ToString();
// do some business logic in here
doSomeBusinessLogic(name, destination,
connection);
} ….} }
SOLID principles
• Single responsibility principleSRP
• Open/Closed principleOCP
• Liskov substitution principleLSP
• Interface segregation principleISP
• Dependency inversion principleDIP
S - Single responsibility principle (SRP)
Object should have only a single responsibility.
Single responsibility principle
Responsibility 1:
Station related
Responsibility 2:
Volume related
Single responsibility principle
Responsibility 1:
Station related
Responsibility 2:
Volume related
O - Open/closed principle (OCP)
Object should be open for extension, but closed
for modification.
Open/closed principle
Open for
extension?
Closed for
modification?
Open/closed principle
DrawShape in GraphicEditor
{
public void DrawShape(Shape s)
{
if (s._type == 1)
{
DrawRectangle((Rectangle)s);
}
else if (s._type == 2)
{
DrawCircle((Circle)s);
}
}
Drawing in GraphicEditor
public void DrawRectangle(Rectangle
s)
{
Console.WriteLine("Rectangle");
}
public void DrawCircle(Circle s)
{
Console.WriteLine("Circle");
}
}
Open/closed principle
Open for extension
Closed for
modification
L - Liskov substitution principle (LSP)
Derived classes must be substitutable for their
base classes.
Liskov substitution principle
Is a square rectangle?
Liskov substitution principle
public void SetWidth(Rectangle rect, int
width)
{
rect.Width = width;
}
-------------------------------
Rectangle rect =
new Rectangle(50, 20);
SetWidth(rect, 100);
Assert.AreEqual(20,rect.Height);
Liskov substitution principle
Is a square rectangle?
Liskov substitution principle
I - Interface segregation principle (ISP)
Clients should not be forced to implement
interfaces they don’t use.
Or as Uncle Bob puts it: Make fine grained
interfaces that are client specific.
Interface segregation principle
Calendar
date
required for
birthday?
Interface segregation principle
Calendar
date
required for
birthday?
D - Dependency inversion principle
(DIP)
high-level classes should not depend on low-
level classes. Both should depend on
abstractions.
Abstractions should not depend on details.
Details should depend on abstractions.
Dependency inversion principle
public class BirthdayCalculator
{
private readonly List<Birthday> _birthdays;
public BirthdayCalculator()
{
_birthdays = new List<Birthday>();
}
public List<Birthday> Birthdays
{
get { return _birthdays; }
}
public List<Birthday> GetTodaysBirthdays()
{
return _birthdays
.Where(bd => bd.Date.Month == DateTime.Now.Date.Month)
.Where(bd => bd.Date.Day == DateTime.Now.Date.Day)
.ToList();
}
}
Dependency inversion principle
public class BirthdayCalculator
{
private readonly List<Birthday> _birthdays;
public BirthdayCalculator()
{
_birthdays = new List<Birthday>();
}
public List<Birthday> Birthdays
{
get { return _birthdays; }
}
public List<Birthday> GetTodaysBirthdays()
{
return _birthdays
.Where(bd => bd.Date.Month == DateTime.Now.Date.Month)
.Where(bd => bd.Date.Day == DateTime.Now.Date.Day)
.ToList();
}
}
Dependency inversion principle
public class BirthdayCalculator
{
private readonly IList<Birthday> _birthdays;
public BirthdayCalculator(IList<Birthday> birthdays)
{
_birthdays = birthdays;
}
public IList<Birthday> Birthdays
{
get { return _birthdays; }
}
public IList<Birthday> GetBirthdays(DateTime checkDate)
{
return _birthdays
.Where(bd => bd.Date.Day == checkDate.Day)
.Where(bd => bd.Date.Month == checkDate.Month)
.ToList();
}
}
QUIZ 1/5
A class should have one, and only one,
reason to change.
SRP
QUIZ 2/5
You should be able to extend a classes
behavior, without modifying it.
OCP
QUIZ 3/5
References to base classes must be able to use
objects of derived classes without knowing it
LSP
QUIZ 4/5
Make fine grained interfaces that are client
specific.
ISP
QUIZ 5/5
Depend on abstractions, not on concretions.
DIP
Correlations
• SRP correlates with the DIP since the abstraction
of responsibilities is often reached by inversion of
dependecies.
• OCP correlates with the DIP since the openness
for change is opften reached by inversion of
dependecies.
• DIP correlates with OCP, since there is the chance
that new requirements could be satisfied by
adding details to existing abstractions.

More Related Content

What's hot

Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Guillaume Laforge
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersJoris Verbogt
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterMithun T. Dhar
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploitsPriyanka Aash
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 

What's hot (20)

Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013
 
Specs2
Specs2Specs2
Specs2
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Es.next
Es.nextEs.next
Es.next
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 

Viewers also liked (13)

Total Knee Replacement Surgery - Pain-Free Knee Mobility
Total Knee Replacement Surgery - Pain-Free Knee MobilityTotal Knee Replacement Surgery - Pain-Free Knee Mobility
Total Knee Replacement Surgery - Pain-Free Knee Mobility
 
Thr ss 2
Thr ss 2Thr ss 2
Thr ss 2
 
Total knee replacement
Total knee replacementTotal knee replacement
Total knee replacement
 
Thr, tkr
Thr, tkrThr, tkr
Thr, tkr
 
Total Hip Replacement
Total Hip ReplacementTotal Hip Replacement
Total Hip Replacement
 
TOTAL KNEE REPLACEMENT
TOTAL KNEE REPLACEMENTTOTAL KNEE REPLACEMENT
TOTAL KNEE REPLACEMENT
 
Tkr by dr. saumya agarwal
Tkr by dr. saumya agarwalTkr by dr. saumya agarwal
Tkr by dr. saumya agarwal
 
Total Knee Replacement
Total Knee ReplacementTotal Knee Replacement
Total Knee Replacement
 
Total Knee Replacement
Total Knee ReplacementTotal Knee Replacement
Total Knee Replacement
 
Total Knee Replacement
Total Knee ReplacementTotal Knee Replacement
Total Knee Replacement
 
Primary total knee arthroplasty
Primary total knee arthroplastyPrimary total knee arthroplasty
Primary total knee arthroplasty
 
Total hip arthroplasty
Total hip arthroplastyTotal hip arthroplasty
Total hip arthroplasty
 
Total knee replacement (tkr) ppt
Total knee replacement (tkr) pptTotal knee replacement (tkr) ppt
Total knee replacement (tkr) ppt
 

Similar to Solid principles

Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversRebecca Mills
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC PrinciplesPavlo Hodysh
 
Expanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerExpanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerCisco Canada
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernates4al_com
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integrationPeter Gfader
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020Geir Høydalsvik
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMax Kleiner
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 

Similar to Solid principles (20)

Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra Drivers
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Expanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerExpanding your impact with programmability in the data center
Expanding your impact with programmability in the data center
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integration
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
 
B_110500002
B_110500002B_110500002
B_110500002
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Vhdl new
Vhdl newVhdl new
Vhdl new
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 

More from Hanokh Aloni

NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!Hanokh Aloni
 
CI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUCI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUHanokh Aloni
 
How to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHow to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHanokh Aloni
 
Architectural kata 0 of n.pptx
Architectural kata 0 of n.pptxArchitectural kata 0 of n.pptx
Architectural kata 0 of n.pptxHanokh Aloni
 
Code smells (1).pptx
Code smells (1).pptxCode smells (1).pptx
Code smells (1).pptxHanokh Aloni
 
top developer mistakes
top developer mistakes top developer mistakes
top developer mistakes Hanokh Aloni
 
Things senior developers should know
Things senior developers should knowThings senior developers should know
Things senior developers should knowHanokh Aloni
 
Cynefin framework in software engineering
Cynefin framework in software engineeringCynefin framework in software engineering
Cynefin framework in software engineeringHanokh Aloni
 
Trunk based vs git flow
Trunk based vs git flowTrunk based vs git flow
Trunk based vs git flowHanokh Aloni
 
How to write unmaintainable code
How to write unmaintainable codeHow to write unmaintainable code
How to write unmaintainable codeHanokh Aloni
 
How i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHow i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHanokh Aloni
 
Game is ggj2018 presentation
Game is ggj2018 presentationGame is ggj2018 presentation
Game is ggj2018 presentationHanokh Aloni
 
Game is ggj2017 presentation
Game is ggj2017 presentationGame is ggj2017 presentation
Game is ggj2017 presentationHanokh Aloni
 
02 terms and issues
02 terms and issues02 terms and issues
02 terms and issuesHanokh Aloni
 

More from Hanokh Aloni (20)

NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!
 
CI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUCI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOU
 
How to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHow to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptx
 
Architectural kata 0 of n.pptx
Architectural kata 0 of n.pptxArchitectural kata 0 of n.pptx
Architectural kata 0 of n.pptx
 
Code smells (1).pptx
Code smells (1).pptxCode smells (1).pptx
Code smells (1).pptx
 
NWD the73js.pptx
NWD the73js.pptxNWD the73js.pptx
NWD the73js.pptx
 
top developer mistakes
top developer mistakes top developer mistakes
top developer mistakes
 
Things senior developers should know
Things senior developers should knowThings senior developers should know
Things senior developers should know
 
Cynefin framework in software engineering
Cynefin framework in software engineeringCynefin framework in software engineering
Cynefin framework in software engineering
 
Microservices
MicroservicesMicroservices
Microservices
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
 
Trunk based vs git flow
Trunk based vs git flowTrunk based vs git flow
Trunk based vs git flow
 
How to write unmaintainable code
How to write unmaintainable codeHow to write unmaintainable code
How to write unmaintainable code
 
How i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHow i learned to stop worrying and love the logs
How i learned to stop worrying and love the logs
 
Game is ggj2018 presentation
Game is ggj2018 presentationGame is ggj2018 presentation
Game is ggj2018 presentation
 
Microservices
MicroservicesMicroservices
Microservices
 
Game is ggj2017 presentation
Game is ggj2017 presentationGame is ggj2017 presentation
Game is ggj2017 presentation
 
02 terms and issues
02 terms and issues02 terms and issues
02 terms and issues
 
Sip introduction
Sip introductionSip introduction
Sip introduction
 
Tdd guide
Tdd guideTdd guide
Tdd guide
 

Recently uploaded

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 

Recently uploaded (20)

(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 

Solid principles

  • 2. What makes a good software?
  • 3. Promote object orient programming and design Promote code reuse Prevent duplicated code Promote adaptive software development Keep things simple + YAGNI
  • 4. Basic principles • Degree to which each program module relies on each one of the other modules. Coupling • Degree to which elements belong together. Cohesion • Make objects interchangeable, and guards their states from invalid changes Encapsulation
  • 5. Cohesion levels WORST • Coincidental  Logical  Temporal • Procedural  Communicational • Sequencial BEST • Functional
  • 6. Coupling public void DoSomething() { // Go get some configuration int threshold = int.Parse(ConfigurationManager.AppSettings["thr eshold"]); string connectionString = ConfigurationManager.AppSettings["connectionSt ring"]; string sql = @"select * from things size > "; sql += threshold; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(sql, connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string name = reader["Name"].ToString(); string destination = reader["destination"].ToString(); // do some business logic in here doSomeBusinessLogic(name, destination, connection); } ….} }
  • 7. Coupling public void DoSomething() { // Go get some configuration int threshold = int.Parse(ConfigurationManager.AppSettings["thr eshold"]); string connectionString = ConfigurationManager.AppSettings["connectionSt ring"]; string sql = @"select * from things size > "; sql += threshold; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(sql, connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string name = reader["Name"].ToString(); string destination = reader["destination"].ToString(); // do some business logic in here doSomeBusinessLogic(name, destination, connection); } ….} }
  • 8. SOLID principles • Single responsibility principleSRP • Open/Closed principleOCP • Liskov substitution principleLSP • Interface segregation principleISP • Dependency inversion principleDIP
  • 9. S - Single responsibility principle (SRP) Object should have only a single responsibility.
  • 10. Single responsibility principle Responsibility 1: Station related Responsibility 2: Volume related
  • 11. Single responsibility principle Responsibility 1: Station related Responsibility 2: Volume related
  • 12. O - Open/closed principle (OCP) Object should be open for extension, but closed for modification.
  • 14. Open/closed principle DrawShape in GraphicEditor { public void DrawShape(Shape s) { if (s._type == 1) { DrawRectangle((Rectangle)s); } else if (s._type == 2) { DrawCircle((Circle)s); } } Drawing in GraphicEditor public void DrawRectangle(Rectangle s) { Console.WriteLine("Rectangle"); } public void DrawCircle(Circle s) { Console.WriteLine("Circle"); } }
  • 15. Open/closed principle Open for extension Closed for modification
  • 16. L - Liskov substitution principle (LSP) Derived classes must be substitutable for their base classes.
  • 17. Liskov substitution principle Is a square rectangle?
  • 18. Liskov substitution principle public void SetWidth(Rectangle rect, int width) { rect.Width = width; } ------------------------------- Rectangle rect = new Rectangle(50, 20); SetWidth(rect, 100); Assert.AreEqual(20,rect.Height);
  • 19. Liskov substitution principle Is a square rectangle?
  • 21. I - Interface segregation principle (ISP) Clients should not be forced to implement interfaces they don’t use. Or as Uncle Bob puts it: Make fine grained interfaces that are client specific.
  • 24. D - Dependency inversion principle (DIP) high-level classes should not depend on low- level classes. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
  • 25. Dependency inversion principle public class BirthdayCalculator { private readonly List<Birthday> _birthdays; public BirthdayCalculator() { _birthdays = new List<Birthday>(); } public List<Birthday> Birthdays { get { return _birthdays; } } public List<Birthday> GetTodaysBirthdays() { return _birthdays .Where(bd => bd.Date.Month == DateTime.Now.Date.Month) .Where(bd => bd.Date.Day == DateTime.Now.Date.Day) .ToList(); } }
  • 26. Dependency inversion principle public class BirthdayCalculator { private readonly List<Birthday> _birthdays; public BirthdayCalculator() { _birthdays = new List<Birthday>(); } public List<Birthday> Birthdays { get { return _birthdays; } } public List<Birthday> GetTodaysBirthdays() { return _birthdays .Where(bd => bd.Date.Month == DateTime.Now.Date.Month) .Where(bd => bd.Date.Day == DateTime.Now.Date.Day) .ToList(); } }
  • 27. Dependency inversion principle public class BirthdayCalculator { private readonly IList<Birthday> _birthdays; public BirthdayCalculator(IList<Birthday> birthdays) { _birthdays = birthdays; } public IList<Birthday> Birthdays { get { return _birthdays; } } public IList<Birthday> GetBirthdays(DateTime checkDate) { return _birthdays .Where(bd => bd.Date.Day == checkDate.Day) .Where(bd => bd.Date.Month == checkDate.Month) .ToList(); } }
  • 28. QUIZ 1/5 A class should have one, and only one, reason to change. SRP
  • 29. QUIZ 2/5 You should be able to extend a classes behavior, without modifying it. OCP
  • 30. QUIZ 3/5 References to base classes must be able to use objects of derived classes without knowing it LSP
  • 31. QUIZ 4/5 Make fine grained interfaces that are client specific. ISP
  • 32. QUIZ 5/5 Depend on abstractions, not on concretions. DIP
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39. Correlations • SRP correlates with the DIP since the abstraction of responsibilities is often reached by inversion of dependecies. • OCP correlates with the DIP since the openness for change is opften reached by inversion of dependecies. • DIP correlates with OCP, since there is the chance that new requirements could be satisfied by adding details to existing abstractions.

Editor's Notes

  1. S.O.L.I.D. is a collection of best-practice object-oriented design principles that you can apply to your design to accomplish various desirable goals like loose-coupling, higher maintainability, intuitive location of interesting code, etc.  S.O.L.I.D. is an acronym for the following principles (which are, themselves acronyms — confused yet?).
  2. עקרונות בסיסיים: Cohesion refers to the degree to which the elements of a module belong together לכידות– מדד לכידות (באנגלית: Cohesion) מייצג את חוזק הקשר הפונקציונלי בין פעולות שונות תחת אותו מודול. מונח זה הומצא על ידי מהנדס תוכנה אמריקאי בשם לארי קונסטנטין, כחלק משיטה שפיתח להערכת איכות של תוכנה. מונח נוסף אשר הומצא במסגרת שיטה זו הוא מדד הצימוד (Coupling), המתייחס לרמת התלות בין המודולים השונים. לכידות גבוהה, במקרים רבים, היא סימן לצמידות נמוכה ולהיפך. בהערכת איכותו של קוד תוכנה, יועדף קוד בעל לכידות גבוהה, המהווה סימן לתכונות חיוביות וחשובות שעל הקוד לקיים, הכוללות חוסן, אמינות, יכולת שימוש מחדש ויכולת הבנה גבוהה. מאידך, לכידות נמוכה מרמזת על תכונות שליליות הכוללות קושי בתחזוקה, קושי בבדיקות, יכולת שימוש מחדש נמוכה ויכולת הבנה נמוכה. Coupling Given two lines of code, A and B, they are coupled when B must change behavior only because A changed. coupling or dependency is the degree to which each program module relies on each one of the other modules. צימוד – בהערכת איכותו של קוד תוכנה, יועדף קוד בעל צמידות נמוכה, המהווה סימן לכך שהקוד תוכנן כהלכה ובנוי היטב. על מנת להשיג צמידות נמוכה, יש לתכנן כל מודול כיחידה עצמאית ככל הניתן, אשר תלויה כמה שפחות במודולים נוספים במערכת. במצב זה, במידה שיידרשו שינויים בקוד, אלו יבוצעו ביתר קלות כיוון ששינוי במודול מסוים לא יאלץ שינויים בכל המערכת. שילוב של צמידות נמוכה ולכידות גבוהה הוא סימן לכך שהקוד בעל יכולת תחזוקה גבוהה, מצביע על חוסן, אמינות, יכולת שימוש מחדש ויכולת הבנה גבוהה של הקוד. Encapsulation enclosing objects in a common interface in a way that makes them interchangeable, and guards their states from invalid changes כימוס Coupling refers to the degree to which one class knows about or uses members of another class. Loose coupling is the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage. Tight coupling is the undesirable state of having classes that break the rules of loose coupling. Cohesion refers to the degree in which a class has a single, well-defined role or responsibility. High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility. Low cohesion is the undesirable state of a class whose members support multiple, unfocused roles or responsibilities. ניתן לסווג קוד לאחת מרמות הסיווג הבאות (מהטובה ביותר אל הגרועה ביותר): לכידות פונקציונלית (Functional Cohesion) - פעולות במודול תורמות כולן למשימה בודדת ומוגדרת היטב של המודול. לכידות סדרתית (Sequential Cohesion) - פעולות במודול מקובצות תחתיו כיוון שהפלט של פעולות מסוימות הינו הקלט של פעולות אחרות. לכידות תקשורתית (Communicational Cohesion) - פעולות במודול מקובצות תחתיו כיוון שהן פועלות על אותו המידע. לכידות פרוצדורלית (Procedural Cohesion) - פעולות במודול מקובצות תחתיו כיוון שהן תמיד מבוצעות יחד כחלק מהליך של המערכת (לדוגמה, פעולת בקשת הרשאות ופעולת פתיחת קובץ המבוצעות בזו אחר זו). לכידות טמפורלית (Temporal Cohesion) - כאשר הפעולות במודול מקובצות תחתיו כיוון שהן מבצעות את פעולותיהן במהלך פרק זמן מוגדר במהלך ריצת התוכנית. לכידות לוגית (Logic Cohesion) - כאשר הפעולות במודול מקובצות תחתיו כיוון שהן מבצעות משימות דומות, גם כאשר הינן שונות מטבען (לדוגמה, קיבוץ כל פעולות הקלט תחת אותו מודול). לכידות מקרית (Coincidental Cohesion) - הפעולות במודול מקובצות תחתיו באופן שרירותי, כאשר הקשר היחיד בין הפעולות הוא בכך שקובצו יחדיו תחת אותו מודול.
  3. Coincidental cohesion (worst) Coincidental cohesion is when parts of a module are grouped arbitrarily; the only relationship between the parts is that they have been grouped together (e.g. a “Utilities” class). Logical cohesion Logical cohesion is when parts of a module are grouped because they logically are categorized to do the same thing, even if they are different by nature (e.g. grouping all mouse and keyboard input handling routines). Temporal cohesion Temporal cohesion is when parts of a module are grouped by when they are processed - the parts are processed at a particular time in program execution (e.g. a function which is called after catching an exception which closes open files, creates an error log, and notifies the user). Procedural cohesion Procedural cohesion is when parts of a module are grouped because they always follow a certain sequence of execution (e.g. a function which checks file permissions and then opens the file). Communicational cohesion Communicational cohesion is when parts of a module are grouped because they operate on the same data (e.g. a module which operates on the same record of information). Sequential cohesion Sequential cohesion is when parts of a module are grouped because the output from one part is the input to another part like an assembly line (e.g. a function which reads data from a file and processes the data). Functional cohesion (best)Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module (e.g. tokenizing a string of XML).
  4. This code is of low cohesion – too many things are involved within the same method.
  5. מושגים ע"ש רוברט סי מרטין (הידוע בשם "הדוד בוב")
  6. הרציונל : צריך להיות מקום אחד בקוד שצריך לשנות על מנת לשנות התנהגות. המקום הנכון הוא כזה שמונע תופעת לוואי. אם קרה שבשל שינוי אחד – עברתם על מספר מקומות בקוד – אתם כנראה לאט אוכפים נכון SRP SRP is the idea that objects should do one thing and one thing only. It is tempting to think this means that a class should represent an entire piece of business logic or data, but that is not quite correct. The idea is not to group all of the functionality that is related together, but all of the functionality that achieves the same goal together. For example, if you have a class representing printer, putting all of the printer operations (getting toner levels, printing a page, getting an error message) in the printer class may make sense, but it is not really the right approach. Instead, you would put all of the functions related to printing in the same class, and all of the functions for reporting status in a class, and so on. You break the work down into small, digestible chunks. The payoff here is that you can make changes to a select piece of functionality without possibly affecting a ton of other items. - Uncle Bob defines a responsibility to be ‘a reason for change’. The more responsibilities a class has, the more change can be expected. The more expected change, the more likely is the introduction of bugs. Changes to one responsibility can have an impact on other responsibilities.
  7. רדיו מכיל מספר תפקידים The first post in the SOLID by Example series deals with the Single Responsibility Principle (SRP). This is the notion that an object should have only a single responsibility. Uncle Bob defines a responsibility to be ‘a reason for change’. The more responsibilities a class has, the more change can be expected. The more expected change, the more likely is the introduction of bugs. Changes to one responsibility can have an impact on other responsibilities. In this example we create a Radio class with some common operations. We can turn the volume up or down and change the station. Here is one way we could implement this class.(left) One could argue that the Radio class has two responsibilities, being volume and station management. These operations will be called from completely different areas of the client using it. Changes can occur whenever we want to modify some of the volume- or station management logic. By separating these responsibilities into distinct classes, we can avoid breakage in other parts of our class when our code meets a new requirement (next)
  8. הפרדת התפקידים. האפקט: הקטנת תופעות לוואי בעת שינוי קוד פחות מקומות שמשנים בקוד על מנת לשנות התנהגות Increase reusability
  9. כשמגיעה דרישה חדשה – למעשה לא מיד צריך לשנות את מה שקיים. למעשה אולי כדאי שדרישות חדשות ימומושו בקוד חדש (extension)\ לא ניתן לתכנן מערכת שהיא פתוחה לענות על כל הדרישות. ---------------- “Open chest surgery is not needed when putting on a coat”. This very simple idea is that classes can allow themselves to be extended but not modified. The source code for the original class should only be modified if a bug is found. The reason behind this is that changing the code will mean that everything depending upon it will need to be retested as well.
  10. Shape בנוי בצורה שאינה מאפשרת הרחבה. כל שינוי בSHAPE יוביל לשינוי ביורשים ובמשתמשים. במבנה כזה עדיף לערוך או להוסיף קלאס חדש. כמו כן – drawshape הוא מעין switch/case ארוך שצריך לתחזק. Left { 03   public void DrawShape(Shape s) 04   { 05      if (s._type == 1) 06      { 07         DrawRectangle((Rectangle)s); 08      } 09      else if (s._type == 2) 10     { 11         DrawCircle((Circle)s); 12      } 13} 14  15   public void DrawRectangle(Rectangle s) 16   { 17      Console.WriteLine("Rectangle"); 18   } 19  20   public void DrawCircle(Circle s) 21   { 22      Console.WriteLine("Circle"); 23   } 24}
  11. הפונקציונל מוגדר בINTERFACE אין צורך בswitch case קל להרחיב את המודל – ע"י הוספת class שיורש מshape האפקט: נמנעים משינוי בהתנהגות המקורית של המערכת מקטינים את כמות הקוד שנוגעים בו ע"מ לשנות. ----------------\
  12. ברברה ליסקוב Let q(x) be property provable about object x of type T. Then q(y) should be provable for objects y of type S where S is a subtype f T. רציונל: הורשה אינה מקיימת יחס is-a . LSP מקיים יחס "מתנהג כמו" behaves-like-a היררכיה צריכה להיות מוגדרת כך שרמות נמוכות מרחיבות שימוש של רמות שמעליהן.
  13. square: width and hight are the same Rectangle:width and height vary independently מה שקורה כאן = ששימוש (או החלפה) של SQUARE בRETANGLE תגרות לתופעות בלתי צפויות. The Liskov Substitution Principle is broken here, because the behavior of the Width and Height properties changed in the descendant class. Substitution of the Square with a Rectangle gives some unexpected results. (
  14. That test will fail, because setting a square's width to 100 will also change its height. Thus, Liskov's substitution principle is violated by deriving Square from Rectangle. The "is-a" rule makes sense in the "real world" (a square is definitely a kind of rectangle), but not always in the world of software design.
  15. square: width and hight are the same Rectangle:width and height vary independently מה שקורה כאן = ששימוש (או החלפה) של SQUARE בRETANGLE תגרות לתופעות בלתי צפויות. The Liskov Substitution Principle is broken here, because the behavior of the Width and Height properties changed in the descendant class. Substitution of the Square with a Rectangle gives some unexpected results. (
  16. באפקט : Code is “well formed” נמנעים מתופעות לוואי בעת מימוש הרחבות. The Liskov Substitution Principle held here, because the behavior of the Width and Height properties were not changed in the descendant class. Substitution of the Square or Rectangle with the Shape class gives the expected result.
  17. ISP reduces coupling.
  18. SEGREGATION – הפרדה\הבדלה High coupling between person and calendar. לCALENDAR נכנס מידע שאולי לא רלוונטי כמו משקל וגובה. In the following example we have a simple Person class with some obvious person-like methods and properties. We also have a BirthdayCalendar class that has an Add() method to add a person’s birthday to the calendar. The Add() method takes a Person object as a parameter. This makes sure that Person and BirtdayCalendar are tightly coupled. If Person changes, this can have an impact. If we want to add birtdays from entities other than from a Person we’re in trouble. There’s also no need for BirtdayCalendar to know all of Persons interface. This is why some might say that this class has a fat interface. It has a few useless properties and methods for different clients using the interface. To prevent this we let BirthdayCalendar specify an interface that Person must implement. In this case IBirthday with a Name, Age and DayOfBirth property.
  19. לCALENDAR נכנס רק המידע הרלוונטי. האפקט: Avoid unwanted side effects Increase reusability. This makes BirthdayCalendar independent of the Person class which makes it easier to maintain and extend. Imagine we also wanted to add the birthdays of pets to the BirthdayCalendar. The Pet class only had to implement the IBirtday interface to achieve that.
  20. העיקרון מדבר על שינוי דרישות קיימות. אם הפרטים משתנים, לא צריך לשנות את כל המערכת.
  21. הפרטים : List Hardcoded DataTime.Now.Date.Month
  22. הפרטים : List Hardcoded DataTime.Now.Date.Month
  23. במקום list – משתמשים באבסטרקציה dateTime מןעבר כפרמטר. האפקט: Reduce effort when adapting existing code when modifying existing code. Avoid unwanted side effects Increase reusability.
  24. There should only be one reason for a class to change (SRP) Entities should be open for extension but close for modification (OCP) References to base classes must be able to use objects of derived classes without knowing it (LSP) Clients should not be forced to depend upon interfaces that they use (ISP) Depend upon abstractions. Do not depend upon concretions(DIP)
  25. There should only be one reason for a class to change (SRP) Entities should be open for extension but close for modification (OCP) References to base classes must be able to use objects of derived classes without knowing it (LSP) Clients should not be forced to depend upon interfaces that they use (ISP) Depend upon abstractions. Do not depend upon concretions(DIP)
  26. There should only be one reason for a class to change (SRP) Entities should be open for extension but close for modification (OCP) References to base classes must be able to use objects of derived classes without knowing it (LSP) Clients should not be forced to depend upon interfaces that they use (ISP) Depend upon abstractions. Do not depend upon concretions(DIP)
  27. There should only be one reason for a class to change (SRP) Entities should be open for extension but close for modification (OCP) References to base classes must be able to use objects of derived classes without knowing it (LSP) Clients should not be forced to depend upon interfaces that they use (ISP) Depend upon abstractions. Do not depend upon concretions(DIP)
  28. There should only be one reason for a class to change (SRP) Entities should be open for extension but close for modification (OCP) References to base classes must be able to use objects of derived classes without knowing it (LSP) Clients should not be forced to depend upon interfaces that they use (ISP) Depend upon abstractions. Do not depend upon concretions(DIP)