Software Design and SOLID Principles

Similar documents
Single Responsibility Principle

Software Engineering

Technical Metrics for OO Systems

SOLID Principles. Equuleus Technologies. Optional Subheading October 19, 2016

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

Open Closed Principle (OCP)

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas

17.11 Bean Rules persistent

Object-Oriented Design

GRASP Design Patterns A.A. 2018/2019

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle

Object-Oriented Concepts and Design Principles

Intro to: Design Principles

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Object-Oriented Design II

COURSE 2 DESIGN PATTERNS

Inheritance and object compatibility

Principles of Ruby Applica3on Design. Dean Wampler Senior Mentor and Consultant Object Mentor, Inc. Chicago, IL

Liskov Substitution Principle

CSE 70 Final Exam Fall 2009

Object-Oriented Design

Software Engineering CSC40232: SOFTWARE ENGINEERING. Guest Lecturer: Jin Guo SOLID Principles sarec.nd.edu/courses/se2017

Abstraction. Design fundamentals in OO Systems. Fundamental Software Development Principles

Principles of Object-Oriented Design

Patterns in Software Engineering

Dependency Injection (ESaaS 11.6)! 2013 Armando Fox & David Patterson, all rights reserved

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

Exam in TDDB84: Design Patterns,

Advanced WCF 4.0 .NET. Web Services. Contents for.net Professionals. Learn new and stay updated. Design Patterns, OOPS Principles, WCF, WPF, MVC &LINQ

Design Principles: Part 2

CMPS 115 Winter 04. Class #10 (2004/02/05) Changes/Review Programming Paradigms Principles of OOD <break> Design Patterns

CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L

Outline. Design Principles: Part 2. e.g. Rectangles and Squares. The Liskov Substitution Principle (LSP) ENGI 5895: Software Design.

Agile Software Development

CSC207H: Software Design SOLID. CSC207 Winter 2018

Ingegneria del Software Corso di Laurea in Informatica per il Management. Software quality and Object Oriented Principles

Lessons Learned. Johnny Bigert, Ph.D., Skype/Microsoft October 26, 2011

The following topics will be covered in this course (not necessarily in this order).

Single Responsibility Principle (SRP)

Design Patterns. CSC207 Fall 2017

Conception Orientée Objets. Programmation SOLID

Design Quality Assessment in Practice

Design Patterns Reid Holmes

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

OO Class Design Principles

OOD Smells and Principles

Object-Oriented Design

Design Principles: Part 2

Summary of the course lectures

Magento Technical Guidelines

Princípy tvorby softvéru Dizajnové princípy

CS 520 Theory and Practice of Software Engineering Fall 2017

Design Patterns. CSC207 Winter 2017

CS 520 Theory and Practice of Software Engineering Fall 2018

Credit where Credit is Due. Lecture 25: Refactoring. Goals for this lecture. Last Lecture

Understading Refactorings

CSC207 Week 3. Larry Zhang

Evolving Software. CMSC 433 Programming Language Technologies and Paradigms Spring Example. Some Motivations for This Refactoring

Chapter 5 Object-Oriented Programming

Administrivia. Programming Language Fall Example. Evolving Software. Project 3 coming out Midterm October 28. Refactoring October 14, 2004

Design Pattern - Factory Pattern

Object Oriented Metrics. Impact on Software Quality

Last Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Object Oriented Software Design - I

Principles of OO Design

Inheritance (Chapter 7)

CHAPTER 5: PRINCIPLES OF DETAILED DESIGN

CS 320 Introduction to Software Engineering Spring March 06, 2017

Build Testable Client and Service Applications

Object Oriented Programming. Java-Lecture 11 Polymorphism

Design Pattern Examples

LABORATORY 1 REVISION

Component-Level Design. Slides copyright 1996, 2001, 2005, 2009 by Roger S. Pressman. For non-profit educational use only

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Agile Principles, Patterns, and Practices in C#

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Kostis Kapelonis Athens Greece, March 2010

Metrics and OO. SE 3S03 - Tutorial 12. Alicia Marinache. Week of Apr 04, Department of Computer Science McMaster University

