High-Quality Routines

Slides:



Advertisements
Similar presentations
Quality of a Class Abstraction: Coupling & Cohesion Michael L. Collard, Ph.D. Department of Computer Science Kent State University.
Advertisements

Chapter 3: Modules, Hierarchy Charts, and Documentation
Structured Design. 2 Design Quality – Simplicity “There are two ways of constructing a software design: One is to make it so simple that there are obviously.
Software Engineering Routine design. High quality routines Routine: individual method or procedure invocable for a single purpose.
Lecture 9 Improving Software Design CSC301-Winter 2011 – University of Toronto – Department of Computer Science Hesam C. Esfahani
Module: Definition ● A logical collection of related program entities ● Not necessarily a physical concept, e.g., file, function, class, package ● Often.
Jump to first page 1 System Design (Finalizing Design Specifications) Chapter 3d.
Computer Science 240 Principles of Software Design.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Design-Making Projects Work (Chapter7) n Large Projects u Design often distinct from analysis or coding u Project takes weeks, months or years to create.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Coupling and Cohesion Source:
SOFTWARE DESIGN (SWD) Instructor: Dr. Hany H. Ammar
Chapter 7: High Quality Routines By Raj Ramsaroop.
SE: CHAPTER 7 Writing The Program
Cohesion and Coupling CS 4311
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
Coupling Cohesion Chandan R. Rupakheti Steve Chenoweth (Chapter 18)
Software Engineering Principles. SE Principles Principles are statements describing desirable properties of the product and process.
CS242.  Reduce Complexity  Introduce an intermediate, understandable abstraction  Avoid code duplication  Support subclassing  Hide sequences  Hide.
CS540 Software Design Lecture 3 & 4 1 Lecture 3 & 4: Modularity, Coupling, Cohesion and Abstraction Anita S. Malik Adapted from Schach.
Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the.
High-Quality Routines Chapter 5-6. Review Class Quality Checklist 2.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Key Principles of Software Architecture and Design (II) adapted from Dave Penny’s.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Coupling and Cohesion Schach, S, R. Object-Oriented and Classical Software Engineering. McGraw-Hill, 2002.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Further Modularization, Cohesion, and Coupling. Simple Program Design, Fourth Edition Chapter 9 2 Objectives In this chapter you will be able to: Further.
Introduction To DBMS.
Modularity Most useful abstractions an OS wants to offer can’t be directly realized by hardware Modularity is one technique the OS uses to provide better.
Programming Logic and Design Seventh Edition
7. Modular and structured design
Coupling and Cohesion Rajni Bhalla.
Software Metrics 1.
Lecture 1 Introduction Richard Gesick.
Introduction to the C Language
Coupling and Cohesion 1.
Data Abstraction: The Walls
CPSC 315 – Programming Studio Spring 2012
Software Design Mr. Manoj Kumar Kar.
The Selection Structure
Run-time organization
Systems Analysis and Design
Not what first comes to mind
Cohesion and Coupling Chapter 5, Pfleeger 01/01/10.
High-Quality Routines
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Unit# 9: Computer Program Development
Objects First with Java
Topics Introduction to File Input and Output
Improving the Design “Can the design be better?”
Software Design CMSC 345, Version 1/11.
Chapter 09 – Part I Creating High-Quality Code
Programming Logic and Design Fourth Edition, Comprehensive
Chapter 7 Writing the Programs Shari L. Pfleeger Joann M. Atlee 4th Edition.
Software Design Lecture : 9.
Software Design Lecture : 8
Software Design Lecture : 10
CSE 303 Concepts and Tools for Software Development
Communication between modules, cohesion and coupling
Cohesion and Coupling.
Variables in C Topics Naming Variables Declaring Variables
Topics Introduction to File Input and Output
Programming Issues Code Complete (Roger S. Pressman)
Chapter 4: Writing and Designing a Complete Program
DESIGN CONCEPTS AND PRINCIPLES
Presentation transcript:

High-Quality Routines SCMP 391.00 Special Topic: Software Development Spring 2017 James Skon

High-Quality Routines What is it?

