Introduction to Programming Structure Lesson 4 McManusCOP10001.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Quality of a Class Abstraction: Coupling & Cohesion Michael L. Collard, Ph.D. Department of Computer Science Kent State University.
Programming Languages and Paradigms
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lesson 4 McManus COP  Pointers  Modules & Functions  Cohesion & Coupling  Local & Global Variables  Parameters  Variable Names & Data Dictionaries.
CS0004: Introduction to Programming Repetition – Do Loops.
Module: Definition ● A logical collection of related program entities ● Not necessarily a physical concept, e.g., file, function, class, package ● Often.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Chapter 4 Sec. 4.1, 4.2, 4.4 Procedures (User-defined)
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
INTRODUCTION TO PROGRAMMING STRUCTURE Chapter 4 1.
สาขาวิชาเทคโนโลยี สารสนเทศ คณะเทคโนโลยีสารสนเทศ และการสื่อสาร.
1 VBA – podstawowe reguły języka Opracowanie Janusz Górczyński wg Microsoft Help.
CSCI 3327 Visual Basic Chapter 6: Methods: A Deeper Look UTPA – Fall 2011.
Introduction to Programming Structure Lesson 4 McManusCOP10061.
Flow of Control. 2 Control Structures Control structure: An instruction that determines the order in which other instructions in a program are executed.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Lecture 14 Functions.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Problem Solving with Decisions
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Program Organization Sequential Execution: One line done after the other Conditional Execution: If a test is true, one section is done, otherwise another.
Chapter 3: User-Defined Functions I
Systems Design.  Application Design  User Interface Design  Database Design.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
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.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Coupling and Cohesion Schach, S, R. Object-Oriented and Classical Software Engineering. McGraw-Hill, 2002.
Sub Procedures and Functions Visual Basic. Sub Procedures Slide 2 of 26 Topic & Structure of the lesson Introduction to Modular Design Concepts Write.
Computer Programming 12 Lesson 4 - Computer Programming Structure By Dan Lunney.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Programming Logic and Design Seventh Edition
Coupling and Cohesion Rajni Bhalla.
Chapter 6: User-Defined Functions I
Coupling and Cohesion 1.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Object-Oriented Programming: Classes and Objects
User-Defined Functions
6 Chapter Functions.
Programming Logic and Design Fourth Edition, Comprehensive
Software Design Lecture : 9.
Flow of Control.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Introduction to Programming Structure Lesson 4 McManusCOP10001

Overview Guidelines Modules & Functions Cohesion & Coupling Local & Global Variables Parameters Variable Names & Data Dictionaries Three Logic Structures McManusCOP10002

Guidelines on Program Structure Use Modules –Each part should have a particular function Use the three logic structures –Sequential, Decision & Iteration Don’t reinvent the wheel –Avoid rewriting identical processes Use techniques to improve readability McManusCOP10003

Cohesion & Coupling Making Modules Better! McManusCOP10004

Cohesion & Coupling Each module should –Be functionally independent –Perform one problem-related task Calculating IRS Withholding is one problem-related task, but may have multiple operations within the module –When connected, use the smallest interface possible. McManusCOP10005

Cohesion The degree of interaction within a module. –Each module should perform one functionally-related task…not necessarily one assignment statement. –Concentration is on what goes on within the module. McManusCOP10006 Term was coined by Larry Constantine in mid-1960’s

Scale of Cohesion Stevens, Myers, Constantine, and Yourdon developed the Scale of Cohesion as a measure of the “black boxiness” of a module, and as a result, the maintainability of a module. McManusCOP10007 Type Measure Black Box Functional BestBlack Box Informational ** Best Sequential Communicational ProceduralGray Box Temporal Logical Coincidental WorstTransparent or White Box **Originally not part of Scale

Coupling The degree of interaction between two modules. –Interaction is the interface, or lack thereof, between two modules. The interface is the parameter list. –Create it, use it, lose it McManusCOP10008 Best (Lowest Interaction) Worst (Highest Interaction) Normal Data Stamp Control Common Content

Effects? Which pieces affect Cohesion and which affect Coupling? McManusCOP10009 Private Sub Minimum(min As Long, y As Long, z As Long) If y < min Then min = y End If If z < min Then min = z End If lblSmallest.Caption = "Smallest value is " & min End Sub What does this code do?

What is the code doing? What are the parameters? Variables? McManusCOP Private Sub Minimum(Scully As Long, Mulder As Long) Dim Temp As Long If Scully < Mulder Then Temp = Scully Scully = Mulder Mulder = Temp End If End Sub Global & Parameters Local Variable

