Object-Oriented Design Principles

Similar documents
Ingegneria del Software Corso di Laurea in Informatica per il Management. Object Oriented Principles

OO Design Quality Metrics

COSC 3351 Software Design. Recap for the first quiz. Edgar Gabriel. Spring For the 1 st Quiz

Agile Software Development

September 18, Modular development in Magento 2. Igor Miniailo Magento

Object Oriented Design

Object Oriented Software Design - I

Code Qualities and Coding Practices

STAN. Structure Analysis for Java. Version 2. White Paper. Fall 2009

Stop being Rails developer

ForeverSOA: Towards the Maintenance of Service-Oriented Architecture (SOA) Software

Chapter 8 Approaches to System Development

Java (12 Weeks) Introduction to Java Programming Language

The Dependency Inversion Principle

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Teaching Object-Oriented Software Design within the Context of Software Frameworks

Design Principles and Design Patterns

Introduction to Object-Oriented Programming

Fundamentals of Java Programming

Object-Oriented Design Guidelines

Approach of Unit testing with the help of JUnit

User experience storyboards: Building better UIs with RUP, UML, and use cases

Glossary of Object Oriented Terms

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

Why & How: Business Data Modelling. It should be a requirement of the job that business analysts document process AND data requirements

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

II. TYPES OF LEVEL A.

How To Understand The Software Development Lifecycle

Design with Reuse. Building software from reusable components. Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 14 Slide 1

Karunya University Dept. of Information Technology

Chapter 4, Requirements Elicitation

Aspect-Oriented Programming

MA-WA1920: Enterprise iphone and ipad Programming

Contents. Introduction and System Engineering 1. Introduction 2. Software Process and Methodology 16. System Engineering 53

Software Service Engineering Architect s Dream or Developer s Nightmare?

Chapter 13: Program Development and Programming Languages

Object Oriented Analysis and Design and Software Development Process Phases

In this Lecture you will Learn: Systems Development Methodologies. Why Methodology? Why Methodology?

Progress Report Aspect Oriented Programming meets Design Patterns. Academic Programme MSc in Advanced Computer Science. Guillermo Antonio Toro Bayona

Applying Object-Oriented Principles to the Analysis and Design of Learning Objects

Quotes from Object-Oriented Software Construction

Limitations of Data Encapsulation and Abstract Data Types

CSC408H Lecture Notes

An Introduction to Extreme Programming

Basic Trends of Modern Software Development

Specialized Programme on Web Application Development using Open Source Tools

SOACertifiedProfessional.Braindumps.S90-03A.v by.JANET.100q. Exam Code: S90-03A. Exam Name: SOA Design & Architecture

Course MS10975A Introduction to Programming. Length: 5 Days

Program Understanding in Software Engineering

Ingegneria del Software Corso di Laurea in Informatica per il Management GRASP. Davide Rossi Dipartimento di Informatica Università di Bologna

Object-oriented design methodologies

Managing Variability in Software Architectures 1 Felix Bachmann*

Java: Learning to Program with Robots. Chapter 11: Building Quality Software

Chapter 1: Key Concepts of Programming and Software Engineering

UML for the C programming language.

Chapter 13: Program Development and Programming Languages

Assuming the Role of Systems Analyst & Analysis Alternatives

Quality Analysis with Metrics

Software Configuration Management Best Practices

Unit Test Case Design Metrics in Test Driven Development

Software Engineering Introduction & Background. Complaints. General Problems. Department of Computer Science Kent State University

Logistics. Software Testing. Logistics. Logistics. Plan for this week. Before we begin. Project. Final exam. Questions?

Product Review: James F. Koopmann Pine Horse, Inc. Quest Software s Foglight Performance Analysis for Oracle

Cascaded Counters. Page 1 BYU

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

The Best Software Testing Arie Van Deursen TU Delft, 2011

Java Application Developer Certificate Program Competencies