What are all these parameters? Counter example Changes! void HandleStuff( CORP_DATA & inputRec, int crntQtr, EMP_DATA empRec, double & estimRevenue, double ytdRevenue, int screenX, int screenY, COLOR_TYPE & newColor, COLOR_TYPE & prevColor, StatusType & status, int expenseType ) { int i; for ( i = 0; i < 100; i++ ) { inputRec.revenue[i] = 0; inputRec.expense[i] = corpExpense[ crntQtr ][ i ]; } UpdateCorpDatabase( empRec ); estimRevenue = ytdRevenue * 4.0 / (double) crntQtr; newColor = prevColor; status = SUCCESS; if ( expenseType == 1 ) { for ( i = 0; i < 12; i++ ) profit[i] = revenue[i] - expense.type1[i]; else if ( expenseType == 2 ) { profit[i] = revenue[i] - expense.type2[i]; else if ( expenseType == 3 ) profit[i] = revenue[i] - expense.type3[i]; To many Params Bad name Not changed Unused! Hard to follow Global No single purpose What if zero? Magic Numbers Bad Layout What are all these parameters?

Characteristics of Good Design Component independence High cohesion Low coupling Exception identification and handling Fault prevention and fault tolerance Design for change M1 M2 M3

Routines “Aside from the computer itself, the routine is the single greatest invention in computer science.” Imagine life without them: One big piece of code.. Repeat same code over and over rather then calling one copy. Much harder to debug (and need to debug duplicate code)

Valid Reasons to Create a Routine Reduce complexity You don’t need to think about the internal complexity to use it, only when you write it.

Valid Reasons to Create a Routine Introduce an intermediate, understandable abstraction leafName = GetLeafName( node ) if ( node <> NULL ) then while ( node.next <> NULL ) do node = node.next leafName = node.name end while else leafName = "" end if This Not this

Valid Reasons to Create a Routine Avoid duplicate code Hide pointer operations Improve portability – isolate dependancies Simplify complicated boolean tests Improve performance – optimize in one place only

Example - DeviceUnitsToPoints points = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) Function DeviceUnitsToPoints ( deviceUnits Integer ): Integer DeviceUnitsToPoints = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) End Function points = DeviceUnitsToPoints( deviceUnits )

Example - DeviceUnitsToPoints Another advantage is that over time the code may change, localizing changes: Function DeviceUnitsToPoints ( deviceUnits Integer ): Integer DeviceUnitsToPoints = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) End Function Function DeviceUnitsToPoints( deviceUnits: Integer ) Integer; if ( DeviceUnitsPerInch() <> 0 ) DeviceUnitsToPoints = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) else DeviceUnitsToPoints = 0 end if End Function

Cohesion refers to how closely the operations in a routine are related. the degree to which a method implements a single function The goal is to have each routine do one thing well and not do anything else.

Cohesion Definition The degree to which all elements of a component are directed towards a single task. The degree to which all elements directed towards a task are contained in a single component. The degree to which all responsibilities of a single class are related. Internal glue with which component is constructed All elements of component are directed toward and essential for performing the same task. 12

High Cohesion: payoff Higher reliability! A study of 450 routines found that 50 percent of the highly cohesive routines were fault free, whereas only 18 percent of routines with low cohesion were fault free (Card, Church, and Agresti 1986) Another study found that routines with the highest coupling-to-cohesion ratios had 7 times as many errors as those with the lowest coupling-to-cohesion ratios and were 20 times as costly to fix (Selby and Basili 1991).

Type of Cohesion High Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Low 14

Coincidental Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Parts of the component are unrelated (unrelated functions, processes, or data) Parts of the component are only related by their location in source code. Elements needed to achieve some functionality are scattered throughout the system. Accidental Worst form 15

Example Print next line Reverse string of characters in second argument Add 7 to 5th argument Convert 4th argument to float 16

Logical Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Elements of component are related logically and not functionally. Several logically related elements are in the same component and one of the elements is selected by the client component. 17

Example A component reads inputs from tape, disk, and network. All the code for these functions are in the same component. Operations are related, but the functions are significantly different. Improvement? 18

Temporal Cohesion Def: Elements are related by timing involved Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Elements are related by timing involved Elements are grouped by when they are processed. Example: An exception handler that Closes all open files Creates an error log Notifies user Lots of different activities occur, all at same time 19

Example A system initialization routine: this routine contains all of the code for initializing all of the parts of the system. Lots of different activities occur, all at init time. Improvement? 20

Procedural Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Elements of a component are related only to ensure a particular order of execution. Actions are still weakly connected and unlikely to be reusable. Example: ... Write output record Read new input record Pad input with spaces Return new record 21

Communicational Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Functions performed on the same data or to produce the same data. Examples: Update record in data base and send it to the printer Update a record on a database Print the record Fetch unrelated data at the same time. To minimize disk access 22

Sequential Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: The output of one part is the input to another. Data flows between parts (different from procedural cohesion) Occurs naturally in functional programming languages Good situation 23

