Lecture: Modular Design

Similar documents
Intro to: Design Principles

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 Software Design - I

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

S.O.L.I.D: Software Engineering Principles

Introduction to Object-Oriented Programming

Test Code Patterns. How to design your test code

Testing and Inheritance. Test Code Patterns. Inheritance-related bugs. Inheritance. Testing of Inheritance. Inheritance-related bugs

11/4/15. Review. Objec&ves. Refactoring for Readability. Review. Liskov Subs&tu&on Principle (LSP) LISKOV SUBSTITUTION PRINCIPLE

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

CPSC 410? Advanced Software Engineering Mid-term Examination (Term I ) SOLUTION Instructor: Gail Murphy

Principles of Object-Oriented Design

Object-oriented design principles

Programming in the large

CS 520 Theory and Practice of Software Engineering Fall 2017

PRINCIPLES OF SOFTWARE DESIGN

Liskov Substitution Principle

Principles of Software Design. Software Engineering Alessio Gambi Saarland University

CS 520 Theory and Practice of Software Engineering Fall 2018

Objec&ves. Review. Liskov Subs&tu&on Principle Refactoring for Extensibility. What are reasons that we refactor our code?

CS 320 Introduction to Software Engineering Spring March 06, 2017

CSC207H: Software Design SOLID. CSC207 Winter 2018

Principles of OO Design

Maintainable Software. Software Engineering Andreas Zeller, Saarland University

Design Principles: Part 2

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

Design Principles: Part 2

The Challenge. Principles of Software Design

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

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

Object-Oriented Concepts and Design Principles

CSC207 Week 3. Larry Zhang

GRASP Design Patterns A.A. 2018/2019

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Object-Oriented Design

Object-Oriented Design

Open Closed Principle (OCP)

CS 320 Introduction to Software Engineering Spring March

Software Engineering

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

Component-Level Design

Object- Oriented Design with UML and Java Part I: Fundamentals

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

OO Class 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

L4: Inheritance. Inheritance. Chapter 8 and 10 of Budd.

Single Responsibility Principle

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

CPSC 310: Sample Final Exam Study Questions 2014S1 (These are in addition to the Study Questions listed at the end of some lectures)

Java Object Oriented Design. CSC207 Fall 2014

COURSE 2 DESIGN PATTERNS

Chapter 8: Class and Method Design

Today's Agenda. References. Open Closed Principle. CS 247: Software Engineering Principles. Object-Oriented Design Principles

Subtypes and Subclasses

Chapter 6: Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

Software Development

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CSE 401/M501 Compilers

Announcements. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Intuition: Type Signature is a Specification.

Classes and Objects. Object Orientated Analysis and Design. Benjamin Kenwright

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Elementary Concepts of Object Class

Programming Languages Seminar. Lecture in the subject of. Yair Moshe

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

Advanced Object Oriented Design Laboratory.

ITI Introduction to Computing II

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

Architecture CSE 403. Fallingwater by Frank Lloyd Wright

Originality is Overrated: OO Design Principles

ITI Introduction to Computing II

Bruno Bossola SOLID Design Principles

Summary of the course lectures

Chapter 10 Classes Continued. Fundamentals of Java

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

OBJECT ORİENTATİON ENCAPSULATİON

The Liskov Substitution Principle

Topics. Software Process. Agile. Requirements. Basic Design. Modular Design. Design Patterns. Testing. Quality. Refactoring.

CSE 70 Final Exam Fall 2009

What are the characteristics of Object Oriented programming language?

Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 6

Refactoring Practice: How it is and How it Should be Supported

OO Design Principles

Inheritance and Interfaces

Inheritance and object compatibility

EINDHOVEN UNIVERSITY OF TECHNOLOGY

Introduction to Object Oriented Programming. (Hebrew University, CS / Spring 2012 )

INTERNAL ASSESSMENT TEST III Answer Schema

Software Engineering Design & Construction

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

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

The S.O.L.I.D. Principles. of Object Oriented Programming

Object-Oriented Design II

Self-review Questions

MSO Lecture Design by Contract"

CAS 703 Software Design

Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page:

CS342: Software Design. November 21, 2017

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

Transcription:

