SlideShare una empresa de Scribd logo
1 de 39
Software Craftsmanship by Sandro Mancuso Twitter: @sandromancuso http://www.londonswcraft.com How much do we know about OOP/OOD?
Inheritance >> Before we start What can we expect from this session?
Class Invariant >> Inheritance
public class  Rectangle {      private int  height;      private int  width;        public  Rectangle( int  height,  int  width) {          this. height = height;          this. width = width;      }      public int  getHeight() {          return   this .height;      }      public void  setHeight( int  height) {          this .height = height;      }      public int  getWidth() {          return   this .width;      }      public void  setWidth( int  width) {          this. width = width;      } }   public class  Square  extends  Rectangle {        public  Square( int  size) {          super(size, size);      }        public int  setHeight( int  height) {          return   super. setHeight(height);      }      public int  setWidth( int  width) {          return   super. setWidth(width);      } } What will happen when we call the setters? Class Invariant Invariant fix >>
public class  Square  extends  Rectangle {        public  Square( int  size) {          super (size, size);      }        public void  setHeight( int  height) {          super .setHeight(height);          super .setWidth(height);      }      public void  setWidth( int  width) {          super .setWidth(width);          super .height(width);      } } ,[object Object],[object Object],[object Object],[object Object],Should Square extend Rectangle? Class invariant – a fix but not a solution LSP >>
“ Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.  “ LSP violation public void  drawShape(Shape s) {      if  (s  instanceof  Square) {          drawSquare((Square) s);      }  else if  (s instanceof Circle){          drawCircle((Circle) s);      } } Liskov Substitution Principle - LSP Behavioral subtyping LSP violations >>
A more subtle violation of LSP Rectangle r = new Square(); r.setHeight(5); r.setWidth(6); Violations - Without the fix, Square would be in an invalid state when used as a Rectangle; - With the fix, the Square setter methods weaken (violate) Rectangle’s post conditions, which state that dimensions can be modified independently Liskov Substitution Principle - LSP Fixing the design >>
What we’ve learnt? ,[object Object],[object Object],[object Object],Liskov Substitution Principle - LSP public class  Square {      int  size;            public  Square( int  size) {          this .size = size;      }        public int  getSize() {          return   this .size;      }      public void  setSize( int  size) {          this. size = size;      } } DbC >>
- Term was coined by Bertrand Meyer in 1986 Based on the mutual  obligations  and  benefits  principle.  -  Pre-condition : obligation for the client, benefit for the supplier -  Post-condition : obligation for the supplier, benefit for the client -  Invariant : Assumed on entry, guaranteed on exit Design by Contract DbC implications >>
[object Object],[object Object],[object Object],[object Object],Design by Contract implications public class  ClassA {      public void  someMethod() {…} } public class  ClassB  extends  ClassA {      public void  someMethod() { // Stronger pre-condition // Weaker post-condition & invariant } } public class  Client {      public void  doSomething(ClassA a) { a.someMethod(); } } ,[object Object],[object Object],[object Object],Defensive Programming >>
-  DbC : It’s the client’s responsibility (obligation) to respect supplier’s pre-condition. Code should “fail-hard” -  Defensive Programming : Supplier takes the responsibility to validate pre-condition In both cases, client needs to take an action. DbC vs Defensive Programming - Whatever you do, don’t hide bugs. If a pre-condition is not met, let the system blow or let the client handle it.  - Don’t code  default behaviour  unless this is part of the requirement. Side effect >>
A code is said to have side effect when it modifies some state or has an  observable  interaction with calling functions or outside world. (linked to DbC post-condition) Side effect ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Very common in imperative programming and rare in functional programming. Avoiding problems >>
Side effect ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],POLA/POLS >>
Principle of least astonishment/surprise ,[object Object],[object Object],[object Object],The result of performing some operation should be obvious, consistent, and predictable, based upon the name of the operation, parameters and return value.  All programmers are API designers – Joshua Bloch ,[object Object],[object Object],[object Object],Violation >>
Violation of POLA / POLS public class  EventProcessor {      public void  processEvent(Event event) throws EventProcessorException { try  { doSomethingWith(event); event.setState( PROCESSED );  // violation }  catch  (Exception e) { event.setState( FAILED );  // violation throw new   EventProcessorException(e); } } } Possible undesired side effect. SRP >>
Single Responsibility Principle - SRP ,[object Object],[object Object],[object Object],SRP violations >> What about the “else” keyword? What does it imply when we use it?
Single Responsibility Principle - SRP Where do things go wrong? - SRP violations are most seen in systems developed without TDD and refactoring. - Classes closer to the system interface have a more generic and broader responsibility - Failure do identify responsibility / delegation ratio Cohesion >>
Cohesion The cornerstone of Object-Oriented Programming Class level >> Cambridge Dictionary Cohesion (noun)  : when the members of a group or society are united. Cohesive (adjective)  : united and working together effectively. Wikipedia In computer programming, cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are.  LCOM4: Lack of Cohesion Methods (metrics used by Sonar)
Cohesion at class level The cornerstone of Object-Oriented Programming Method level >> ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cohesion at method level The cornerstone of Object-Oriented Programming God object >> ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
God Object Coupling >>
Coupling Types >> Coupling  or  dependency  is the degree to which each program module relies on each one of the other modules  - Low coupling often correlates with high cohesion, and vice versa. - Sign of good design and well maintainable code.
Coupling general types other types >> ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Coupling – other types Ripple effect >> ,[object Object],[object Object]
Coupling – The ripple effect ISP >>
Interface Segregation Principle - ISP ISP >>
Interface Segregation Principle - ISP Role interface >>
Role Interface DIP >> ,[object Object],[object Object],[object Object],[object Object]
Dependency Inversion Principle - DIP DIP >> ,[object Object],[object Object],Violation What if we want to write it to disk? How can we reuse Copier?
Dependency Inversion Principle - DIP IoC & DI >> High and low-level modules now depend on an abstraction
DIP, IoC and DI Encapsulation Jump >> ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Encapsulation Information Hiding >> ,[object Object],[object Object],Information Hiding  !=  Data encapsulation
Information Hiding & Protected Variation OCP >> Information Hiding : Hide information about the design from other modules, at the points of difficult or likely to change.  David Parnas Information hiding is Protected Variation, not data encapsulation To minimise change impacts, we aim for low coupling. To design for low coupling, we design for protected variations. Craig Larman Protected Variation : Identify points of predicted variation and create a stable interface around them.  Alistair Cockburn
Open Closed Principle (OCP) LoD >> Software entities (classes, modules, functions, etc) should be open for extension, but closed for modification ,[object Object],[object Object],[object Object],[object Object],Misconception : Closed to modification does not mean that we cannot change a class. It means that we should avoid modifications that affect clients. Is it still a good idea today?
Law of Demeter - LoD Feature Envy >> ,[object Object],[object Object],[object Object],[object Object],Violation context.getCar().getEngine().getPiston().getSparkPlug(),doSomething(); parent.getChildren().delete(child);
Feature Envy Other topics >> public void  doSomething() { BigDecimal baseMonthlySalary = employee.getBaseMontlySalary(); int  overtimeInHours  = employee.getOverTimeInHours(); BigDecimal overtimeHourRate  = employee.getOvertimeHourRate(); BigDecimal salaryToBePaid  = baseMonthlySalary +  (overtimeInHours * overtimeHourRate); // Do more stuff with the salary } public void  doSomething() { BigDecimal salaryToBePaid = employee.getMonthlySalaryToBePaid(); // Do more stuff with the salary } A better implementation
A few other related topics Wrap up >> ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Wrap up There is always a good reason to break a rule or law, but it really needs to be a good one. The critical design tool for software development is a mind well educated in design principles. It is not the UML or any other technology   Craig Larman Most software engineers don’t set out to create “bad designs”. Yet most software eventually degrades to the point where someone will declare the design to be unsound. Why does this happen? Was the design poor to begin with, or did the design actually degrade like a piece of rotten meat? At the heart of this issue is our lack of a good working definition of “bad” design .  Uncle Bob Martin Questions >>
Questions London Software Craftsmanship Community – LSCC –  http://www.londonswcraft.com Twitter:  @sandromancuso

Más contenido relacionado

La actualidad más candente

DDD Strategic Patterns and Microservices by Example
DDD Strategic Patterns and Microservices by ExampleDDD Strategic Patterns and Microservices by Example
DDD Strategic Patterns and Microservices by ExampleErik Ashepa
 
Hardcore CSS Made Easy
Hardcore CSS Made EasyHardcore CSS Made Easy
Hardcore CSS Made EasyJosé Rosário
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Krishna-Kumar
 
How to design a file system
How to design a file systemHow to design a file system
How to design a file systemNikhil Anurag VN
 
The NixOS project and deploying systems declaratively
The NixOS project and deploying systems declarativelyThe NixOS project and deploying systems declaratively
The NixOS project and deploying systems declarativelySander van der Burg
 
Git이란 (Git 소개 및 기초 이론)
Git이란 (Git 소개 및 기초 이론)Git이란 (Git 소개 및 기초 이론)
Git이란 (Git 소개 및 기초 이론)승용 윤
 
Linux - Hedi Magroun - AUF - 2008
Linux -  Hedi Magroun - AUF - 2008Linux -  Hedi Magroun - AUF - 2008
Linux - Hedi Magroun - AUF - 2008Hedi Magroun
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#Pascal Laurin
 
Introduction to Version Control
Introduction to Version ControlIntroduction to Version Control
Introduction to Version ControlJeremy Coates
 
android activity
android activityandroid activity
android activityDeepa Rani
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to FlutterEason Pai
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & ArchitectureMassimo Oliviero
 
Docker and the Linux Kernel
Docker and the Linux KernelDocker and the Linux Kernel
Docker and the Linux KernelDocker, Inc.
 

La actualidad más candente (20)

DDD Strategic Patterns and Microservices by Example
DDD Strategic Patterns and Microservices by ExampleDDD Strategic Patterns and Microservices by Example
DDD Strategic Patterns and Microservices by Example
 
Hardcore CSS Made Easy
Hardcore CSS Made EasyHardcore CSS Made Easy
Hardcore CSS Made Easy
 
Gitlab flow
Gitlab flowGitlab flow
Gitlab flow
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Pengenalan ReactJS
Pengenalan ReactJS Pengenalan ReactJS
Pengenalan ReactJS
 
Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases Stateful set in kubernetes implementation & usecases
Stateful set in kubernetes implementation & usecases
 
How to design a file system
How to design a file systemHow to design a file system
How to design a file system
 
The NixOS project and deploying systems declaratively
The NixOS project and deploying systems declarativelyThe NixOS project and deploying systems declaratively
The NixOS project and deploying systems declaratively
 
Git이란 (Git 소개 및 기초 이론)
Git이란 (Git 소개 및 기초 이론)Git이란 (Git 소개 및 기초 이론)
Git이란 (Git 소개 및 기초 이론)
 
Linux - Hedi Magroun - AUF - 2008
Linux -  Hedi Magroun - AUF - 2008Linux -  Hedi Magroun - AUF - 2008
Linux - Hedi Magroun - AUF - 2008
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#
 
Introduction to Version Control
Introduction to Version ControlIntroduction to Version Control
Introduction to Version Control
 
android activity
android activityandroid activity
android activity
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Android Intent.pptx
Android Intent.pptxAndroid Intent.pptx
Android Intent.pptx
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to Flutter
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & Architecture
 
Docker and the Linux Kernel
Docker and the Linux KernelDocker and the Linux Kernel
Docker and the Linux Kernel
 

Destacado

Crafted Design - GeeCON 2014
Crafted Design - GeeCON 2014Crafted Design - GeeCON 2014
Crafted Design - GeeCON 2014Sandro Mancuso
 
Crafted Design - LJC World Tour Mash Up 2014
Crafted Design - LJC World Tour Mash Up 2014Crafted Design - LJC World Tour Mash Up 2014
Crafted Design - LJC World Tour Mash Up 2014Sandro Mancuso
 
Crafted Design - ITAKE 2014
Crafted Design - ITAKE 2014Crafted Design - ITAKE 2014
Crafted Design - ITAKE 2014Sandro Mancuso
 
Software Craftsmanship - JAX London 2011
Software Craftsmanship - JAX London 2011Software Craftsmanship - JAX London 2011
Software Craftsmanship - JAX London 2011Sandro Mancuso
 
Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software CraftsmanshipSandro Mancuso
 
Crafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoCrafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoJAXLondon2014
 
Legacy Code Hands-on Session
Legacy Code Hands-on Session Legacy Code Hands-on Session
Legacy Code Hands-on Session Sandro Mancuso
 
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014TSundberg
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 

Destacado (9)

Crafted Design - GeeCON 2014
Crafted Design - GeeCON 2014Crafted Design - GeeCON 2014
Crafted Design - GeeCON 2014
 
Crafted Design - LJC World Tour Mash Up 2014
Crafted Design - LJC World Tour Mash Up 2014Crafted Design - LJC World Tour Mash Up 2014
Crafted Design - LJC World Tour Mash Up 2014
 
Crafted Design - ITAKE 2014
Crafted Design - ITAKE 2014Crafted Design - ITAKE 2014
Crafted Design - ITAKE 2014
 
Software Craftsmanship - JAX London 2011
Software Craftsmanship - JAX London 2011Software Craftsmanship - JAX London 2011
Software Craftsmanship - JAX London 2011
 
Software Craftsmanship
Software CraftsmanshipSoftware Craftsmanship
Software Craftsmanship
 
Crafted Design - Sandro Mancuso
Crafted Design - Sandro MancusoCrafted Design - Sandro Mancuso
Crafted Design - Sandro Mancuso
 
Legacy Code Hands-on Session
Legacy Code Hands-on Session Legacy Code Hands-on Session
Legacy Code Hands-on Session
 
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014
BDD with Cucumber-JVM as presented at I T.A.K.E. Unconference in Bucharest 2014
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 

Similar a How much do we know about Object-Oriented Programming?

Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
M03 1 Structuraldiagrams
M03 1 StructuraldiagramsM03 1 Structuraldiagrams
M03 1 StructuraldiagramsDang Tuan
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
design-principles.ppt
design-principles.pptdesign-principles.ppt
design-principles.pptWalidLahsiki
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAttila Bertók
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll Uchiha Shahin
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questionsRamu Palanki
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questionsRamu Palanki
 

Similar a How much do we know about Object-Oriented Programming? (20)

Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
M03 1 Structuraldiagrams
M03 1 StructuraldiagramsM03 1 Structuraldiagrams
M03 1 Structuraldiagrams
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
design-principles.ppt
design-principles.pptdesign-principles.ppt
design-principles.ppt
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 
SAD10 - Refactoring
SAD10 - RefactoringSAD10 - Refactoring
SAD10 - Refactoring
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Clean code
Clean codeClean code
Clean code
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
 

Último

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...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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 CVKhem
 
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 educationjfdjdjcjdnsjd
 
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)wesley chun
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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 FresherRemote DBA Services
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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 RobisonAnna Loughnan Colquhoun
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

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...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
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
 
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)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+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...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

How much do we know about Object-Oriented Programming?

  • 1. Software Craftsmanship by Sandro Mancuso Twitter: @sandromancuso http://www.londonswcraft.com How much do we know about OOP/OOD?
  • 2. Inheritance >> Before we start What can we expect from this session?
  • 3. Class Invariant >> Inheritance
  • 4. public class Rectangle {      private int height;      private int width;        public Rectangle( int height, int width) {          this. height = height;          this. width = width;      }      public int getHeight() {          return this .height;      }      public void setHeight( int height) {          this .height = height;      }      public int getWidth() {          return this .width;      }      public void setWidth( int width) {          this. width = width;      } }   public class Square extends Rectangle {        public Square( int size) {          super(size, size);      }       public int setHeight( int height) {          return super. setHeight(height);      }      public int setWidth( int width) {          return super. setWidth(width);      } } What will happen when we call the setters? Class Invariant Invariant fix >>
  • 5.
  • 6. “ Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. “ LSP violation public void drawShape(Shape s) {      if (s instanceof Square) {          drawSquare((Square) s);      } else if (s instanceof Circle){          drawCircle((Circle) s);      } } Liskov Substitution Principle - LSP Behavioral subtyping LSP violations >>
  • 7. A more subtle violation of LSP Rectangle r = new Square(); r.setHeight(5); r.setWidth(6); Violations - Without the fix, Square would be in an invalid state when used as a Rectangle; - With the fix, the Square setter methods weaken (violate) Rectangle’s post conditions, which state that dimensions can be modified independently Liskov Substitution Principle - LSP Fixing the design >>
  • 8.
  • 9. - Term was coined by Bertrand Meyer in 1986 Based on the mutual obligations and benefits principle. - Pre-condition : obligation for the client, benefit for the supplier - Post-condition : obligation for the supplier, benefit for the client - Invariant : Assumed on entry, guaranteed on exit Design by Contract DbC implications >>
  • 10.
  • 11. - DbC : It’s the client’s responsibility (obligation) to respect supplier’s pre-condition. Code should “fail-hard” - Defensive Programming : Supplier takes the responsibility to validate pre-condition In both cases, client needs to take an action. DbC vs Defensive Programming - Whatever you do, don’t hide bugs. If a pre-condition is not met, let the system blow or let the client handle it. - Don’t code default behaviour unless this is part of the requirement. Side effect >>
  • 12.
  • 13.
  • 14.
  • 15. Violation of POLA / POLS public class EventProcessor {      public void processEvent(Event event) throws EventProcessorException { try { doSomethingWith(event); event.setState( PROCESSED ); // violation } catch (Exception e) { event.setState( FAILED ); // violation throw new EventProcessorException(e); } } } Possible undesired side effect. SRP >>
  • 16.
  • 17. Single Responsibility Principle - SRP Where do things go wrong? - SRP violations are most seen in systems developed without TDD and refactoring. - Classes closer to the system interface have a more generic and broader responsibility - Failure do identify responsibility / delegation ratio Cohesion >>
  • 18. Cohesion The cornerstone of Object-Oriented Programming Class level >> Cambridge Dictionary Cohesion (noun) : when the members of a group or society are united. Cohesive (adjective) : united and working together effectively. Wikipedia In computer programming, cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. LCOM4: Lack of Cohesion Methods (metrics used by Sonar)
  • 19.
  • 20.
  • 22. Coupling Types >> Coupling or dependency is the degree to which each program module relies on each one of the other modules - Low coupling often correlates with high cohesion, and vice versa. - Sign of good design and well maintainable code.
  • 23.
  • 24.
  • 25. Coupling – The ripple effect ISP >>
  • 27. Interface Segregation Principle - ISP Role interface >>
  • 28.
  • 29.
  • 30. Dependency Inversion Principle - DIP IoC & DI >> High and low-level modules now depend on an abstraction
  • 31.
  • 32.
  • 33. Information Hiding & Protected Variation OCP >> Information Hiding : Hide information about the design from other modules, at the points of difficult or likely to change. David Parnas Information hiding is Protected Variation, not data encapsulation To minimise change impacts, we aim for low coupling. To design for low coupling, we design for protected variations. Craig Larman Protected Variation : Identify points of predicted variation and create a stable interface around them. Alistair Cockburn
  • 34.
  • 35.
  • 36. Feature Envy Other topics >> public void doSomething() { BigDecimal baseMonthlySalary = employee.getBaseMontlySalary(); int overtimeInHours = employee.getOverTimeInHours(); BigDecimal overtimeHourRate = employee.getOvertimeHourRate(); BigDecimal salaryToBePaid = baseMonthlySalary + (overtimeInHours * overtimeHourRate); // Do more stuff with the salary } public void doSomething() { BigDecimal salaryToBePaid = employee.getMonthlySalaryToBePaid(); // Do more stuff with the salary } A better implementation
  • 37.
  • 38. Wrap up There is always a good reason to break a rule or law, but it really needs to be a good one. The critical design tool for software development is a mind well educated in design principles. It is not the UML or any other technology Craig Larman Most software engineers don’t set out to create “bad designs”. Yet most software eventually degrades to the point where someone will declare the design to be unsound. Why does this happen? Was the design poor to begin with, or did the design actually degrade like a piece of rotten meat? At the heart of this issue is our lack of a good working definition of “bad” design . Uncle Bob Martin Questions >>
  • 39. Questions London Software Craftsmanship Community – LSCC – http://www.londonswcraft.com Twitter: @sandromancuso

Notas del editor

  1. Class invariants are established during construction and constantly maintained between calls to public methods.
  2. LSP's importance is noticed mainly when it is violated. Client code needs to do instanceof or type casting.
  3. LSP's importance is noticed mainly when it is violated. Client code needs to do instanceof or type casting. violation of the Liskov Substitution Principle since the methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently.
  4. LSP's importance is noticed mainly when it is violated. Client code needs to do instanceof or type casting. violation of the Liskov Substitution Principle since the methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently.
  5. Client pays fee (obligation) and get a product back (benefit). Supplier gives product to client (obligation) and get money in exchange (benefit). Three questions we need to ask when defining a method: - What does it expect? - What does it guarantee? - What does it maintain?
  6. Testing: Unit testing tests a class in isolation, checking if it meets its contract assuming its clients and suppliers meet theirs Integration/Functional tests checks whether the various classes are working properly together
  7. Pre-condition checks using assertions are quite often associated with Design by Contract. Some languages like Eifel have native support. In Java, frameworks like JContract are meant to do check pre-condition, post-condition and invariants using annotations.
  8. Side effect examples: a function might modify a global or static variable , modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions. Bugs due to "action at a distance" may arise because a program component is doing something at the wrong time, or affecting something it should not. It is very difficult, however, to track down which component is responsible. Side effects from innocent actions can put the program in an unknown state, so local data is not necessarily local. The solution in this particular scenario is to define which components should be interacting with which others. A proper design that accurately defines the interface between parts of a program, and that avoids shared states, can largely eliminate problems caused by action at a distance.
  9. Red box: TradeService.processTrade(tradeXml) or Order.placeOrder(shoppingBasket) - The closer the code is to the system's interface, the broader and more generic its responsibility will be. The further away the code is from the system's interface, the narrower and more specific its responsibility will be.  - The closer the class is to the system's interface, the more delegation the class will do. The further way the class is from the system's interface, less delegation the class will do.
  10. www.cs.fsu.edu/~stoeckli/COURSES/CENSWE2/Support/GoodMethods.ppt
  11. www.cs.fsu.edu/~stoeckli/COURSES/CENSWE2/Support/GoodMethods.ppt
  12. God object is an object that knows too much or does too much . The God object is an example of an anti-pattern .
  13. - Low coupling often correlates with high cohesion, and vice versa. - Sign of good design and well maintainable code.
  14. Content coupling (high) Content coupling is when one module modifies or relies on the internal workings of another module (e.g., accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module. Common coupling Common coupling is when two modules share the same global data (e.g., a global variable). Changing the shared resource implies changing all the modules using it. External coupling External coupling occurs when two modules share an externally imposed data format, communication protocol, or device interface.This is basically related to the communication to external tools and devices. Control coupling Control coupling is one module controlling the flow of another, by passing it information on what to do (e.g., passing a what-to-do flag). Stamp coupling (Data-structured coupling) Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part (e.g., passing a whole record to a function that only needs one field of it). This may lead to changing the way a module reads a record because a field that the module doesn't need has been modified. Data coupling Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared (e.g., passing an integer to a function that computes a square root). Message coupling (low) This is the loosest type of coupling. It can be achieved by state decentralization (as in objects) and component communication is done via parameters or message passing (see Message passing ).
  15. Content coupling (high) Content coupling is when one module modifies or relies on the internal workings of another module (e.g., accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module. Common coupling Common coupling is when two modules share the same global data (e.g., a global variable). Changing the shared resource implies changing all the modules using it. External coupling External coupling occurs when two modules share an externally imposed data format, communication protocol, or device interface.This is basically related to the communication to external tools and devices. Control coupling Control coupling is one module controlling the flow of another, by passing it information on what to do (e.g., passing a what-to-do flag). Stamp coupling (Data-structured coupling) Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part (e.g., passing a whole record to a function that only needs one field of it). This may lead to changing the way a module reads a record because a field that the module doesn't need has been modified. Data coupling Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared (e.g., passing an integer to a function that computes a square root). Message coupling (low) This is the loosest type of coupling. It can be achieved by state decentralization (as in objects) and component communication is done via parameters or message passing (see Message passing ).
  16. http://www.objectmentor.com/resources/articles/dip.pdf
  17. http://www.objectmentor.com/resources/articles/dip.pdf
  18. Spring, PicoContainer, Avalon, Guice, Seam
  19. Object oriented programming feature.
  20. Alistair Cockburn defined Protected Variation before knowing about OCP Craig Larman explains differences here: http://im.ufba.br/pub/MATA63/Documentos/ProtectedVariation%5B1%5D.pdf
  21. With modern tools, TDD, automated refactoring tools, etc, I would not be too bothered. http://im.ufba.br/pub/MATA63/Documentos/ProtectedVariation%5B1%5D.pdf
  22. What about encapsulation? How can we write tests for this?
  23. What about encapsulation? How can we write tests for this?
  24. With modern tools, TDD, automated refactoring tools, etc, I would not be too bothered. http://im.ufba.br/pub/MATA63/Documentos/ProtectedVariation%5B1%5D.pdf