Download presentation
Presentation is loading. Please wait.
1
High-Quality Routines
SCMP Special Topic: Software Development Spring 2017 James Skon
2
High-Quality Routines
What is it?
3
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?
4
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
5
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)
6
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.
7
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
8
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
9
Example - DeviceUnitsToPoints
points = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) Function DeviceUnitsToPoints ( deviceUnits Integer ): Integer DeviceUnitsToPoints = deviceUnits * ( POINTS_PER_INCH / DeviceUnitsPerInch() ) End Function points = DeviceUnitsToPoints( deviceUnits )
10
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
11
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.
12
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
13
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).
14
Type of Cohesion High Cohesion Functional Sequential Communicational
Procedural Temporal Logical Coincidental Low 14
15
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
16
Example Print next line
Reverse string of characters in second argument Add 7 to 5th argument Convert 4th argument to float 16
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
Outline Cohesion Coupling 28
29
Coupling The degree of dependence such as the amount of interactions among components No dependencies Loosely coupled some dependencies Highly coupled many dependencies
30
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)
31
Indications of Coupling
?
32
Type of Coupling High Coupling Content Avoid Common External Control
Stamp Data Uncoupled Avoid Loose Try to achieve Low 32
33
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
34
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
35
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
36
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
37
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
38
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
39
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
40
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
41
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) { … }
42
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
43
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.
44
Exercise: Define Coupling between Pairs of Modules
Content Common External Control Stamp Data Uncoupled
45
Coupling between Pairs of Modules
Q R S T U P
46
Consequences of Coupling
Why does coupling matter? What are the costs and benefits of coupling? (pairs, 3 minutes)
47
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
48
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
49
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()
50
Good Routine Names Bad Names!
Avoid meaningless, vague, or wishy- washy verbs: HandleCalculation() PerformServices() OutputUser() ProcessInput(), DealWithOutput() Bad Names!
51
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.
52
Good Routine Names Good!
To name a function, use a description of the return value: cos() customerId.Next() printer.IsReady() pen.CurrentColor() Good!
53
Good Routine Names To name a procedure, use a strong verb followed by an object. PrintDocument() CalcMonthlyRevenues() CheckOrderlnfo() RepaginateDocument()
54
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
55
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()
56
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).
57
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).
58
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).
59
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.
60
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.
61
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
62
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; }
63
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!
64
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
65
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.