Software Engineering. So(ware Evolu1on

Network Security. Mobin Javed. October 5, 2011

Conflict Resolution / Behavior Management Notes - New

Stock-picking strategies

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Creative Shorts: The business value of Release Management

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Component Based Software Engineering: A Broad Based Model is Needed

Module 3: Functional Requirements

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Chapter 24 - Quality Management. Lecture 1. Chapter 24 Quality management

(Refer Slide Time: 2:03)

Interview with David Bouthiette [at AMHI 3 times] September 4, Interviewer: Karen Evans

A Meeting Room Scheduling Problem

Programming and Software Development CTAG Alignments

USERV Auto Insurance Rule Model in Corticon

Design as Product Strategy Bringing design thinking to product management to create products people love

Exercise 8: SRS - Student Registration System

Easy Casino Profits. Congratulations!!

* Dry Cleaning and Laundry Services Picked Up and Delivered to Your Home or Business

The Easy Way To Flipping Domain Names

Software Design Principles and Guidelines

The Doctor-Patient Relationship

Real Time Programming: Concepts

International Journal of Advanced Research in Computer Science and Software Engineering

A LITTLE PROMISE FROM YOU

The EMSX Platform. A Modular, Scalable, Efficient, Adaptable Platform to Manage Multi-technology Networks. A White Paper.

Whatever the specifics of a plan may be, the following are key principles to make the plan most effective:

CS 121 Midterm Exam Fall 12 CLOSED BOOK THE RULES - PLEASE READ CAREFULLY

Step 1: Come Together

Software Engineering 1

Load Testing Basics: These are the basic ideas in setting up a load test By: Bob Wescott

Transcription:

Object-Oriented Design Principles The Pillars of the Paradigm Abstraction Encapsulation Hierarchy Association, Aggregation Inheritance Polymorphism 2

What s OO? Is it using Objects? Is it using C++, Java, C#, Smalltalk? No, its got to be using UML?! :) What makes a program OO? How do you measure good design? 3 Measuring Quality of an Abstraction Designing Classes & Objects An incremental, iterative process Difficult to design right the first time 4

Metrics for class design Coupling inheritance Vs. coupling Strong coupling complicates a system design for weakest possible coupling Cohesion degree of connectivity among the elements of a single module/class coincidental cohesion: all elements related undesirable Functional cohesion: work together to provide wellbounded behavior 5 Law of Demeter Methods of a class should not depend in any way on the structure of any class, except the immediate structure of their own class. Further, each method should send messages to objects belonging to a very limited set of classes only. First part talks about encapsulation and cohesion Second part talks about low coupling 6

Tell Don t Ask Procedural code gets information and then makes decisions. OO code tells objects to do things, Alec Sharp in Smalltalk by Example. Objects should take limited responsibility and rely on others to provide appropriate service Command-Query Separation: categorize methods as command or query 7 David Bock s Example on LoD/TDA David Bocks The Paper Boy, The Wallet, and The Law Of Demeter Failing LoD PaperBoy s method does: customer.waller.totalmoney; Honoring LoD PaperBoy s method does: customer.getpayment(...); => drives away shiny new Jaguar! => Customer controls amount, where it s kept (wallet, hidden in cookie jar,...) 8

Train Wreck Coding You may find code that continues to call on objects returned by methods in sequence customer.getaddress().getcity().getcounty()... This indicates that you are interested in working with objects that are farther away than those that are your close friends Hard to understand Hard to debug Lacks Cohesion Good candidate for refactoring 9 Perils of a bad design Bad design Rigidity Hard to change, results in cascade of changes Fragility Breaks easily and often Immobility Hard to reuse (due to coupling) Viscosity Easy to do wrong things, hard to do right things Needless Complexity Complicated class design, overly generalized Needless Repetition Copy and Paste away Opacity Hard to understand 10

Principles Guiding Principles that help develop better systems Use principles only where they apply You must see the symptoms to apply them If you apply arbitrarily, the code ends up with Needless Complexity 11 YAGNI You Aren t Going To Need It You are looking out for extensibility You are not sure if a certain functionality is needed Designing what you do not know fully leads to unnecessary complexity and heavy weight design If you really need it, design it at that time 12

DRY Don t Repeat Yourself Every Piece of Knowledge must have a single, unambiguous, authoritative representation within a system One of the most difficult, but most seen How many times have you see this happen Execution Engine (chokes on certain names of objects) Font end Application where UI did business validation. Start out due to flaw in Application Engine. Once flaw was rectified, took us weeks to fix the UI due to duplication of validation logic. 13 DRY Some times hard to realize this It is much easier to copy, paste and modify code to get it working the way you want it, isn t it Duplicating code results in Poor maintainability Expensive to fix bugs/errors Hard to keep up with change 14

SRP Single-Responsibility Principle What metric comes to mind? A class should have only one reason to change Some C++ books promoted bad design Overloading input/output operators! What if you do not want to display on a terminal any more? GUI based, or web based? 15 UI SRP Alarm +alert() +display(panel) Control System Faces more frequent change Has greater dependency (to UI related stuff) Related topics: MVC Analysis model stereotypes : Control Entity Boundary UI Alarm +alert() AlarmUI +display(panel) Control System 16

SRP at Module Level Can be extended to module level as well GUI Framework V 1.0 Component Development Utilities Throw it in there GUI Framework V 1.1 User Forced to accept Irrelevant change GUI Framework V 1.2 17 SRP affects Reuse Lower cohesion results in poor reuse My brother just bought a new DVD and a big screen TV! He offers to give me his VCR! I have a great TV and all I need is a VCR Here is what I found when I went to pickup! Disclaimer: This slide not intended to say anything about the brand of product shown here as an example! Tight coupling Poor Cohesion Bad for reuse 18

Nature of code Software Systems change during their life time Both better designs and poor designs have to face the changes; good designs are stable 19 OCP Bertrand Meyer: Software Entities (Classes, Modules, Functions, etc.) should be open for extension, but closed for modification 20

OCP Characteristics of a poor design: Single change results in cascade of changes Program is fragile, rigid and unpredictable Characteristics of good design: Modules never change Extend Module s behavior by adding new code, not changing existing code 21 OCP Software Modules must be open for extension module s behavior can be extended closed for modification source code for the module must not be changed 22

OCP Car Piston Engine How to make the Car run efficiently with Turbo Engine? Only by changing Car in the above design 23 OCP Car Abstract Engine Piston Engine Abstraction & Polymorphism are the Key A class must not depend on a Concrete class; it must depend on an abstract class 24

Strategic Closure: OCP No program can be 100% closed There will always be changes against which the module is not closed Closure is not complete - it is strategic Designer must decide what kinds of changes to close the design for. This is where the experience and problem domain knowledge of the designer comes in 25 OCP Heuristics and Conventions that arise from OCP Make all member variables private encapsulation: All classes/code that depend on my class are closed from change to the variable names or their implementation within my class. Member functions of my class are never closed from these changes Further, if this were public, no class will be closed against improper changes made by any other class No global variables 26

OCP Heuristics and Conventions that arise from OCP... RTTI is ugly and dangerous If a module tries to dynamically cast a base class pointer to several derived classes, any time you extend the inheritance hierarchy, you need to change the module Not all these situations violate OCP all the time 27 Liskov Substitution Principle Inheritance is used to realize Abstraction! and Polymorphism which are key to OCP How do we measure the quality of inheritance? LSP:! Functions that use pointers or references to base classes must be! able to use objects of derived classes without knowing it 28

Inheritance A public/is-a!b publicly inherits from ( is-a ) A means!every object of type B is also object of type A!What s true of object of A is also of object of B!A represents a more general concept than B!B represents more specialized concept than A!anywhere an object of A can be used, an object of B can be used B 29 Behavior Advertised Behavior of an object Advertised Requirements (Pre-Condition) Advertised Promise (Post Condition) Stack and estack example 30

Design by Contract Design by Contract Advertised Behavior of the Derived class is Substitutable for that of the Base class Substitutability: Derived class Services Require no more and promise no less than the specifications of the corresponding services in the base class 31 LSP Any Derived class object must be substitutable where ever a Base class object is used, without the need for the user to know the difference 32

LSP in Java? LSP is being used in Java at least in two places Overriding methods can not throw new unrelated exceptions Overriding method s access can t be more restrictive than the overridden method for instance you can t override a public method as protected or private in derived class 33 Nature of Bad Design Bad Design is one that is Rigid - hard to change since changes affect too many parts Fragile - unexpected parts break upon change Immobile - hard to separate from current application for reuse in another 34

Ramifications Controller Depends for Alarm Controller needs an alarm Clock has it, so why not use it? Clock Concrete Controller depends on concrete Clock Changes to Clock affect Controller Hard to make Controller use different alarm (fails OCP) Clock has multiple responsibilities (fails SRP) 35 Alternate Design Controller IAlarm Clock Timer Dependency has been inverted Both Controller and Clock depend on Abstraction (IAlarm) Changes to Clock does not affect Controller Better reuse results as well 36

Inheritance Vs. Delegation Inheritance is one of the most abused concepts in OO programming Often, delegation may be a better choice than inheritance When should you use inheritance vs. delegation? 37 Inheritance Vs. Delegation... If an object of B may be used in place of an object of A, use inheritance If an object of B may use an object of A, then use delegation 38

DIP Dependency Inversion Principle High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details.! Details should depend upon abstractions. 39 The Founding Principles The three principles are closely related Violating either LSP or DIP invariably results in violating OCP It is important to keep in mind these principles to get the most out of OO development 40

C1 Fat Interfaces A Class C2 Clients should not know this as a single class They should know about abstract base classes with cohesive interfaces Classes tend to grow into fat interfaces Examples of this can been seen in several APIs Less cohesive (fails SRP) C1 I1 A Class I2 Interface of the class may be split C2 Growth of an interface C1 IMicrowave +cook(time) +stop() C2 A few days later, Client C1 wants it to notify (workaholic client?!) C1 Clients are forced to use interfaces they do not care about. May result in greater coupling, dependency to more libraries MicrowaveImpl IMicrowave +cook(time) +stop() +chime() +notify( ) MicrowaveImpl A few days later, Client C2 wants it to chime C2 All implementations must carry the weights Interface does not mean all methods in a class 41 42

ISP Interface Segregation Principle Clients should not be forced to depend on methods that they do not use C1 INotify +notify( ) IMicrowave +cook(time) +stop() C2 IChimer +chime() MicrowaveImpl1 MicrowaveImpl2 43 Reuse/Release Equivalency Principle The granularity of reuse is the same as the granularity of release. Only components that are released through a tracking system can be effectively reused. 44

Reuse/Release Equivalency Principle Release A class generally collaborates with other classes For a class to be reused, you need also the classes that this class depends on All related classes must be released together 45 Tracking Reuse/Release Equivalency Principle A class being reused must not change in an uncontrolled manner Code copying is a poor form of reuse Software must be released in small chunks - components Each chunk must have a version number Reusers may decide on an appropriate time to use a newer version of a component release 46

Common Closure Principle Classes within a released component should share common closure. If one need to be changed, they all are likely to need to be changed. What affects one, affect all. 47 Common Closure Principle A change must not cause modification to all released components Change must affect smallest possible number of released components Classes within a component must be cohesive Given a particular kind of change, either all classes in a component must be modified or no class needs to be modified Reduces frequency of re-release of component 48

Common Reuse Principle Classes within a released component should be reused together. That is, it must be impossible to separate the component in order to reuse less than the total. 49 Common Reuse Principle... Components must be focused Component must not contain classes that an user is not likely to reuse user may be forced to accept a new release due to changes to unused classes Component must be narrow 50

Acyclic Dependence Principle The dependency structure for released component must be a Directed Acyclic Graph. There can be no cycles. 51 Acyclic Dependence Principle If there are cycles, it becomes hard to maintain Change ripples through Can t release components in small increments 52

Stable Dependency Principle Dependencies between released components must run in the direction of stability. The dependee must be more stable than the depender. 53 A component can never be more stable than the one it depends upon Instability I = Ce / (Ca + Ce), where Ca - # of classes outside that depend upon this class Ce - # of classes outside that this class depends upon 0 " I " 1 Stable Dependency Principle 0 - ultimately stable; 1 - ultimately unstable 54

Stable Dependency Principle... Components should be arranged such that components with a high I metrics should depend upon component with low I metrics 55 Stable Abstraction Principle The more stable a component is, the more it must consist of abstract classes. A completely stable category should consist of nothing but abstract classes. 56

Implementation of methods change more often than the interface Interfaces have more intrinsic stability than executable code Abstraction of a Component! A = (# of abstract classes) / (# of classes) 0 " A " 1 Stable Abstraction Principle 0 - no abstract classes; 1 - all abstract classes 57 Maximally stable & abstract A (0, 1) Abstractness Stability Vs. Abstractness 0 Highly stable & Concrete (Rigid) The Main Sequence Instability (1,1) (1, 0) I Maximally instable & concrete Highly instable & abstract (Rigid) 58

Distance from the main sequence D = (A + I - 1) / #2 0 " D " 0.707; Desirable value of D is closed to 0 Normalized form D' = (A + I -1) Calculate D value for each component Component whose D value is not near Zero can be reexamined and restructured 59 Applying the Principles Developing with OO is more than Using a certain language Creating objects Drawing UML It tends to elude even experienced developers Following the principles while developing code helps attain agility Use of each principle should be justified at each occurrence, however 60

OO Principles and Agile Development These principles are more relevant during iterative development and refactoring than upfront design As the requirements become clearer and we understand the specifics the forces behind the use of these principle become clear as well 61