Design Patterns. CSC207 Fall 2017

OO Frameworks. Introduction. Using Frameworks

Designing with patterns - Refactoring. What is Refactoring?

Influence of Design Patterns Application on Quality of IT Solutions

Originality is Overrated: OO Design Principles

SOLID: Principles of OOD

EasyChair Preprint. Software Metrics Proposal for Conformity Checking of Class Diagram to SOLID Design Principles

09. Component-Level Design

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Design Patterns V Structural Design Patterns, 2

TDDB84: Lecture 09. SOLID, Language design, Summary. fredag 11 oktober 13

An Introduction to Object Orientation

Towards Cohesion-based Metrics as Early Quality Indicators of Faulty Classes and Components

Basic design patterns

1: Introduction to Object (1)

SOFTWARE PATTERNS. Joseph Bonello

Bruno Bossola SOLID Design Principles

C++ Modern and Lucid C++ for Professional Programmers

Object-Oriented Design I - SOLID

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Software Development

Transcription:

TCSS 360: SOFTWARE DEVELOPMENT AND QUALITY ASSURANCE OBJECTIVES Software Design and SOLID Principles Wes J. Lloyd Institute of Technology University of Washington - Tacoma SessionMgr read_from_db() store_in_db() Database SessionMgr get_session() store_session() From chapter 11: Engineering SaaS Software Design & Architecture SOLID Design Principles Design Patterns «interface» SessionStore Software Metrics Database L7.2 Software Architecture SOFTWARE DESIGN: REQUIREMENTS TO CODE Provides a high-level framework to build and evolve the system ARCHITECTURE VS. DESIGN PATTERNS Architecture: provides high-level framework for structuring application Client-server REST web services Client-server SOAP web services Client-server based on remote procedure calls Distributed system based on CORBA Defines the system in terms of computational components and their interactions Design Patterns Lower level than architecture Reusable collaborations that solve sub-problems within an application E.g. How can I decouple subsystem X from subsystem Y? L7.3 L7.4 SOFTWARE ARCHITECTURE: 100,000 FT VIEW Component based design Systems consist of components and connectors Components: define the basic computations comprising the system and their behaviors Abstract data types, classes, etc. Connectors: define the interconnections between components Procedure call, event announcement, asynchronous messages ABSTRACT DATA TYPES Abstract data types provide a model for a certain class of data structures with similar behavior ADTs include A collection of data elements A set of operations to perform on the data ADT specification Defines what the operations do, but now how ADT implementation Provides an implementation for the operations specific to a particular data structure Consider Java s List Interface Provides an abstract definition of List operations Java class provide concrete implementations L7.5 L7.6 Slides by Wes J. Lloyd L7.1

ABSTRACTION SOLID DESIGN GUIDELINES Define the operations Define the data Provide an implementation Why would we like to abstract the definition of our operations? Common interface Many implementations Backward compatibility: introduce new interfaces while retaining support for old L7.7 Single Responsibility A class should have one and only one reason to change O pen/closed Classes should be open for extension but closed for modification L iskov Substitution Substituting a subclass for a class should preserve correct program behavior Interface Segregation No client should dep on methods it does not use Injecting Depencies Collaborating classes who implementation may vary at runtime should dep on an intermediate injected depency L7.8 SINGLE RESPONSIBILITY PRINCIPLE SINGLE RESPONSIBILITY - 2 A class should have one and only one responsibility Example: class named Reviewers in CoffeeFinder which defines information about users who review coffee shops A sign-on operation could be added to Reviewers to enable a reviewer to log in This does not separate responsibility! Single Responsibility: Use a Sessions class Decouples the design of logging-in from the Reviewers Class What if the authentication strategy changes? Reviewers class would need to change Sign-on operation added to Reviewers Class How do other classes of users sign-on? Does each user class implement their own? Decouple key features/functions into reusable classes MVC: Controllers Each controller provides business logic for system components Components ReviewerController: User who contributes coffee shop reviews UserController: General system user AdminController: Admin user that performs DB maintenance L7.9 L7.10 SINGLE RESPONSIBILITY - 3 SRP: COHESION METRICS - 1 MVC: Each controller should specialize in dealing with one resource User session is a distinct resource from Reviewer Rule of thumb: if you cannot describe the responsibility of the class in 25 words or less, it may have more than one responsibility Provides a gauge for when to split into multiple classes Measuring abuse: Lack of Cohesion Metrics - (LCOM) Degree to which the elements of a class are related Methods are related if they access the same subset of instance or class variables or if one calls the other Detects unrelated clusters within a class Data clump code smell: when a class is evolving towards multiple responsibilities Group of variables/values passed and returned together Could values benefit from their own class? CKJM Java metrics (Free Tool): http://www.spinellis.gr/sw/ckjm/ L7.11 L7.12 Slides by Wes J. Lloyd L7.2