Functional Cohesion Functional Sequential Communicational Procedural Temporal Logical Coincidental Def: Every essential element to a single computation is contained in the component. Every element in the component is essential to the computation. Ideal situation What is a functionally cohesive component? One that not only performs the task for which it was designed but it performs only that function and nothing else. 24

Related by order of functions Examples of Cohesion Function A Function A Function A’ Function A’’ Time t0 Time t0 + X Time t0 + 2X Function B Function C logic Function D Function E Coincidental Parts unrelated Logical Similar functions Temporal Related by time Function A Function B Function C Procedural Related by order of functions 25

Examples of Cohesion (Cont.) Function A Function B Function C Function A Function B Function C Communicational Access same data Sequential Output of one is input to another Function A part 1 Function A part 2 Function A part 3 Functional Sequential with complete, related functions 26

Exercise: Cohesion for Each Module? Compute average daily temperatures at various sites Initialize sums and open files Create new temperature record Store temperature record Close files and print average temperatures Read in site, time, and temperature Store record for specific site Edit site, time, or temperature field Functional Sequential Communicational Procedural Temporal Logical Coincidental 27

Outline Cohesion Coupling 28

Coupling The degree of dependence such as the amount of interactions among components No dependencies Loosely coupled some dependencies Highly coupled many dependencies

Coupling The degree of dependence such as the amount of interactions among components How can you tell if two components are coupled? (In pairs, 2 minutes)

Indications of Coupling ?

Type of Coupling High Coupling Content Avoid Common External Control Stamp Data Uncoupled Avoid Loose Try to achieve Low 32

Content Coupling Def: One component modifies another. Example: Common External Control Stamp Data Uncoupled Def: One component modifies another. Example: Component directly modifies another’s data Component modifies another’s code, e.g., jumps (goto) into the middle of a routine Question Language features allowing this? 33

Example Part of a program handles lookup for customer. When customer not found, component adds customer by directly modifying the contents of the data structure containing customer data. Improvement? 34

Content Common External Control Stamp Data Uncoupled Common Coupling Def: More than one component share data such as global data structures Usually a poor design choice because Lack of clear responsibility for the data Reduces readability Difficult to determine all the components that affect a data element (reduces maintainability) Difficult to reuse components Reduces ability to control data accesses 35

Example Process control component maintains current data about state of operation. Gets data from multiple sources. Supplies data to multiple sinks. Each source process writes directly to global data store. Each sink process reads directly from global data store. Improvement? 36

External Coupling Content Common External Control Stamp Data Uncoupled Def: Two components share something externally imposed, e.g., External file Device interface Protocol Data format Improvement? 37

Control Coupling Content Common External Control Stamp Data Uncoupled Def: Component passes control parameters to coupled components. May be either good or bad, depending on situation. Bad if parameters indicate completely different behavior Good if parameters allow factoring and reuse of functionality Good example: sort that takes a comparison function as an argument. The sort function is clearly defined: return a list in sorted order, where sorted is determined by a parameter. 38

Stamp Coupling Content Common External Control Stamp Data Uncoupled Def: Component passes a data structure to another component that does not have access to the entire structure. Requires second component to know how to manipulate the data structure (e.g., needs to know about implementation). The second has access to more information that it needs. May be necessary due to efficiency factors: this is a choice made by insightful designer, not lazy programmer. . 39

Example Customer Billing System The print routine of the customer billing accepts customer data structure as an argument, parses it, and prints the name, address, and billing information. Improvement? 40

Improvement --- OO Solution Use an interface to limit access from clients Customer get name get address get billing info get other info … ? void print (Customer c) { … }

Data Coupling Content Common External Control Stamp Data Uncoupled Def: Component passes data (not data structures) to another component. Every argument is simple argument or data structure in which all elements are used Good, if it can be achieved. Example: Customer billing system The print routine takes the customer name, address, and billing information as arguments. CS 4311 42

Uncoupled Completely uncoupled components are not systems. Content Common Control Stamp Data Uncoupled Content Common External Control Stamp Data Uncoupled Completely uncoupled components are not systems. Systems are made of interacting components.

Exercise: Define Coupling between Pairs of Modules Content Common External Control Stamp Data Uncoupled

Coupling between Pairs of Modules Q R S T U P

Consequences of Coupling Why does coupling matter? What are the costs and benefits of coupling? (pairs, 3 minutes)

Consequences of Coupling High coupling Components are difficult to understand in isolation Changes in component ripple to others Components are difficult to reuse Need to include all coupled components Difficult to understand Low coupling May incur performance cost Generally faster to build systems with low coupling

