Chapter 1 Principles of Programming and Software Engineering
-
Upload
jefferson-tommy -
Category
Documents
-
view
35 -
download
0
description
Transcript of Chapter 1 Principles of Programming and Software Engineering
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Data Abstraction & Problem Solving with Data Abstraction & Problem Solving with C++C++
Fifth EditionFifth Edition
by Frank M. Carranoby Frank M. Carrano
Chapter 1Chapter 1Principles of Principles of
Programming and Software EngineeringProgramming and Software Engineering
22Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Software Engineering and Software Engineering and Object-Oriented DesignObject-Oriented Design
Coding without a solution design increases Coding without a solution design increases debugging timedebugging time
A team of programmers for a large software A team of programmers for a large software development project requiresdevelopment project requires– An overall planAn overall plan– OrganizationOrganization– CommunicationCommunication
Software engineeringSoftware engineering– Provides techniques to facilitate the development of Provides techniques to facilitate the development of
computer programscomputer programs
33Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
An Examination of Problem An Examination of Problem SolvingSolving
Problem solvingProblem solving– The process of taking the statement of a problem and The process of taking the statement of a problem and
developing a computer program that solves that problemdeveloping a computer program that solves that problem Object-oriented analysis and design (OOA / D)Object-oriented analysis and design (OOA / D)
– A process for problem solvingA process for problem solving– A problem solution is a program consisting of a system A problem solution is a program consisting of a system
of interacting classes of objectsof interacting classes of objects Each object has characteristics and behaviors related to the Each object has characteristics and behaviors related to the
solutionsolution A class is a set of objects having the same typeA class is a set of objects having the same type
44Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Aspects of an Object-Oriented Aspects of an Object-Oriented SolutionSolution
A solution is a C++ program A solution is a C++ program consisting of:consisting of:– ModulesModules
A single, stand-alone functionA single, stand-alone function A method of a classA method of a class A classA class Several functions or classes working closely Several functions or classes working closely
togethertogether Other blocks of codeOther blocks of code
55Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Aspects of an Object-Oriented Aspects of an Object-Oriented SolutionSolution
Functions and methods implement Functions and methods implement algorithmsalgorithms– Algorithm: a step-by-step recipe for Algorithm: a step-by-step recipe for
performing a task within a finite period of performing a task within a finite period of timetime
– Algorithms often operate on a collection of Algorithms often operate on a collection of datadata
66Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Aspects of an Object-Oriented Aspects of an Object-Oriented SolutionSolution
Create a good set of modulesCreate a good set of modules– Modules must store, move, and alter dataModules must store, move, and alter data– Modules use algorithms to communicate Modules use algorithms to communicate
with one anotherwith one another
Organize your data collection to Organize your data collection to facilitate operations on the datafacilitate operations on the data
77Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Abstraction and Information Abstraction and Information HidingHiding
AbstractionAbstraction– Separates the purpose of a module from its Separates the purpose of a module from its
implementationimplementation– Specifications for each module are written Specifications for each module are written
before implementationbefore implementation– Functional abstractionFunctional abstraction
Separates the purpose of a module from its Separates the purpose of a module from its implementationimplementation
88Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Abstraction and Information Abstraction and Information HidingHiding
– Data abstractionData abstraction Focuses on the operations of data, not on the Focuses on the operations of data, not on the
implementation of the operationsimplementation of the operations
– Abstract data type (ADT)Abstract data type (ADT) A collection of data and a set of operations on the A collection of data and a set of operations on the
datadata You can use an ADT’s operations without You can use an ADT’s operations without
knowing their implementations or how data is knowing their implementations or how data is stored, if you know the operations’ specificationsstored, if you know the operations’ specifications
99Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Abstraction and Information Abstraction and Information HidingHiding
– Data structureData structure A construct that you can define within a A construct that you can define within a
programming language to store a collection of programming language to store a collection of datadata
– Develop algorithms and ADTs in tandemDevelop algorithms and ADTs in tandem
1010Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Abstraction and Information Abstraction and Information HidingHiding
Information hidingInformation hiding– Hide details within a moduleHide details within a module– Ensure that no other module can tamper with Ensure that no other module can tamper with
these hidden detailsthese hidden details– Public view of a modulePublic view of a module
Described by its specificationsDescribed by its specifications
– Private view of a modulePrivate view of a module Implementation details that the specifications Implementation details that the specifications
should not describeshould not describe
1111Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Principles of Object-Oriented Principles of Object-Oriented Programming (OOP)Programming (OOP)
Object-oriented languages enable us to Object-oriented languages enable us to build classes of objectsbuild classes of objects
A class combinesA class combines– Attributes (characteristics) of objects of a single typeAttributes (characteristics) of objects of a single type
Typically dataTypically data Called data membersCalled data members
– Behaviors (operations)Behaviors (operations) Typically operate on the dataTypically operate on the data Called methods or member functionsCalled methods or member functions
1212Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Principles of Object-Oriented Principles of Object-Oriented ProgrammingProgramming
Three principles of object-oriented Three principles of object-oriented programmingprogramming– EncapsulationEncapsulation
Objects combine data and operationsObjects combine data and operations Hides inner detailsHides inner details
– InheritanceInheritance Classes can inherit properties from other classesClasses can inherit properties from other classes Existing classes can be reusedExisting classes can be reused
– PolymorphismPolymorphism Objects can determine appropriate operations at execution Objects can determine appropriate operations at execution
time time
1313Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Object-Oriented Analysis and Object-Oriented Analysis and DesignDesign
AnalysisAnalysis– Process to developProcess to develop
An understanding of the problemAn understanding of the problem The requirements of a solutionThe requirements of a solution
– WhatWhat a solution must be and do a solution must be and do– Not Not howhow to design or implement it to design or implement it
– Generates an accurate understanding of what end Generates an accurate understanding of what end users will expect the solution to be and dousers will expect the solution to be and do
– Think about the problem, not how to solve itThink about the problem, not how to solve it
1414Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Object-Oriented Analysis and Object-Oriented Analysis and DesignDesign
Object-oriented analysis (OOA)Object-oriented analysis (OOA)– Expresses an understanding of the problem and the Expresses an understanding of the problem and the
requirements of a solution in terms of objects within requirements of a solution in terms of objects within the problem domainthe problem domain
– Objects can representObjects can represent Real-world objectsReal-world objects Software systemsSoftware systems IdeasIdeas
– OOA describes objects and their interactions among OOA describes objects and their interactions among one anotherone another
1515Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Object-Oriented Analysis and Object-Oriented Analysis and DesignDesign
Object-oriented design (OOD)Object-oriented design (OOD)– Expresses an understanding of a solution that Expresses an understanding of a solution that
fulfills the requirements discovered during OOAfulfills the requirements discovered during OOA– Describes a solution in terms ofDescribes a solution in terms of
Software objectsSoftware objects The collaborations of these objects with one anotherThe collaborations of these objects with one another
– Objects collaborate when they send messages (call each Objects collaborate when they send messages (call each other’s operations)other’s operations)
– Collaborations should be meaningful and minimalCollaborations should be meaningful and minimal
– Creates one or more models of a solutionCreates one or more models of a solution Some emphasize interactions among objectsSome emphasize interactions among objects Others emphasize relationships among objectsOthers emphasize relationships among objects
1616Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D Unified Modeling Language (UML)Unified Modeling Language (UML)
– A tool for exploration and communication during A tool for exploration and communication during the design of a solutionthe design of a solution
– Models a problem domain in terms of objects Models a problem domain in terms of objects independently of a programming languageindependently of a programming language
– Visually represents object-oriented solutions as Visually represents object-oriented solutions as diagrams diagrams
– Its visual nature is an advantage, since we are Its visual nature is an advantage, since we are visual creaturesvisual creatures
– Enables members of a programming team to Enables members of a programming team to communicate visually with one another and gain a communicate visually with one another and gain a common understanding of the system being built common understanding of the system being built
1717Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D UML use case for OOAUML use case for OOA
– A set of textual scenarios (stories) of the solutionA set of textual scenarios (stories) of the solution Each scenario describes the system’s behavior under Each scenario describes the system’s behavior under
certain circumstances from the perspective of the usercertain circumstances from the perspective of the user– Focus on the responsibilities of the system to Focus on the responsibilities of the system to
meeting a user’s goalsmeeting a user’s goals Main success scenario (happy path): interaction between Main success scenario (happy path): interaction between
user and system when all goes welluser and system when all goes well Alternate scenarios: interaction between user and Alternate scenarios: interaction between user and
system under exceptional circumstancessystem under exceptional circumstances
– Find noteworthy objects, attributes, and Find noteworthy objects, attributes, and associations within the scenariosassociations within the scenarios
1818Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
– An example of a main success scenarioAn example of a main success scenario Customer asks to withdraw money from a bank accountCustomer asks to withdraw money from a bank account Bank identifies and authenticates customerBank identifies and authenticates customer Bank gets account type, account number, and withdrawal Bank gets account type, account number, and withdrawal
amount from customeramount from customer Bank verifies that account balance is greater than Bank verifies that account balance is greater than
withdrawal amount withdrawal amount Bank generates receipt for the transactionBank generates receipt for the transaction Bank counts out the correct amount of money for customerBank counts out the correct amount of money for customer Customer leaves bankCustomer leaves bank
1919Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
– An example of an alternate scenarioAn example of an alternate scenario Customer asks to withdraw money from a bank accountCustomer asks to withdraw money from a bank account Bank identifies, but fails to authenticate customerBank identifies, but fails to authenticate customer Bank refuses to process the customer’s requestBank refuses to process the customer’s request Customer leaves bankCustomer leaves bank
2020Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
UML sequence (interaction) diagram for UML sequence (interaction) diagram for OODOOD– Models the scenarios in a use case Models the scenarios in a use case – Shows the interactions among objects over timeShows the interactions among objects over time– Lets you visualize the messages sent among objects Lets you visualize the messages sent among objects
in a scenario and their order of occurrencein a scenario and their order of occurrence– Helps to define the responsibilities of the objectsHelps to define the responsibilities of the objects
What must an object remember?What must an object remember? What must an object do for other objects?What must an object do for other objects?
2121Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Figure 1-2 Sequence diagram for the main success scenario
2222Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Figure 1-3 Sequence diagram showing the creation of a new object
2323Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
UML class (static) diagramUML class (static) diagram– Represents a conceptual model of a class of objects Represents a conceptual model of a class of objects
in a language-independent wayin a language-independent way– Shows the name, attributes, and operations of a Shows the name, attributes, and operations of a
classclass– Shows how multiple classes are related to one Shows how multiple classes are related to one
anotheranother
2424Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Figure 1-4 Three possible class diagrams for a class of banks
2525Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Figure 1-5 A UML class diagram of a banking system
2626Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Class relationshipsClass relationships– AssociationAssociation
The classes know about each otherThe classes know about each other Example: The Bank and Customer classesExample: The Bank and Customer classes
– Aggregation (Containment)Aggregation (Containment) One class contains an instance of another classOne class contains an instance of another class Example: The Bank and Account classesExample: The Bank and Account classes The lifetime of the containing object and the object The lifetime of the containing object and the object
contained are not necessarily the samecontained are not necessarily the same– Banks “live” longer than the accounts they containBanks “live” longer than the accounts they contain
2727Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Class relationships (Continued)Class relationships (Continued)– CompositionComposition
A stronger form of aggregationA stronger form of aggregation The lifetime of the containing object and the The lifetime of the containing object and the
object contained are the sameobject contained are the same Example: A ballpoint penExample: A ballpoint pen
– When the pen “dies,” so does the ballWhen the pen “dies,” so does the ball
2828Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D
Class relationships (Continued)Class relationships (Continued)– GeneralizationGeneralization
Indicates a family of classes related by inheritanceIndicates a family of classes related by inheritance Example: Account is an ancestor class; the attributes and Example: Account is an ancestor class; the attributes and
operations of Account are inherited by the descendant operations of Account are inherited by the descendant classes, Checking and Savingsclasses, Checking and Savings
2929Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D NotationNotation
– AssociationAssociation A relationship between two classes is shown by a A relationship between two classes is shown by a
connecting solid lineconnecting solid line Relationships more specific than association are Relationships more specific than association are
indicated with arrowheads, as you will seeindicated with arrowheads, as you will see Multiplicities: Optional numbers at the end(s) of an Multiplicities: Optional numbers at the end(s) of an
association or other relationshipassociation or other relationship– Each bank object is associated with zero or more Each bank object is associated with zero or more
customers (denoted 0..*), but each customer is associated customers (denoted 0..*), but each customer is associated with one bankwith one bank
– Each customer can have multiple accounts of any type, but Each customer can have multiple accounts of any type, but an account can belong to only one customeran account can belong to only one customer
3030Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Applying the UML to OOA/DApplying the UML to OOA/D Notation (Continued)Notation (Continued)
– Aggregation (Containment)Aggregation (Containment) Denoted by an open diamond arrowhead pointing to the Denoted by an open diamond arrowhead pointing to the
containing classcontaining class
– CompositionComposition Denoted by a filled-in diamond arrowhead Denoted by a filled-in diamond arrowhead pointing to pointing to the the
containing classcontaining class
– Generalization (Inheritance)Generalization (Inheritance) Denoted by an open triangular arrowhead pointing to the Denoted by an open triangular arrowhead pointing to the
ancestor (general or parent) classancestor (general or parent) class
– UML also provides notation to specify visibility, UML also provides notation to specify visibility, type, parameter, and default value informationtype, parameter, and default value information
3131Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
The Software Life CycleThe Software Life Cycle
Describes the phases of software Describes the phases of software development from conception to development from conception to deployment to replacement to deletiondeployment to replacement to deletion– We will examine the phases from project conception We will examine the phases from project conception
to deployment to end usersto deployment to end users– Beyond this development process, software needs Beyond this development process, software needs
maintenance to correct errors and add featuresmaintenance to correct errors and add features– Eventually software is retiredEventually software is retired
3232Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Iterative and EvolutionaryIterative and Evolutionary DevelopmentDevelopment
Iterative development of a solution to a Iterative development of a solution to a problemproblem– Many short, fixed-length iterationsMany short, fixed-length iterations– Each iteration builds on the previous iteration until a Each iteration builds on the previous iteration until a
complete solution is achievedcomplete solution is achieved– Each iteration cycles through analysis, design, Each iteration cycles through analysis, design,
implementation, testing, and integration of a small implementation, testing, and integration of a small portion of the problem domainportion of the problem domain
– Early iterations create the core of the system; further Early iterations create the core of the system; further iterations build on that coreiterations build on that core
3333Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Iterative and Evolutionary Iterative and Evolutionary DevelopmentDevelopment
Each iteration has a duration called the Each iteration has a duration called the timeboxtimebox– Chosen at beginning of projectChosen at beginning of project– Typically 2 to 4 weeksTypically 2 to 4 weeks
The partial system at the end of each iteration The partial system at the end of each iteration should be functional and completely testedshould be functional and completely tested
Each iteration makes relatively few changes Each iteration makes relatively few changes to the previous iterationto the previous iteration
End users can provide feedback at the end of End users can provide feedback at the end of each iterationeach iteration
3434Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
RUP gives structure to the software development RUP gives structure to the software development processprocess
RUP uses the OOA/D tools we introducedRUP uses the OOA/D tools we introduced Four development phases:Four development phases:
– Inception: feasibility study, project vision, time/cost estimatesInception: feasibility study, project vision, time/cost estimates– Elaboration: refinement of project vision, time/cost estimates, Elaboration: refinement of project vision, time/cost estimates,
and system requirements; development of core systemand system requirements; development of core system– Construction: iterative development of remaining systemConstruction: iterative development of remaining system– Transition: testing and deployment of the systemTransition: testing and deployment of the system
3535Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
Figure 1-7 RUP development phases
3636Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
Inception phaseInception phase– Define initial set of system requirementsDefine initial set of system requirements– Generate a core set of use case scenarios (about 10% of total Generate a core set of use case scenarios (about 10% of total
number)number)– Identify highest-risk aspects of solutionIdentify highest-risk aspects of solution– Choose iteration timebox lengthChoose iteration timebox length
3737Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
Elaboration phaseElaboration phase– Iteratively develop core architecture of systemIteratively develop core architecture of system– Address highest-risk aspects of systemAddress highest-risk aspects of system
Most potential for system failure, so deal with them firstMost potential for system failure, so deal with them first– Define most of the system requirementsDefine most of the system requirements– Extends over at least 2 iterations to allow for Extends over at least 2 iterations to allow for
feedbackfeedback– Each iteration progresses through OO analysis and Each iteration progresses through OO analysis and
design (use case scenarios, sequence design (use case scenarios, sequence diagrams, class diagrams), coding, testing, diagrams, class diagrams), coding, testing, integration, and feedbackintegration, and feedback
3838Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
Construction phaseConstruction phase– Begins once most of the system requirements are formalizedBegins once most of the system requirements are formalized– Develops the remaining systemDevelops the remaining system– Each iteration requires less analysis and designEach iteration requires less analysis and design– Focus is on implementation and testing Focus is on implementation and testing
Transition phaseTransition phase– Beta testing with advanced end usersBeta testing with advanced end users– System moves into a production environmentSystem moves into a production environment
3939Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Rational Unified Process (RUP) Rational Unified Process (RUP) Development PhasesDevelopment Phases
Figure 1-8 Relative amounts of work done in each development phase
4040Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
What About the Waterfall What About the Waterfall Method of Development?Method of Development?
Develops a solution sequentially by moving Develops a solution sequentially by moving through phases: requirements analysis, design, through phases: requirements analysis, design, implementation, testing, deploymentimplementation, testing, deployment
Hard to correctly specify a system without early Hard to correctly specify a system without early feedbackfeedback
Wrong analysis leads to wrong solutionWrong analysis leads to wrong solution Outdated and should not be usedOutdated and should not be used Do not impose this method on RUP developmentDo not impose this method on RUP development
4141Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Achieving a Better SolutionAchieving a Better Solution
Analysis and design improve solutionsAnalysis and design improve solutions What aspects of one solution make it better than What aspects of one solution make it better than
another?another? What aspects lead to better solutions?What aspects lead to better solutions?
4242Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Evaluation of Designs and Evaluation of Designs and SolutionsSolutions
CohesionCohesion– A highly cohesive module performs one well-defined A highly cohesive module performs one well-defined
tasktask A person with low cohesion has “too many irons in the fire”A person with low cohesion has “too many irons in the fire”
– Promotes self-documenting, easy-to-understand Promotes self-documenting, easy-to-understand codecode
– Easy to reuse in other software projectsEasy to reuse in other software projects– Easy to revise or correctEasy to revise or correct– Robust: less likely to be affected by change; Robust: less likely to be affected by change;
performs well under unusual conditionsperforms well under unusual conditions– Promotes low couplingPromotes low coupling
4343Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Evaluation of Designs and Evaluation of Designs and SolutionsSolutions
CouplingCoupling– Modules with low coupling are independent of one anotherModules with low coupling are independent of one another– System of modules with low coupling is System of modules with low coupling is
Easier to change: A change to one module won’t affect anotherEasier to change: A change to one module won’t affect another Easier to understandEasier to understand
– Module with low coupling isModule with low coupling is Easier to reuseEasier to reuse Has increased cohesionHas increased cohesion
– Coupling cannot be and should not be eliminated entirelyCoupling cannot be and should not be eliminated entirely Objects must collaborateObjects must collaborate
– Class diagrams show dependencies among classes, and Class diagrams show dependencies among classes, and hence couplinghence coupling
4444Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Evaluation of Designs and Evaluation of Designs and SolutionsSolutions
Minimal and complete interfacesMinimal and complete interfaces– A class interface declares publicly accessible methods (and data)A class interface declares publicly accessible methods (and data)
Describes only way for programmers to interact with the classDescribes only way for programmers to interact with the class
– Classes should be easy to understand, and so have few methodsClasses should be easy to understand, and so have few methods Desire to provide power is at odds with this goalDesire to provide power is at odds with this goal
– Complete interfaceComplete interface Provides methods for any reasonable task consistent with the Provides methods for any reasonable task consistent with the
responsibilities of the classresponsibilities of the class Important that an interface is completeImportant that an interface is complete
– Minimal interfaceMinimal interface Provides only essential methodsProvides only essential methods Classes with minimal interfaces are easier to understand, use, and Classes with minimal interfaces are easier to understand, use, and
maintainmaintain Less important than completenessLess important than completeness
4545Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Evaluation of Designs and Evaluation of Designs and SolutionsSolutions
– Signature: the interface for a method or functionSignature: the interface for a method or function Name of method/functionName of method/function Arguments (number, order, type)Arguments (number, order, type) Qualifiers such as Qualifiers such as constconst
4646Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Operation ContractsOperation Contracts
A module’s operation contract specifies itsA module’s operation contract specifies its– PurposePurpose– AssumptionsAssumptions– InputInput– OutputOutput
Begin the contract during analysis, finish Begin the contract during analysis, finish during designduring design
Use to document code, particularly in Use to document code, particularly in header filesheader files
4747Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Operation ContractsOperation Contracts
Specify data flow among modulesSpecify data flow among modules– What data is available to a module?What data is available to a module?– What does the module assume?What does the module assume?– What actions take place?What actions take place?– What effect does the module have on the data?What effect does the module have on the data?
4848Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Operation ContractsOperation Contracts
Contract shows the responsibilities of one module Contract shows the responsibilities of one module to anotherto another
Does Does notnot describe how the module will perform its describe how the module will perform its tasktask
Precondition: Statement of conditions that must Precondition: Statement of conditions that must exist before a module executesexist before a module executes
Postcondition: Statement of conditions that exist Postcondition: Statement of conditions that exist after a module executesafter a module executes
4949Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Operation ContractsOperation Contracts
First draft specificationsFirst draft specifications
sort(anArray, num)// Sorts an array.// Precondition: // anArray is an array of num integers; num > 0.// Postcondition: The integers in anArray are sorted.
5050Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Operation ContractsOperation Contracts
Revised specificationsRevised specifications
sort(sort(anArray, num), num)// Sorts an array into ascending order.// Sorts an array into ascending order.// Precondition: // Precondition: anArray is an array of num is an array of num // integers; 1 <= num <= MAX_ARRAY, where // integers; 1 <= num <= MAX_ARRAY, where // MAX_ARRAY is a global constant that specifies // MAX_ARRAY is a global constant that specifies // the maximum size of // the maximum size of anArray..// Postcondition: anArray[0] <= // Postcondition: anArray[0] <= anArray [1] <= ... [1] <= ...// <= // <= anArray [num-1], num is unchanged. [num-1], num is unchanged.
5151Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
VerificationVerification
AssertionAssertion: A statement about a particular : A statement about a particular condition at a certain point in an algorithmcondition at a certain point in an algorithm– Preconditions and postconditions are examples of Preconditions and postconditions are examples of
assertionsassertions InvariantInvariant: A condition that is always true at a : A condition that is always true at a
certain point in an algorithmcertain point in an algorithm Loop invariantLoop invariant: A condition that is true before and : A condition that is true before and
after each execution of an algorithm’s loopafter each execution of an algorithm’s loop– Can be used to detect errors before coding is startedCan be used to detect errors before coding is started
5252Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
VerificationVerification
Loop invariant (continued)Loop invariant (continued)– The invariant for a correct loop is true:The invariant for a correct loop is true:
Initially, after any initialization steps, but before the Initially, after any initialization steps, but before the loop begins executionloop begins execution
Before every iteration of the loopBefore every iteration of the loop After every iteration of the loopAfter every iteration of the loop After the loop terminatesAfter the loop terminates
5353Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
VerificationVerification
It is possible to prove the correctness of It is possible to prove the correctness of some algorithmssome algorithms– Like proving a theorem in geometryLike proving a theorem in geometry– Starting with a precondition, you prove that each Starting with a precondition, you prove that each
assertion before a step in an algorithm leads to the assertion before a step in an algorithm leads to the assertion after the step until you reach the assertion after the step until you reach the postconditionpostcondition
5454Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
What is a Good Solution?What is a Good Solution? A solution is good if:A solution is good if:
– The total cost it incurs over all phases of its life The total cost it incurs over all phases of its life cycle is minimalcycle is minimal
The cost of a solution includes:The cost of a solution includes:– Computer resources that the program consumesComputer resources that the program consumes– Difficulties encountered by usersDifficulties encountered by users– Consequences of a program that does not behave Consequences of a program that does not behave
correctlycorrectly Programs must be well structured and Programs must be well structured and
documenteddocumented Efficiency is one aspect of a solution’s Efficiency is one aspect of a solution’s
costcost
5555Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in ProgrammingKey Issues in Programming
1.1. ModularityModularity2.2. StyleStyle3.3. ModifiabilityModifiability4.4. Ease of UseEase of Use5.5. Fail-safe programmingFail-safe programming6.6. DebuggingDebugging7.7. TestingTesting
5656Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: ModularityModularity
Modularity has a favorable impact onModularity has a favorable impact on– Constructing programsConstructing programs– Debugging programsDebugging programs– Reading programsReading programs– Modifying programsModifying programs– Eliminating redundant codeEliminating redundant code
5757Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: StyleKey Issues in Programming: Style
1.1. Use of private data membersUse of private data members
2.2. Proper use of reference argumentsProper use of reference arguments
3.3. Proper use of methodsProper use of methods
4.4. Avoidance of global variables in modulesAvoidance of global variables in modules
5.5. Error handlingError handling
6.6. ReadabilityReadability
7.7. DocumentationDocumentation
5858Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: ModifiabilityModifiability
Modifiability is easier through the use Modifiability is easier through the use ofof– Named constantsNamed constants– The The typedeftypedef statementstatement
5959Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: Ease of UseEase of Use
• In an interactive environment, the program In an interactive environment, the program should prompt the user for input in a clear should prompt the user for input in a clear mannermanner
• A program should always echo its inputA program should always echo its input• The output should be well labeled and easy The output should be well labeled and easy
to readto read
6060Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: Fail-Safe ProgrammingFail-Safe Programming
• Fail-safe programs will perform reasonably Fail-safe programs will perform reasonably no matter how anyone uses itno matter how anyone uses it
• Test for invalid input data and program logic Test for invalid input data and program logic errorserrors
• Check invariantsCheck invariants• Enforce preconditionsEnforce preconditions• Check argument valuesCheck argument values
6161Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: DebuggingDebugging
• Programmer must systematically check a Programmer must systematically check a program’s logic to find where an error occursprogram’s logic to find where an error occurs
• Tools to use while debugging:Tools to use while debugging:– – Single-steppingSingle-stepping
– – WatchesWatches
– – BreakpointsBreakpoints
– – coutcout statements statements
– – Dump functionsDump functions
6262Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: TestingTesting
LevelsLevels– Unit testing: Test methods, then classesUnit testing: Test methods, then classes– Integration testing: Test interactions among modulesIntegration testing: Test interactions among modules– System testing: Test entire programSystem testing: Test entire program– Acceptance testing: Show that system complies with Acceptance testing: Show that system complies with
requirementsrequirements
6363Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: TestingTesting
TypesTypes– Open-box (white-box or glass-box) testingOpen-box (white-box or glass-box) testing
Test knowing the implementationTest knowing the implementation Test all lines of code (decision branches, etc.)Test all lines of code (decision branches, etc.)
– Closed-box (black-box or functional) testingClosed-box (black-box or functional) testing Test knowing only the specificationsTest knowing only the specifications
6464Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: TestingTesting
Developing test dataDeveloping test data– Include boundary valuesInclude boundary values– Need to know expected resultsNeed to know expected results
6565Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: TestingTesting
TechniquesTechniques– assertassert statements to check invariants statements to check invariants– Disable, but do not remove, code used for testing Disable, but do not remove, code used for testing
/* and *//* and */ BooleansBooleans MacrosMacros
6666Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
Key Issues in Programming: Key Issues in Programming: TestingTesting
StubsStubs– An incompletely implemented method that simply An incompletely implemented method that simply
acknowledges that it was called acknowledges that it was called DriversDrivers
– A module that tests another moduleA module that tests another module– For example, a For example, a mainmain function function
6767Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
SummarySummary Software engineeringSoftware engineering
– Techniques to facilitate development of programsTechniques to facilitate development of programs Software life cycleSoftware life cycle
– Phases through which software progresses, from Phases through which software progresses, from conception to deployment to replacement to conception to deployment to replacement to deletiondeletion
Loop invariantLoop invariant– Property that is true before and after each iteration Property that is true before and after each iteration
of a loopof a loop Evaluating the quality of a solutionEvaluating the quality of a solution
– Correctness, efficiency, development time, ease of Correctness, efficiency, development time, ease of use, cost of modificationuse, cost of modification
6868Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
SummarySummary
Practice abstraction: Focus on what a Practice abstraction: Focus on what a module does, not howmodule does, not how– For data-management problemsFor data-management problems
Encapsulate data with operations by forming classesEncapsulate data with operations by forming classes
– For algorithmic tasksFor algorithmic tasks Break into subtasksBreak into subtasks
UML is a modeling language used to UML is a modeling language used to express OO designs visually express OO designs visually
6969Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
SummarySummary A solution should be easy to modifyA solution should be easy to modify
– ModularModular– Independent of implementation of it modules Independent of implementation of it modules
Each function/method should be as independent Each function/method should be as independent as possible and perform one well-defined taskas possible and perform one well-defined task
Each function/method should include a Each function/method should include a comment: purpose, precondition, and comment: purpose, precondition, and postconditionpostcondition
A program should be as fail-safe as possibleA program should be as fail-safe as possible Effective use of available diagnostic aids is one Effective use of available diagnostic aids is one
of the keys to debuggingof the keys to debugging Use “dump functions” to help to examine and Use “dump functions” to help to examine and
debug the contents of data structuresdebug the contents of data structures