Software Engineering Lecture: Modular Design Thomas Fritz Many thanks to Philippe Beaudoin, Gail Murphy, David Shepherd, Neil Ernst and Meghan Allen

Reading! For next lecture: (all required) Composite Design Pattern http://sourcemaking.com/design_patterns/composite Mediator Design Pattern http://sourcemaking.com/design_patterns/mediator Façade Design Pattern http://sourcemaking.com/design_patterns/facade 2

Modular Design Overview Introduction to Modularity Principles and Heuristics for good Modularity High Cohesion Loose Coupling Information Hiding Open/Closed Principle Liskov Substitution Principle Law of Demeter 3

Learning Goals By the end of this unit you will be able to: Critique a UML diagram and provide concrete suggestions of how to improve the design Explain the goal of a good modular design and why it is important Apply the following design-principles appropriately: high cohesion, loose coupling, principle of least knowledge, Liskov substitution principle, information hiding, open/closed principle 4

Recap: Bad Design Activity Web site slow or error-prone / crashes? 5

Software Design Modularity The goal of all software design techniques is to break a complicated problem into simple pieces. 6

Modular Design 7

8

Why Modularity? 9

Why Modularity? Minimize Complexity Reusability Extensibility Portability Maintainability 10

What is a good modular Design? There is no right answer with design Applying heuristics/principles can provide insights and lead to a good design 11

Principles & Heuristics for modular Design High Cohesion Loose Coupling Information Hiding Open/Closed Principle Liskov Substitution Principle Law of Demeter. 12

Discussion question Which of these two designs is better? A.public class AddressBook { private LinkedList<Address> theaddresses; public void add (Address a) {theaddresses.add(a);} //... etc.... } B. public class AddressBook extends LinkedList<Address> { // no need to write an add method, we inherit it } 13

14 Design Principles

High Cohesion Cohesion refers to how closely the functions in a module are related Modules should contain functions that logically belong together Group functions that work on the same data Classes should have a single responsibility (no schizophrenic classes) 15

High or low cohesion? public class EmailMessage { public void sendmessage() { } public void setsubject(string subj) { } public void setsender(sender sender) { } public void login(string user, String passw) { }. } 16

Loose Coupling Coupling assesses how tightly a module is related to other modules Goal is loose coupling: modules should depend on as few modules as possible Changes in modules should not impact other modules; easier to work with them separately 17

Tightly or loosely coupled? from Alverson (UW) 18

Tightly or loosely coupled? from Alverson (UW) 19

Information Hiding A good class is a lot like an iceberg: seveneights is under water, and you can see only the one-eight that s above the surface. from CodeComplete by Steve McConnell 20

Information Hiding Only expose necessary functions Abstraction hides complexity by emphasizing on essential characteristics and suppressing detail Caller should not assume anything about how the interface is implemented Effects of internal changes are localized 21

Information Hiding: Example 1 The chief scientist of the elementary particle research lab asks the new intern about his latest results: So what is the average momentum of these neutral particles? a) 42 b) Hmmm. Take this pile of sheet with my observations, here is the textbook that explains how to calculate momentum, also you will need to search online for the latest reference tables. Oh, and don t forget to correct for multiplicity! Which answer is the most likely to get the intern fired? 22

Information Hiding: Example 2 Class DentistScheduler has A public method automaticallyschedule() Private methods: whotoschedulenext() whotogivebadhour() ishourbad() To use DentistScheduler, just call automaticallyschedule() Don t have to know how it s done internally Could use a different scheduling technique: no problem! 23

Open/Closed Principle Classes should be open for extensions It is often desirable to modify the behavior of a class while reusing most of it Classes should be closed for change Modifying the source code of a class risks breaking every other class that relies on it Achieved through inheritance and dynamic binding 24

Open/Closed and Information Hiding Modifying the source code of a class risks breaking every other class that relies on it However, information hiding says that we should not assume anything about implementation So is there a need to keep classes closed for change? Yes because the implied behavior should never change! Inherit to reuse an interface while changing the behavior 25