Each Goal Cohesion’s Goal –To create a procedure that performs one functionally-related task. Coupling’s Goal –To protect global data and local data from being used within a procedure without declaring it on the procedure’s header Create as close to where you’re going to use it as possible, use it, then lose it as soon as possible McManusCOP100011

Goal of Cohesion & Coupling? High Cohesion –Functional or Information Low Coupling –Data, Stamp, Control McManusCOP100012

Modules, Procedures & Functions The subparts to a Program McManusCOP100013

Modules “A module is a lexically contiguous sequence of program statements, bounded by boundary elements, having an aggregate identifier.” Yourdon & Constantine (1979) –A part of a larger system –Written and tested separately –Combined with other modules to form a complete system –Used in top-down programming –Procedures & Functions McManusCOP100014

Procedures A smaller part of the main program. 2 Advantages 1.Eliminates the need to program the same thing more than once. 2.Larger programs are easier to read when broken into procedures (and functions). McManusCOP100015

Functions –A subprogram that acts like a mathematical function: Given a particular set of argument values, the function returns a unique result. Big Difference Between Procedures & Functions: –Use Return values that are associated with the name of the function McManusCOP100016

Function Examples Pascal FUNCTION doublenum(b : Integer) : Integer; BEGIN doublenum := 2 * b END; Visual Basic Private Function Doublenum(b As Integer) As Integer Doublenum = 2 * b End Function C++ Int doublenum ( int b) { return 2 * b; } McManusCOP All three do the same thing, just with different syntax

What Do They Have In Common? Each module –is an entity by itself –has a single purpose –should be easily read, modified and maintained –Length is governed by function and number of instructions contained within –Controls the order of processing McManusCOP100018

An Example of Control McManusCOP100019

Types of Modules/Procedures Control –Demonstrates overall flow of data Initialization & Wrap-Up –Processes instructions to be performed once (either at beginning or at the end of the program) –Used typically in batch processing Process Data –Calculation –Print –Read and Validation Event –Used in OO and some event driven programming languages –More about these later McManusCOP100020

Control Modules Most often called “Main” All other modules, procedures and functions are subordinate to the control module Sub Main Call ProcedureA(X, Y) Call ProcedureB(A, B) End Main McManusCOP100021

Init Module Used in some languages to initialize variables or processes –Examples Opening files Initializing variables Printing report headings Procedure Begin Dim X, Y, Z As Integers Open Payroll file End Procedure ‘Begin McManusCOP Does this violate Cohesion or Coupling?

Process Data Modules Calculation –Performs Arithmetic operations Accumulations Sorting or Searching Private Sub Double (X, Y) Dim Temp as Integer Temp = X * Y Print Temp End Sub  Read and Data Validation ◦ Reads and validates input data  Usually separate modules McManusCOP Private Sub Verify(X) If X 10 Then lblMessage.Text = “Data Error” End If End Sub

Wrap Up Module Used to close out processes –Examples Closing files Printing reports Returning updated data to database Procedure LastProcedure Close Employee file Close Payroll file End Procedure ‘LastProcedure McManusCOP Does this violate Cohesion or Coupling?

Global or Local Variables Scope! McManusCOP100025

Scope The area of a program where an identifier (variable) is visible When an identifier has multiple declarations in different modules, the most local declaration is used each time that identifier is referenced. (overloading) Global or “non-local” variables subject to side effects. McManusCOP100026

Side Effects Caused when the value of a global variable is changed within a procedure or function –Any effect of one module on another module that is not a part of the explicitly defined interface between them Also caused when a variable name is used in globally and locally (causes overloading) A nasty effect that should be avoided! McManusCOP100027

Global Scope Declared within the main program Can be referenced anywhere in the program –Is visible and accessible everywhere McManusCOP X, Y, Z A C B X, Y & Z are Global to modules A, B & C

Local Scope Declared within a module –Has no effect outside the procedure or function in which it is declared Can be referenced only within a procedure or a function McManusCOP X, Y, Z A m C p B n Within A, Variable m is defined, but can also see X, Y, & Z Within B, Variable n is defined, but can also see X, Y, & Z Within C, Variable p is defined, but can also see X, Y, & Z

Global or Local? Private Sub Minimum(Scully As Long, Mulder As Long) Dim Temp As Long If Scully < Mulder Then Temp = Scully Scully = Mulder Mulder = Temp End If End Sub McManusCOP Scully & Mulder are what type of variables? What type of variable is Temp?