SRP: COHESION METRICS - 2 SRP: COHESION SUMMARY Revised Herson-Sellers LCOM=1 (sum(mv i ) / M*V) (produces value from 0 to 1) M = # instance methods V = # instance variables MV i = # instance methods that access the i th instance variable (excluding trivial getters/setters) LCOM-4: counts # of connected components in graph where related methods are connected by an edge High LCOM suggests possible single responsibility violation Cohesion measures the degree of depence among classes/modules in a system High cohesion: Classes/modules in the program perform similar tasks and are related to each other (via associations) GOOD! Low cohesion: Lots of miscellaneous and auxiliary classes/modules, no associations BAD! L7.13 L7.14 SRP: REFACTORING TO SOLVE OPEN/CLOSED PRINCIPLE (OCP) Reviewer class: Attribute: phone_number Attribute: zipcode Extract Class Refactoring: Want ability to check zipcode for accuracy Extract new class(es) from the Reviewer Want to normalize phone numbers into standardized format Could refactor as an Address Class, or separate zipcode and phone number Special methods deal only with specific instance variables of Reviewer class Zipcode and phone number could be separate classes Overtime the number of support methods ts to grow L7.15 Classes should be: open for extension, but closed for modification Exting a class shouldn t require modifying existing code Class Report def output Case statement code smell: formatter = case @format when :html Explicit dispatch based Html.new(self) on the report format when :pdf PdfFormatted.new(self) Adding a new output type #... Etc requires modifying Report.output method L7.16 OPEN/CLOSED PRINCIPLE - 2 Abstract factory design pattern Provides a solution in statically typed languages Provides common interface for instantiating an object whose subclass may not be known until runtime Non-elegant solution: factory must be changed public abstract class AbstractFactory { abstract Color getcolor(string color); abstract Shape getshape(string shape) ; public class ShapeFactory exts AbstractFactory { @Override public Shape getshape(string shapetype){ if(shapetype == null){ return null; if(shapetype.equalsignorecase("circle")){ return new Circle(); else if(shapetype.equalsignorecase("rectangle")){ return new Rectangle(); else if(shapetype.equalsignorecase("square")){ return new Square(); return null; @Override Color getcolor(string color) { return null; L7.17 L7.18 Slides by Wes J. Lloyd L7.3