Open/Closed Example class Drawing { public void drawallshapes(list<ishape> shapes) { for (IShape shape : shapes) { if (shape instanceof Square()) { drawsquare((square) shape); } else if (shape instanceof Circle) { drawcircle((circle) shape)); } } } } private void drawsquare(square square) { // draw the square } private void drawcircle(circle square) { // draw the circle } 26

Open/Closed Example class Drawing { public void drawallshapes(list<ishape> shapes) { for (IShape shape : shapes) { shape.draw(); } } } interface IShape { } public void draw(); class Square implements IShape { } public void draw() { // draw the square } 27

Open/Closed Caveat nice in theory, but in practice deriving a class to modify its behavior is not always best thing to do however, it becomes increasingly important to adhere to the open/closed principle as classes mature and are more and more relied upon some classes are not meant to be reusable, so the Open/Closed principle doesn t apply 28

Liskov Substitution Principle An object of a superclass should always be substitutable by an object of a subclass Subclass has same or weaker preconditions Subclass has same or stronger postconditions Derived methods should not assume more or deliver less 29

Liskov Substitution Principle Example Rectangle Square Reasonable to derive a square from a rectangle? see http://www.objectmentor.com/resources/articles/lsp.pdf 30

LSP Example Rectangle & Square class Rectangle { private double fwidth, fheight; } public void setwidth(double w) { fwidth = w; } public void setheight(double h) { fheight = h; } public double getwidth() { return fwidth; } public double getheight() { return fheight; } 31

LSP Example Rectangle & Square class Square extends Rectangle { public void setwidth(double w) { super.setwidth(w); super.setheight(w); } public void setheight(double h) { super.setheight(h); super.setwidth(h); } } 32

LSP Example Rectangle & Square // somewhere else public void calculate(rectangle r) { r.setwidth(5); r.setheight(6); assert(r.getwidth() * r.getheight() == 30); } // somewhere else Rectangle r = new Square( ); calculate(r); 33

LSP Example Rectangle & Square Postcondition for Rectangle setwidth( ) method assert((fwidth == w) && (fheight == old.fheight)); Square setwidth( ) has weaker postcondition does not conform to (fheight == old.fheight) Square has stronger preconditions Square assumes fwidth == fheight In other words Derived methods assume more and deliver less. 34

LSP Continued LSP shows that a design can be structurally consistent (A Square ISA Rectangle) But behaviourally inconsistent So, we must verify whether the pre and postconditions in properties will hold when a subclass is used. It is only when derived types are completely substitutable for their base types that functions which use those base types can be reused with impunity, and the derived types can be changed with impunity. 35

Law of Demeter (a.k.a. Principle of Least Knowledge) Assume as little as possible about other modules Restrict method calls to your immediate friends Only talk to your friends 36

Law of Demeter for classes Method M of object O should only call methods of: O itself M s parameters Any object created in M O s direct component objects Single dot rule a.b.method( ) breaks LoD a.method( ) does not 37

Class Activity Which principle is violated? a) 52 different import statements at the top of a Java file b) public final class Bird { } c) Point x = body.getcenterofmasspos(); Vec s = body.getcenterofmassspeed(); Vec a = body.getcenterofmassacceleration(); a = a + force * body.getmass(); s = s + a * dt; x = x + s * dt; body.setcenterofmasspos(x); body.setcenterofmassspeed(s); body.setcenterofmassacceleration(a); 38

Which principle is violated? d) public class Road extends Highway { } e) rect.setheight( 52 ); // Following line is not needed because setheight updates maximum height // rect.setmaxheight(52); f) public class System { public void changecarspeed(); public void changecarcolor(); public void changehighwaymaxspeed(); public void updatepolicecarposition(); }; g) public class Kid extends Person { // Inherited from parent class. Does nothing because kids // do not know how to Reason public void Reason() {} } 39

Class Activity Revisiting Your Design Examine your class diagrams and check for the design principles in your design Did you violate any Did you use any, which ones and why Be able to articulate which principles you used and why! 40

Modular Design Summary Goal of design is to manage complexity by decomposing problem into simple pieces Many principles/heuristics for modular design Strong cohesion, loose coupling Call only your friends Information Hiding Hide details, do not assume implementation Open/Closed Principle Open for extension, closed for modification Liskov Substitution Principle Subclass should be able to replace superclass 41