In Class Groups of 2 or 3: P1: What is the effect of cohesion on maintenance? P2: What is the effect of coupling on maintenance? 48

Good Routine Names Describe everything the routine does If the description is too long, the design is probably bad ComputeReportTotals() ComputeReportTotalsAndOpen-OutputFile() Opening a file as a “side effect” makes for a silly name Open-OutputFile()

Good Routine Names Bad Names! Avoid meaningless, vague, or wishy- washy verbs: HandleCalculation() PerformServices() OutputUser() ProcessInput(), DealWithOutput() Bad Names!

Good Routine Names Don't differentiate routine names solely by number. Make names of routines as long as necessary . average length for a variable name is 9 to 15 characters Good variable names help document the program.

Good Routine Names Good! To name a function, use a description of the return value: cos() customerId.Next() printer.IsReady() pen.CurrentColor() Good!

Good Routine Names To name a procedure, use a strong verb followed by an object. PrintDocument() CalcMonthlyRevenues() CheckOrderlnfo() RepaginateDocument()

Good Routine Names Use opposites precisely add/remove increment/decrement open/close begin/end insert/delete show/hide create/destroy lock/unlock source/target first/last min/max start/stop get/put next/previous up/down get/set old/new

Good Routine Names Establish conventions for common operations A naming convention is often the easiest and most reliable way of distinguish among different kinds of operations. All get ID: employee.id.Get() dependent.GetId() supervisor() candidate.id()

How Long Can a Routine Be? A study found that routine size was inversely correlated with errors: as the size of routines increased (up to 200 lines of code), the number of errors per line of code decreased. Another study found that routine size was not correlated with errors, even though structural complexity and amount of data were correlated with errors (Shen et al. 1985).

How Long Can a Routine Be? A 1986 study found that small routines (32 lines of code or fewer) were not correlated with lower cost or fault rate The evidence suggested that larger routines (65 lines of code or more) were cheaper to develop per line of code. An empirical study of 450 routines found that small routines (those with fewer than 143 source statements, including comments) had 23 percent more errors per line of code than larger routines but were 2.4 times less expensive to fix than larger routines (Selby and Basili 1991).

How Long Can a Routine Be? Another study found that code needed to be changed least when routines averaged 100 to 150 lines of code (Lind and Vairavan 1989). A study at IBM found that the most error- prone routines were those that were larger than 500 lines of code. Beyond 500 lines, the error rate tended to be proportional to the size of the routine (Jones 1986a).

How Long Can a Routine Be? Rule of Thumb – keep it under 200 lines if possible. None of the studies that reported decreased cost, decreased error rates, or both with larger routines distinguished among sizes larger than 200 lines. Routines bigger then 200 lines run into an upper limit of understandability.

How to Use Routine Parameters Interfaces between routines are some of the most error-prone areas of a program. One often-cited study by Basili and Perricone (1984) found that 39 percent of all errors were internal interface errors — errors in communication between routines.

How to Use Routine Parameters Put parameters in input-modify-output order Instead of ordering parameters randomly or alphabetically, list the parameters that are input- only first, input-and-output second, and output- only third. If several routines use similar parameters, put the similar parameters in a consistent order

At this point, inputVal no longer contains the value that was input. How to Use Routine Parameters Use all the parameters passed Put status or error variables last Don't use routine parameters as working variables At this point, inputVal no longer contains the value that was input. int Sample( int inputVal ) { inputVal = inputVal * CurrentMultiplier( inputVal ); inputVal = inputVal + CurrentAdder( inputVal ); ... return inputVal; }

Better – inputVal not changed! How to Use Routine Parameters Don't use routine parameters as working variables int Sample( int inputVal ) { int workingVal = inputVal; workingVal = workingVal * CurrentMultiplier( workingVal ); workingVal = workingVal + CurrentAdder( workingVal ); ... <-- 1 return workingVal; } Better – inputVal not changed!

How to Use Routine Parameters Document interface assumptions about parameters Whether parameters are input-only, modified, or output-only Units of numeric parameters (inches, feet, meters, and so on) Meanings of status codes and error values if enumerated types aren't used Ranges of expected values Specific values that should never appear

Macro Routines Routines created with preprocessor macros call for a few unique considerations. #define Cube( a ) a*a*a What’s wrong? Cube(3) Cube(x +1) Cube(y-x) Expand #define Cube( a ) (a)*(a)*(a ) Try again Cube(3)^2 Expand #define Cube( a ) ((a)*(a)*(a )) Try again