Another Example McManusCOP Scope of X, Y, Z, Procedure1 Scope of M, N, Me, X, You program ShowScope; var X, Y, Z : Real; procedure Procedure1 (var M, N, Me : Real); var X, You : Real; begin{Procedure1} end;{Procedure 1} begin {ShowScope} Procedure1(X, Y, Z) end.{ShowScope}

Parameters How we avoid side effects! McManusCOP100032

Parameters Are the variables that are passed into and out of modules Use global parameters –(to the procedure or function) Pass values through the use of variables Actual and Formal parameters Call-by-reference & Call-by-value McManusCOP100033

Parameter Communication A measure of the quantity of data passing through a module’s interface. Is also a measure of the module’s coupling. The goal is to strive for a minimal amount of information being passed. McManusCOP100034

How Parameters are Used Input Parameter –Information passed into a procedure, but not returned or passed out of the procedure. Output Parameter –Information returned to the calling program from a procedure. Input/Output Parameter –Information passed into a procedure, perhaps modified, and a new value returned. McManusCOP Programmers now determine how their parameters are used.

Parameters Provide the communication links between the main program and its modules. Make procedures and functions more versatile. –Different data can be manipulated each time the module is called. Come in two types: –Actual –Formal McManusCOP100036

Actual Parameters –Are substituted for the formal parameter at the time the procedure is called. Parameters used in the call statement –Statements that transfer control to a procedure. Data types must be assignment compatible with its corresponding formal parameter –If they don’t, your program will blow up! Can be a variable, constant or an expression Can be call-by-value or call-by-reference McManusCOP100037

Formal Parameters –Is a list of “place marker” names used in the procedure’s declaration. –Parameters declared in the procedure header –Can include the data type of the valued parameters. –Must be a variable –Can be call-by-value or call-by-reference McManusCOP100038

Parameter Correspondence Rules Determined by position in respective parameter lists Lists must be the same size, although the names may differ Data Types of corresponding actual and formal parameters must be identical McManusCOP100039

Data Areas After a Call McManusCOP ?? Formal Parameters Local Variables Sum Average Num1 Num2 Actual Parameters Var1 Var2 Main program data area Procedure data area

Valued & Variable Parameters By Reference (Call-by-Reference) –Passing a variable to a procedure is called passing an argument by reference, because a variable can be modified by a procedure and returned to the calling module. –You can use it AND you CAN change it! By Value (Call-by-Value) –Passing a literal value (such as a string in quotation marks) to a procedure is called passing an argument by value, because a value cannot be modified by a procedure. –You can use it BUT you CAN’T change it! McManusCOP100041

Call-by-Reference The default for parameter passing Gives access to the contents of the storage area where values are stored Giving the called procedure the ability to directly access the caller’s data Allowing changes in the data McManusCOP100042

Call-by-Value Protects the data being passed Accomplished by creating a copy of the value –without affecting the original value of the variable Thus… –Called procedure is unable to change the values stored in the variable’s storage area Helps avoid Side Effects! McManusCOP100043

Parameter Relationships Call Statements Actual Parameters Valued Variable McManusCOP Procedure Header Parameters Formal Parameters Valued Variable Parameter Interface using Global Variables

Another Look at Variables Names & the Data Dictionary McManusCOP100045

Variable Names-Reminder Use mnemonic terms –Use a variable name that relates the name of the variable to its usage Contributes to self-documenting code –Which reduces the amount of commenting required –Z = X * Y What is it doing (besides multiplication?) –SalesTax = SalesTaxRate * Cost (this you know) Examples –SalesTax, SalesRate, Sales_Rate, PayRate, Temp McManusCOP100046

The Data Dictionary Defines all of the variables used within a program Lists: –Item Name –Variable Names –Domain (range of possible values) –Data type –Location defined & accessed –Test Data (or error checking) McManusCOP Required!

DD Example Item Name (required) Variable Name (required) Data Type (required) ModulesDomain (Range) (required) Scope Hours worked HoursNumeric- real GetHours CalcGrossPay 0 <= n <=168 Global Gross Pay Numeric- real CalcGrossPay CalcDeductions CalcNetPay PrintPayChecks 0 <= n <=1 million Global Net Pay Numeric- real CalcNetPay PrintPayChecks 0 <= n <=1 million Local Global McManusCOP100048

The Three Logic Structures Sequential –One statement follows another Selection (Decision) –Allows choices based on the data –IfThenElse, Nested If’s, Case, Switch Iteration (Looping or Repetition) –Allows statements to be repeated a specified number of times –While, Do, For, Do Until, Repeat McManusCOP100049

McManusCOP Next?