OCP: TEMPLATE METHOD / STRATEGY PATTERN Template method: set of steps is the same, but implementation of steps different Inheritance: subclasses override abstract step methods Strategy: task is the same, but many ways to do it Composition: component classes implement whole task (delegation) Delegation OCP: REPORT - TEMPLATE PATTERN class Report attr_accessor :title, :t ext def output_rep ort output_title output_header output_body class HtmlRepor t < Report def output_tit le... def output_hea der... en d class PdfReport < Report def output_tit le... def output_hea der... en d Template method stays the same; helpers overridden in subclass HtmlReport output_title() output_header() output_body() Report output_title() output_header() output_body() PdfReport output_title() output_header() output_body() L7.19 L7.20 OCP: REPORT - STRATEGY PATTERN OCP - TOO MUCH INHERITANCE class Report attr_accessor :title, :text, :formatter def output_report formatter.output_report Delegation (vs. inheritance) Report @formatter Html RegularPdf PdfWithWatermark- PdfWithPasswordAnd- Watermark Pdf PdfWithPassword- @base protect_with_password() PdfWithPassword- Multiplication of subclasses favor: composition over inheritance Pdf PdfWithWatermark- @base add_watermark() Html Pdf Prefer composition over inheritance L7.21 L7.22 OPEN/CLOSED PRINCIPLE CONCLUSIONS LISKOV SUBSTITUTION PRINCIPLE (LSP) In some cases it won t be possible to be closed for all types of modifications Design pattern or approach should be chosen Agile methods can help determine potential changes early Can try to refactor, etc. to keep classes closed to modification Can you think of some implications for class modification vs. extension? What about depent code? If class behavior changes, potentially affects other code Extension is generally harmless Class subtypes can substitute for base types Current formulation attributed to (Turing Award winner) Barbara Liskov A method that works on an instance of type T, should also work on any subtype of T Type/subtype!= Class/subclass All of T s subtypes should preserve T s contract L7.23 L7.24 Slides by Wes J. Lloyd L7.4

LSP: REFUSED BEQUEST LSP: SOLUTION Code smell: In a refused bequest a subclass either: Destructively overrides a behavior inherited from its superclass Forces changes to the superclass to avoid the problem Subclasses that don t take advantage of parent (gifts) implementations should not be subclasses Indicates inappropriate use of inheritance! Symptom: change to subclass requires change to superclass (shotgun surgery code smell) Rectangle area, perimeter width, height Square make_twice_as_wide _as_high LSP Violation: Square inherits from rectangle Rectangle provides make_twice_as_wide_as_high() method Not shown in UML diagram Makes no sense in a square (OCP) Square @rect area(), perimeter() Rectangle width, height area(), perimeter() Composition should be used instead of inheritance The square will be composed of a rectangle (it uses it!) rather than inheriting from, and exting the rectangle class L7.25 L7.26 INTERFACE SEGREGATION PRINCIPLE (ISP) ISP: MINIMAL INTERFACE EXAMPLE Clients should not be forced to dep on methods they do not use Split large interfaces into smaller, more specific ones ISP reduces coupling High code coupling is correlates with higher software maintenance costs Code is harder to modify, refactor, ext L7.27 L7.28 ISP: CODE COUPLING ISP: COUPLING LEVELS Degree of interdepence between software modules Measure of how closely connected two routines/modules are These factors are commonly correlated: Low coupling High Cohesion High readability High maintainability Characteristics of: Good software designs Content: one module relies on internal workings or data of another. One class reads/deps on another internal variables Common: two modules share global data; all modules using the global data are impacted by a change External: two modules share an externally imposed data format, communication protocol, device interface Control: one module controls the flow of another by passing it information on what to do Stamp: modules share a common data structure, though may only sparsely use some of its fields Data: modules share data through parameters passing Message: modules communicate through message passing code not explicitly coupled, messages come through channels L7.29 L7.30 Slides by Wes J. Lloyd L7.5

ISP: COUPLING METRICS ISP: COUPLING SUMMARY To measure coupling must define precisely what to quantify Response for class (RFC): class methods + distinct method calls made Message passing coupling (MPC): number of messages passing among objects of a class Chidamber & Kemerer Coupling between objects (CBO): total classes reference by a class, plus the total number of classes referencing it. Fan out: number of other classes referenced by the class Fan In: number of other classes referencing the class Efferent coupling (Ce): Fan In stricter implementation Afferent coupling (Ca): Fan out stricter implementation Coupling measures depencies between subsystems High coupling: changes to one subsystem will have high impact on the other subsystem BAD!! Require change of model, massive compilation Low coupling: change in one subsystem does not affect any other subsystem - - GOOD!! L7.31 L7.32 TUTORIAL #2 - CONTINUED http://faculty.washington.edu/wlloyd/courses/tcss360/tutori als/tcss360_w2017_tutorial_2.pdf QUESTIONS L7.33 L23.34 Slides by Wes J. Lloyd L7.6