Software Engineering CSE470 (Fall 2000) Instructor: Dr. B. Cheng (Sect. 1-3) TA: Arun Subramanian Software Engineering CSE470: Cheng 1 What is Software Engineering ??? The study of systematic and effective processes and technologies for supporting software development and maintenance activities Improve quality Reduce costs Software Engineering CSE470: Cheng 2 Historical Perspective 1940s: computers invented 1950s: assembly language, Fortran 1960s: COBOL, ALGOL, PL/1, operating systems 1969: First conference on Software Eng 1970s: multi-user systems, databases, structured programming Software Engineering CSE470: Cheng 3 Historical Perspective (cont.) 1980s: networking, personal computing, embedded systems, parallel architectures 1990s: information superhighway, distributed systems, OO 2000s: virtual reality, voice recognition, video conferencing, global computing, ... Software Engineering CSE470: Cheng 4 Hardware Costs vs Software Costs (% of overall costs) s/w costs h/w costs Software Engineering CSE470: Cheng 5 Why is software so expensive? Hardware has made great advances But, software has made great advances ... Do the least understood tasks in software When task is simple & understood, encode it in hardware Demand more and more of software Software Engineering CSE470: Cheng 6 Size of programs continues to grow Trivial: 1 month, 1 programmer, 500 LOC, Very small: 4 months, 1 programmer, 2000 LOC Course project Small: 2 years, 3 programmers, 50K LOC Intro programming assignments Nuclear power plant, pace maker Medium: 3 years, 10s of programmers, 100K LOC Optimizing compiler Software Engineering CSE470: Cheng 7 Size of programs continues to grow Large: 5 years, 100s of programmers, 1M LOC MS Word, Excel Very large: 10 years, 1000s of programmers, 10M LOC Air traffic control, Telecommunications, space shuttle Software Engineering CSE470: Cheng 8 Goals of this Course Expose you to some of the problems typically encountered in software eng Expose you to some of the techniques that have been found to be effective •Requires more rigor •Often appears “obvious” (but only after being learned) Software Engineering CSE470: Cheng 9 Overview of Course Emphasis on analysis and design Learn/apply new techniques for software development Learn to work with a group Improve technical writing skills Become up to date on current trends in SE Explore presentation media Software Engineering CSE470: Cheng 10 What’s the problem? Software cannot be built fast enough to keep up with H/W advances Rising expectations Feature explosion Increasing need for high reliability software Software Engineering CSE470: Cheng 11 What’s the problem? Software is difficult to maintain “aging software” Difficult to estimate software costs and schedules Too many projects fail Arianne Missile Denver Airport Baggage System Software Engineering CSE470: Cheng 12 Why is software engineering needed? To predict time, effort, and cost To improve software quality To improve maintainability To meet increasing demands To lower software costs To successfully build large, complex software systems To facilitate group effort in developing software Software Engineering CSE470: Cheng 13 Structure of Course (Short) assignments over readings In lab assignments (various SE tools) Group projects (prototype, analysis, design) One hour exam Presentations: oral presentations, prototype demos Software Engineering CSE470: Cheng 14 Software Engineering Phases Definition: What? Development: How? Maintenance: Managing change Umbrella Activities: Throughout lifecycle Software Engineering CSE470: Cheng 15 Definition Requirements definition and analysis Developer must understand Application domain Required functionality Required performance User interface Software Engineering CSE470: Cheng 16 Definition (cont.) Project planning Allocate resources Estimate costs Define work tasks Define schedule Software Engineering CSE470: Cheng System analysis Allocate system resources to Hardware Software Users 17 Development Software design User interface design High-level design Define modular components Define major data structures Detailed design Define algorithms and procedural detail Software Engineering CSE470: Cheng 18 Development (cont.) Coding Integration Develop code for each Combine modules module System testing Unit testing Software Engineering CSE470: Cheng 19 Maintenance Correction - Fix software defects Adaptation - Accommodate changes New hardware New company policies Enhancement - Add functionality Prevention - make more maintainable Software Engineering CSE470: Cheng 20 Umbrella Activities Reviews - assure quality Documentation - improve maintainability Version control - track changes Configuration management - integrity of collection of components Software Engineering CSE470: Cheng 21 Software Engineering Costs Maintenance Development Definition Software Engineering CSE470: Cheng 22 Software Engineering Costs Prevention Enhancement Adaption Correction Integration Coding Design Specification Requirements Software Engineering CSE470: Cheng 23 Relative Costs to Fix Errors Requirements Design Coding Testing After Delivery 1st Qtr 0 20 40 Software Engineering CSE470: Cheng 60 80 24 Waterfall Process Model Requirements Design Coding Testing Maintenance Software Engineering CSE470: Cheng 25 Prototyping Process Model Requirements Quick Design Prototype Evaluate Design Software Engineering CSE470: Cheng 26 When to use prototyping? Help the customer pin down the requirements Concrete model to “test out” Often done via the user interface Explore alternative solutions to a troublesome component e.g., determine if an approach gives acceptable performance Improve morale Partially running system provides visibility into a project Software Engineering CSE470: Cheng 27 Spiral Process Model Planning Customer Evaluation Software Engineering CSE470: Cheng Risk Analysis Engineering 28 Process Models Idealized views of the process Different models are often used for different subprocesses may use spiral model for overall development prototyping for a particularly complex component waterfall model for other components Software Engineering CSE470: Cheng 29 Capability Maturity Model Level 1: Initial success depends on people Level 2: Repeatable track cost, schedule, functionality Level 3: Defined Level 4: Managed collect detailed metrics Level 5: Optimizing continuous process improvement “built-in” process improvement use standardized processes Software Engineering CSE470: Cheng 30 Why is software development so difficult? Communication Between customer and developer Project characteristics Poor problem definition is largest cause of failed software projects Within development team More people = more communication New programmers need training Software Engineering CSE470: Cheng Novelty Changing requirements 5 x cost during development up to 100 x cost during maintenance Hardware/software configuration Security requirements Real time requirements Reliability requirements 31 Why is software development difficult? Personnel characteristics Ability Prior experience Communication skills Team cooperation Training Management issues Facilities and resources Identification Acquisition Software Engineering CSE470: Cheng (cont.) Realistic goals Cost estimation Scheduling Resource allocation Quality assurance Version control Contracts 32 Summary Software lifecycle consist of Different process models concentrate on different aspects Definition (what) Development (how) Maintenance (change) Waterfall model: maintainability Prototype model: clarifying requirements Spiral model: identifying risk Maintenance costs much more than development Software Engineering CSE470: Cheng 33 Bottom Line U.S. software is a major part of our societal infrastructure Costs upwards of $200 billion/year Need to Improve software quality Reduce software costs/risks Software Engineering CSE470: Cheng 34 Computer System Engineering Computer System Engineering is a problem-solving activity. Itemize desired system functions Analyze them Allocate functions to individual system elements Systems Analyst (computer systems engineer) Start with customer-defined goals and constraints Derive a representation of function, performance, interfaces, design constraints, and information structure That can be allocated to each of the generic system elements (i.e., Software, Hardware, People, database, documentation, procedures) Focus on WHAT, NOT how. Software Engineering CSE470: Cheng 35 Criteria for System Configuration: Technical Criteria for allocation of function and performance to generic system elements: Technical Analysis: (existence of necessary technology, function and performance assured, maintainability) Environmental Interfaces: (proposed configuration integrate with external environment, interoperability) Off-the-shelf options must be considered. Manufacturing evaluation: (facilities and equipment available, quality assured?) Software Engineering CSE470: Cheng 36 Criteria for System Configuration: Business Issues Criteria for allocation of function and performance to generic system elements: Project_Considerations: (cost, schedules, and risks) Business_Considerations: (marketability, profitability) Legal_Considerations: (liability, proprietary issues, infringement?) Human issues: (personnel trained? political problems, customer understanding of problem) Software Engineering CSE470: Cheng 37 Hardware and Hardware Engineering Characteristics: Components are packaged as individual building blocks Standardized interfaces among components Large number of off-the-shelf components Performance, cost, and availability easily determined/measured Hardware configuration built from a hierarchy of "building blocks." Software Engineering CSE470: Cheng 38 Hardware Engineering Phases to system engineering of hardware: Development Planning and requirements analysis: best classes of hardware for problem, availability of hardware type of interface required identification of what needs to be designed and built Establish a Plan or "road map" for design implementation May involve a hardware specification. Use CAE/CAD to develop a prototype (breadboard) Develop printed circuit (PC) boards Manufacturing of boards Software Engineering CSE470: Cheng 39 Software and Software Engineering Function may be the implementation of a sequential procedure for data manipulation Performance may not be explicitly defined (exception is real-time systems) Software element of computer-based system consists of two classes of programs, data, and documentation Application_Software: implements the procedure that is required to accommodate information processing functions System Software: implements control functions that enable application software to interface with other system elements Software Engineering CSE470: Cheng 40 Three high-level phases of Software Engineering Definition phase: Software planning step scope of project, risk, resource identification cost and schedule estimates Software Requirements Analysis Software Project Plan Requirements Specification System element allocated to software is defined in detail. Formal information domain analysis to establish models of information flow and structure (expand to produce specification) Prototype of software is built and evaluated by customer Performance requirements or resource limits defined in terms of software characteristics Definition and Requirements must be performed in cooperation Software Engineering CSE470: Cheng 41 Third Phase of Software Engineering Development Phase: Translate set of requirements into an operational system element Design Design Specification Coding (appropriate programming language or CASE tool) Should be able to directly trace detail design descriptions from code. Verification, release, and maintenance phase: Testing software: Testing Plan to find maximum number of errors before shipping Prepare software for release Quality Assurance Maintain software throughout its lifetime Software Engineering CSE470: Cheng 42 Structured Design: Design Issues Modularity Criteria: Decomposability: decompose large problem into easier to solve subproblems Composability: how well modules can be reused to create other systems Understandability: how easily understood without other reference info Continuity: make small changes and have them reflected in corresponding changes in one or a few modules Protection: architectural characteristic to reduce propagation of side effects of a given error in a module. Software Engineering CSE470: Cheng 43 Design Issues Basic Design Principle: Linguistic modular units: correspond to syntactic units in implementation language Few interfaces: minimize the number of interfaces between modules Small interfaces (weak coupling): minimize amount of info moving across interfaces Explicit interfaces: when modules do interact, should be in obvious way Information hiding: all info about module is hidden from outside access Software Engineering CSE470: Cheng 44 Design Heuristics Evaluate "First-cut" program structure Reduce coupling: Improve cohesion Use exploding: common process exists in 2 or more modules Use imploding: if high coupling exists, implode to reduce control transfer, reference to global data, and interface complexity Minimize Structures with high fan-out ; Strive for Fan-in as depth increases Keep scope effect of a module within scope of control of that module effect of module should be in deeper nesting Evaluate module interfaces: Reduce complexity Reduce redundancy Improve consistency Software Engineering CSE470: Cheng 45 Design Heuristics (cont’d) Define predicatable functions for modules, but not too restrictive: "Single-entry-single-exit" modules: Avoid "Pathological Connections" Black box modules are predictable Restricting module processing to single subfunction (high cohesion) High maintenance: if randomly restrict local data structure size, options within control flow, or types of external interface Enter at top, exit at bottom Pathological connection: entry into middle of module Package SW based on design constraints and portability requirements Assemble SW for specific processing environment Program may "overlay" itself in memory reorganize group modules according to degree of repetition, access frequency, and interval of calls Separate out modules only used once. Software Engineering CSE470: Cheng 46 Design Postprocessing After Transaction or transform analysis: complete documentation to be included as part of architectural design Processing narrative for each module Interface description for each module Definition of local and global data structures Description of all design restrictions Perform review of preliminary design "optimization" (as required or necessary) Software Engineering CSE470: Cheng 47 Design Optimization Objectives: Smallest number of modules (within effective modularity criteria) Least complex data structure for given purpose Refinement of program structure during early design stages is best Time-critical applications may require further refinements for optimizations in later stages (detailed design and coding) Software Engineering CSE470: Cheng 48 What is an Embedded System? Definition of an embedded computer system: is a digital system. uses a microprocessor (usually). runs software for some or all of its functions. frequently used as a controller. Software Engineering CSE470: Cheng 49 What an embedded system is NOT. Not a computer system that is used primarily for processing. Not a software system on a PC or Unix box. Not a traditional business or scientific application. Software Engineering CSE470: Cheng 50 Examples of Embedded Systems Medical instrument’s controls: CAT scanners, implanted heart monitors, etc. Automotive systems: electronic dashboards, ABS brakes, transmission controls. Controls for digital equipment: CD players, TV remote, programmable sprinklers, household appliances, etc. Software Engineering CSE470: Cheng 51 Why ‘embedded’? Because the processor is ‘inside’ some other system. A microprocessor is ‘embedded’ into your TV, car, or appliance. The consumer does not think about performing processing, Considers running a machine or `making something work’. Software Engineering CSE470: Cheng 52 Special Characteristics hardware and software (in one system) concurrency (several processes working at same time) timing (often real time) synchronization (this process must complete before this process begins) Software Engineering CSE470: Cheng sensors and actuators (for inputs and outputs) 53 How are embedded systems different than traditional software? Responding to sensors (Was this button pushed?) Turning on actuators (Turn on power to the boiler.) Real-time (Respond to temperature change within 3 seconds.) Software Engineering CSE470: Cheng 54 Differences between ES and traditional software development Not dealing with only sequential code. Routine can stop at completion or in response to an external event. Many parts of system might be running concurrently. Safety-critical component of many systems. Software Engineering CSE470: Cheng 55 Small and Many! Most embedded systems use 4-, 8-, or 16-bit processors. 32-bit used for intensive applications like printer controls. 8-bit processors have about 64K of memory, that limits amount of code. “By 1990 a total of about 45 million recognizable computers (i.e., PCs, Macintosh, even CP/M systems) were in place. Yet over 1 billion microprocessors and microcontrollers were shipped in that year alone!” Ganssle, J. The Art of Programming Embedded Systems Academic Press, 1992, San Diego, Cal. Software Engineering CSE470: Cheng 56 hardware or software ? Where to place functionality? ex: A Sort algorithm Faster in hardware, but more expensive. More flexible in software but slower. Must be able to explore these various trade-offs: Cost. Speed. Reliability. Form (size, weight, and power constraints.) Software Engineering CSE470: Cheng 57 hardware/software Codesign or ‘Codesign’ Model the hardware and the software system in a unified approach. Use similar design models. Need for ‘model continuity’ spanning levels of the design process. Software Engineering CSE470: Cheng 58 Traditional Embedded System Development Approach Decide on the hardware Give the chip to the software people. Software programmer must make software ‘fit’ on the chip and only use that hardware’s capabilities. Software Engineering CSE470: Cheng 59 Increased Complexity Systems are becoming more and more complex. Harder to think about total design. Harder to fix ‘bugs.’ Harder to maintain systems over time. Therefore, the traditional development process has to change, Software Engineering CSE470: Cheng 60 Less Time to Develop In embedded electronics, the total design cycle must decrease. Historically, design for automotive electronic systems takes 3-5 years to develop. Must become a 1-3 year development cycle. Must still be reliable and safe. B. Wilkie, R. Frank and J. Suchyta - Motorola Semiconductor Products Sectors, ‘Silicon or Software: The Foundation of Automotive Electronics’, IEEE Vehicular Tech., August 95. Software Engineering CSE470: Cheng 61 Solutions to Complexity: Need to keep design process abstract for a longer period of time. Decomposable hierarchy (object-oriented). Reuse previous designs: When a design changes, reuse similar sections. Don’t throw away last year’s design and start from scratch! Automated verification systems. Software Engineering CSE470: Cheng 62 Example: Fly-by-Wire Airplane How would you start to think about developing this complex/large system? What are potential problems with deciding on the hardware right away? What are possible concurrent systems needs? What type of timing constraints might be needed? Software Engineering CSE470: Cheng 63 Fly-by-Wire Airplane Continued What would be the sensors and actuators of this system? How concerned should developers be about the safety of the system? Would testing be enough? Software Engineering CSE470: Cheng 64 The Problems with Software Engineering Where do we go wrong? The UML lecture notes are based in part on those developed originally by Mats PE Heimdahl Software Engineering CSE470: Cheng 65 Common Problems The requirements are wrong Continual change Incomplete, inconsistent, or ambiguous The developer and the customer did not interpret the requirements the same way Requirements drift The requirements tend to change throughout the project Late design changes Software Engineering CSE470: Cheng The functionality of the system continually changes Many changes come late in the project Many changes during maintenance Breakdown of system structure The system finally becomes unusable 66 Solutions Rigorous requirements and planning stage Make sure all stakeholders understand and agree on the requirements Structure the system design to accommodate change Isolate parts that are likely to change Modularize so changes are contained Attempt to not compromise system structure during change Software Engineering CSE470: Cheng 67 Use-Cases and Scenarios A powerful approach to find out what the requirements on the system are Helps the analysts identify The various users of the system Humans, software, and machines The functions the system must provide Provide more stable requirements Software Engineering CSE470: Cheng 68 The OO Solution The problem domain is relatively constant Creating cards Auto pilot Assemble the card and get the right thing at the right place Get a plane from point A to point B using the available control surfaces The functionality and data representation is what is likely to change Creating cards The type of information and placement of information changes often The options available to the user evolve with time Auto pilot The hardware interfaces are different between different models The operational modes vary between models and evolve over time Structure the system based on the structure of the problem domain, NOT based on the structure of the solution Software Engineering CSE470: Cheng 69 What is OO A way of thinking about a problem (software) based on abstractions of concepts that exist in the real world OO is not constrained by implementation language (C, Pascal, FORTRAN , etc. will work) Software Engineering CSE470: Cheng 70 What is not OO Using an “object oriented” language (C++, Eiffel, Smalltalk) Using an “OO notation” for design You can easily misuse the OO support in these languages Misuse the notation for a non-OO design Calling what you do OO Management and customers like OO, therefore, that is what we are doing OO is not the answer to all your problems Software Engineering CSE470: Cheng 71 Several Complementary Models Structural Models Describes the structure of the objects in a system Structure of individual objects (attributes and operations) Relationships between the objects (inheritance, sharing, and associations) Clustering of objects in logical packages and on the actual hardware Dynamic models (behavioral models) The aspects related to sequencing of operations Changes to attributes and sequences of changes The control aspects of the system Software Engineering CSE470: Cheng 72 The OO Development Process Software Engineering CSE470: Cheng 73 We Will Cover Requirements specification Very briefly Iterative development Different models Three distinct models for which you can use UML Domain (or conceptual) model Analysis (specification) model Design (implementation) model How do we move between the models Software Engineering CSE470: Cheng 74 Process Overview Transition Inception Elaboration Software Engineering CSE470: Cheng Construction n Many iterations Construction 3 Construction 2 Inception Elaboration Construction Construction 1 Transition 75 Inception Creation of the basic idea that we want to implement (presumably with software) Could take many shapes A discussion over a beer at the pub A full fledged feasibility study Figure out (roughly) The business case How much money will this make the company Project scope Software Engineering CSE470: Cheng 76 Elaboration Answer the following: What is it you are going to build? How are you going to build it? What technology are you going to use? Your decisions should be guided by the risks Requirements risks Technological risks Skills risks Political risks Software Engineering CSE470: Cheng 77 Requirements Risks Poor or wrong requirements a serious problem Use UML notations to help you understand the customers requirements and the inherent structure of the problem domain Use-case diagrams and use cases to understand customer requirements Class diagrams, activity diagrams, and possibly other diagrams to understand the domain Software Engineering CSE470: Cheng 78 Plan the Construction Phase We will never build the entire system at once Categorize the use cases Incremental development “I absolutely must have this function in the system” “I can live without this feature for a little while” “This is an important function, but we might be able to live without it” Time estimate and allocate the use cases to iterations Software Engineering CSE470: Cheng 79 Construction Construct the system as a series of iterations Each iteration is a “mini” project Refine your domain model Identify all attributes and operations Define the dynamic behavior of all objects Analyze the use case, design, code, test, and integrate. State machines “Contracts” Make decisions influenced by platform and language Software Engineering CSE470: Cheng 80 Transition The phase between the beta release and the final product Wrap up all the issues that should not be done or cannot be done during the iterations Examples include performance evaluation and optimization Complete system testing No new functionality added Fix bugs Refactor your system a final time Software Engineering CSE470: Cheng 81 Three Distinct Models A conceptual model (domain model) An analysis model (specification model) Try to figure out what is really going on Build a model to better understand the problem Used to communicate with the customer and “domain” experts Model the software that will implement the system Focus on the software structure and the module interfaces Design model (implementation model) A detailed design of the software Including all attributes and detailed descriptions of the operations Software Engineering CSE470: Cheng 82 Summary Transition Inception Elaboration Software Engineering CSE470: Cheng Construction n Many iterations Construction 3 Construction 2 Inception Elaboration Construction Construction 1 Transition 83 Use Cases and Scenarios Software Engineering CSE470: Cheng 84 We Will Cover What is a use-case Use-Case diagrams Use-case versus user interaction The constructs in the use-case diagrams Capturing the use-case High-level use-case Extended use-case Difference between use case and scenario Software Engineering CSE470: Cheng 85 What is a Use-Case A use-case captures some user visible function This may be a large or small function A use-case achieves a discrete goal for the user Examples Depends on the level of detail in your modeling effort Format a document Request an elevator How are the use cases found (captured or elicited)? Software Engineering CSE470: Cheng 86 User Goals versus User Interactions Consider the following when formatting a document versus Format a document Ensure consistent formatting of two documents The latter is a user goal Define a style Change a style Copy a style from one document to the next Something the user wants to achieve The former are user interactions Things the user does to the system to achieve the goal Software Engineering CSE470: Cheng 87 Goals and Interactions There is a place for both goals and interactions Understand what the system shall do Understand how the user will achieve the goals Capture the user goals Capture user interactions Sequences of user interactions Thus, start with the user goals and then refine the user goals into several (many) user interactions Software Engineering CSE470: Cheng 88 Use-Case Diagrams (POST) POST: Point of Sale Terminal Use Case POST System Boundary Buy Item Log In Cashier Customer Refund a Purchased Item Adapted from Larman “Applying UML and Patterns” Software Engineering CSE470: Cheng 89 Another Example Set Limits Update Accounts Trading Manager Accounting System Analyze Risk «uses» Valuation «uses» Price Deal Trader Capture Deal «extends» Salesperson Adapted from Fowler “UML Distilled” Software Engineering CSE470: Cheng Limit Exceeded 90 Uses and Extends Includes You have a piece of behavior that is similar across many use cases Break this out as a separate use-case and let the other ones “include” it Examples include Valuation Validate user interaction Sanity check on sensor inputs Check for proper authorization Software Engineering CSE470: Cheng Extends A use-case is similar to another one but does a little bit more Put the normal behavior in one use-case and the exceptional behavior somewhere else Capture the normal behavior Try to figure out what can go wrong in each step Capture the exceptional cases in separate use-cases Makes it a lot easier to understand 91 Includes You have a piece of behavior that is similar across many use cases Break this out as a separate use-case and let the other ones “include” it Examples include Valuation Validate user interaction Sanity check on sensor inputs Check for proper authorization Software Engineering CSE470: Cheng 92 Extends A use-case is similar to another one but does a little bit more Put the normal behavior in one use-case and the exceptional behavior somewhere else Capture the normal behavior Try to figure out what can go wrong in each step Capture the exceptional cases in separate use-cases Makes it a lot easier to understand Software Engineering CSE470: Cheng 93 Setting the System Boundary The system boundary will affect your actors and use-cases POST Buy Item Log In Cashier Customer Refund a Purchased Item Adapted from Larman “Applying UML and Patterns” Software Engineering CSE470: Cheng MH 94 A Different Boundary Let us view the whole store as our system Store Buy Item Refund a Purchased Item Customer Adapted from Larman “Applying UML and Patterns” Software Engineering CSE470: Cheng 95 Partial POST POST Buy Item Log In Cashier Customer Refund a Purchased Item Start Up Manager Manage Users System Administrator And a Lot More Adapted from Larman “Applying UML and Patterns” Software Engineering CSE470: Cheng MH 96 POST Use-Case Use case: Actors: Type: Description: Buy Item Customer (initiator), Cashier Primary The Customer arrives at the checkout with items to purchase. The Cashier records the purchase items and collects a payment. On completion the Customer leaves with the items Software Engineering CSE470: Cheng 97 POST Expanded Use-Case Use case: Actors: Type: Description: Cross Ref.: Use-Cases: Buy Item Customer (initiator), Cashier Primary and essential The Customer arrives at the checkout with items to purchase. The Cashier records the purchase items and collects a payment. On completion the Customer leaves with the items. Requirements XX, YY, and ZZ Cashier must have completed the Log In use-case Software Engineering CSE470: Cheng 98 The Home Heating System Water Valve Water Pump Home Hot Water Controller Burner Fuel Valve 90 80 70 Fuel Off On 60 50 Control Panel Temp Sensor Software Engineering CSE470: Cheng 100 Home Heating Use-Case Diagram Home Heating Power Up Power Down Home Owner Change Temp. MH Software Engineering CSE470: Cheng 101 Home Heating Use-Cases Use case: Power Up Actors: Home Owner (initiator) Type: Primary and essential Description: The Home Owner turns the power on. Each room Cross Ref.: Use-Cases: is temperature checked. If a room is below the the desired temperature the valve for the room is opened, the water pump started, the fuel valve opened, and the burner ignited. If the temperature in all rooms is above the desired temperature, no actions are taken. Requirements XX, YY, and ZZ None Software Engineering CSE470: Cheng 102 Modified Home Heating Home Heating Temp. High Power Up «uses» «uses» Power Down Adjust Temp «uses» Home Owner «uses» Change Temp. Temp. Low MH Software Engineering CSE470: Cheng 103 HACS Homework assignment and collection are an integral part of any educational system. Today, this task is performed manually. What we want the homework assignment distribution and collection system (HACS for short) to do is to automate this process. HACS will be used by the instructor to distribute the homework assignments, review the students’ solutions, distribute suggested solution, and distribute student grades on each assignment. HACS shall also help the students by automatically distributing the assignments to the students, provide a facility where the students can submit their solutions, remind the students when an assignment is almost due, remind the students when an assignment is overdue. Software Engineering CSE470: Cheng 104 HACS Use-Case Diagram HACS Configure HACS Distribute Asignments Remind Student Get Assignment System Admin Post Solutions Submit Assignment Student Distribute Grade Get Solution Instructor Get Grade MH Software Engineering CSE470: Cheng 105 HACS Use-Cases Use case: Actors: Type: Description: Distribute Assignments Instructor (initiator) Primary and essential The Instructor completes an assignment and submits it to the system. The instructor will also submit the due date and the class the assignment is assigned for. Cross Ref.: Use-Cases: Requirements XX, YY, and ZZ Configure HACS must be done before any user (Instructor or Student) can use HACS Software Engineering CSE470: Cheng 106 Alternate HACS HACS Configure HACS Distribute Asignments System Admin Post Solutions Distribute Grade Student Instructor Remind Student Submit Assignment Software Engineering CSE470: Cheng MH 107 Alternate HACS Use-Cases Use case: Distribute Assignments Actors: Instructor (initiator), Student Type: Primary and essential Description: The Instructor completes an assignment and submits it to the system. The instructor will also submit the delivery date, due date, and the class the assignment is assigned for. The system will at the due date mail the assignment to the student. Cross Ref.: Requirements XX, YY, and ZZ Use-Cases: Configure HACS must be done before any user (Instructor or Student) can use HACS Software Engineering CSE470: Cheng 108 When to use Use-Cases In short, always!!! Requirements is the toughest part of software development Use-Cases is a powerful tool to understand Who your users are (including interacting systems) What functions the system shall provide How these functions work at a high level Spend adequate time on requirements and in the elaboration phase Software Engineering CSE470: Cheng 109 How it Fits Together Preliminary Investigation Report Requirements Specification Use-Cases a. All High Level b. Some Expanded Prototypes Use-Case Diagram Budget, Schedule Draft Conceptual Model Adapted from Larman “Applying UML and Patterns” Software Engineering CSE470: Cheng Glossary (data dictionary) 110 Conceptual Modeling A Short Discussion Software Engineering CSE470: Cheng 111 Outline Conceptual modeling The OO solution The object model (conceptual) The goal of conceptual modeling Syntax and semantics Object modeling approach Home Heating System Software Engineering CSE470: Cheng 112 Conceptual Modeling Early modeling to understand the problem Conducted in cooperation with the customer Domain experts Domain engineers No real problem analysis if the customer is not involved Power of OO It is simple and people can quickly participate effectively Software Engineering CSE470: Cheng 113 The OO Solution The OO model closely resembles the problem domain Base your model on the objects in the problem domain Iteratively refine the high-level model until you have an implementation Attempt to avoid big conceptual jumps during the development process Software Engineering CSE470: Cheng 114 Objects State of Michigan Drivers License J. Q. Public A-123456 03-12-63 Software Engineering CSE470: Cheng VISA J. Q. Public 123 4567 887766 998 115 Attributes and Operations Person class Person objects abstracts to Card objects Card class State of Michigan Drivers License VISA J. Q. Public A-123456 03-12-63 Attributes name age height weight Operations move change-job J. Q. Public 123 4567 887766 998 Attributes height width id-number Operations issue change Characteristics of Objects Identity Classification Abstract entities with the same structure (attributes) and behavior (operations) into classes Polymorphism Discrete and distinguishable entities The same operation may behave differently on different classes Inheritance Sharing of attributes and operations based on a hierarchical relationship Software Engineering CSE470: Cheng 117 The Class Diagrams Software Engineering CSE470: Cheng 118 Objects Something that makes sense in the application context (application domain) J.Q. Public Joe’s Homework Assignment 1 J. Q. Public’s drivers license All objects have identity and are distinguishable NOT objects Person Drivers license Software Engineering CSE470: Cheng 119 Classes Describes a group of objects with similar properties (attributes), common behavior (operations), common relationships to other classes, and common semantics Person J. Q. Public Joe Smith D. Q. Public Card Credit card Drivers license Teller card Software Engineering CSE470: Cheng 120 Class Diagrams Class diagram Person name: String age: integer Class with attributes Person person ID: integer name: String age: integer Software Engineering CSE470: Cheng Instance diagram Person Person D. Q. Public 32 J. Q. Public 35 Objects with values Objects have an identity Do not explicitly list object identifiers SSN OK! 121 Examples Person name: String age: integer height: integer weight: integer SSN: integer Software Engineering CSE470: Cheng Card height: integer width: integer thickness: integer id-number: integer 122 Operations and Methods Transformation that can be applied to or performed by an object May have arguments Card Shape height: integer width: integer thickness: integer id-number: integer height: integer width: integer rotate(angle: integer) move(x: integer, y: integer) issue() revoke() Software Engineering CSE470: Cheng 123 Object Notation - Summary Class name attribute-1 : data-type-1 = default-value-1 attribute-2 : data-type-2 = default-value-2 attribute-3 : data-type-3 = default-value-3 operation-1(argument-list-1) : result-type-1 operation-2(argument-list-2) : result-type-2 operation-3(argument-list-3) : result-type-3 Software Engineering CSE470: Cheng 124 Associations Conceptual connection between classes A credit card is issued-by a bank A person works-for a company Credit Card Person Issued-by8 Works-for8 Person Bank Class diagrams Company Company Works-for8 J.Q. Public 35 Michigan State Univ Software Engineering CSE470: Cheng Instance diagram 125 Associations are Bi-directional There is no direction implied in an association (Rumbaugh - OMT) Country name Person name Has-capital Is-issued Software Engineering CSE470: Cheng City name Drivers-license lic.-number: integer 126 Associations Have Direction Unified adds a direction indicator Inconsistently used Country name Person name Has-capital Is-issued Software Engineering CSE470: Cheng City name Drivers-license lic.-number: integer 127 Multiplicity One person holds one credit card Person Credit-card Holds 8 card-number: integer name: String One object can be related to many objects through the same association One person can hold zero or more credit cards (* stands for many) Software Engineering CSE470: Cheng Person name: String Holds 8 0..* Credit-card card-number: integer 128 Multiplicity (Cont.) One person can hold zero or more credit cards (0..*) Each card has zero or one holder (0..1) Person 0..1 Holds8 0..* Credit-card card-number: integer name: String Credit-Card Person Holds8 123 456 789 J. Q. Public 35 Holds8 Credit-Card Credit-Card Person 111 222 333 D.Q. Public 32 111 222 333 Software Engineering CSE470: Cheng 129 Multiplicity (Cont.) •One person can hold zero or more credit cards (0..*) •Each card has one holder (no indication or 1) •Each card has one or more authorized users (1..*) •One person can be authorized to use zero or more cards Person name: String 1 Holds8 0..* 3Authorized 1..* Explicit enumeration is also possible (2, 3, 2..5, etc.) Credit-Card Credit-card 3Authorized Person card-number: integer 0..* Holds8 123 456 789 J. Q. Public 35 Holds8 3Authorized Credit-Card 111 222 333 3Authorized Person D. Q. Public 32 Holds8 Credit-Card 3Authorized 111 222 333 Software Engineering CSE470: Cheng 130 Higher order associations Ternary association Project, language, person Seldom needed (and should be avoided) Language 1..* 1..* Project 1..* Person Language Project C++ Compiler Person J. Q. Public 35 Software Engineering CSE470: Cheng Language Project LISP TicTacToe 131 Link Attributes Associations can have properties the same way objects have properties Person name: String age: integer SSN: integer address: String Person name: String age: integer SSN: integer address: String 0..* 0..* Works-for 8 Works-for 8 Company name: String address: String How to represent salary and job title? Company name: String address: String Use a link attribute! salary: integer job-title: String Software Engineering CSE470: Cheng 132 Folding Link Attributes Why not this? Person name: String age: integer SSN: integer address: String salary: integer job-title: String Person name: String age: integer SSN: integer address: String 0..* 0..* Company Works-for 8 Works-for 8 name: String address: String Salary and job title are properties of the job not the person Company 0..* salary: integer job-title: String Software Engineering CSE470: Cheng name: String address: String In this case, a link attribute is the only solution 133 Role Names Attach names to the ends of an association to clarify its meaning Person name: String boss age: integer 0..1 SSN: integer address: String 0..* worker Manages8 Company 0..* Works-for8 employee Software Engineering CSE470: Cheng 0..* employer name: String address: String salary: integer job-title: String 134 Aggregation A special association, the is-part-of association A sentence is part of a paragraph (a paragraph consists of sentences) A paragraph is part of a document (a document consists of paragraphs) Document 0..* Paragraph Aggregation symbol Software Engineering CSE470: Cheng 0..* Sentence 135 Aggregation (Cont.) Often used in parts explosion Car 4 Wheel Body Gearbox 1..* Door Engine 1..* Hood Trunk Software Engineering CSE470: Cheng Piston 0..* Valve Crankshaft 136 Generalization and Inheritance Card The is-a association Cards have many properties in common Generalize the common properties to a separate class, the base-card Let all cards inherit from this class, all cards is-a base-card (plus possibly something more) height: integer width: integer thickness: integer id-number: integer issue() revoke() Drivers License ID Card Credit Card class: vehicle issued: date expires: date issued: date expires: date credit-limit: integer issued: date expire() validate() expire() Software Engineering CSE470: Cheng 137 Example Owns8 City 3Based-In 0..* name Pilot Airline 3Works-for name 3Located-In 0..* 1..* Offers 8 Airport heat() clean() Certified-On 8 3Pilots 0..* name name license 0..* 0..* Departs 8 0..* Arrives 8 0..* 0..* Flight date flight # Used-For 8 Plane model serial # hours flown cancel() delay() heat() refuel() clean() 30..* Passenger name 0..* Seat location Confirmed-for reserve() Aggregation Versus Association Can you use the phrase is-part-of or is-made-of Are operations automatically applied to the parts (for example, move) - aggregation Not clear what it should be…… Company 0..* Division 0..* Department 3Works-for 0..* Person Software Engineering CSE470: Cheng 139 Aggregation Versus Inheritance Do not confuse the is-a relation (inheritance) with the is-part-of relation (aggregation) Use inheritance for special cases of a general concept Use aggregation for parts explosion Minivan 4 Wheel Body Car Gearbox Engine Compact Jeep Roll Bar Software Engineering CSE470: Cheng 140 Recursive Aggregates A recursive aggregate contains (directly or indirectly) an instance of the same kind of aggregate Program 0..* Compound Statement Software Engineering CSE470: Cheng Block Simple Statement 141 Object Modeling Summary Classes Name Attributes Operations Aggregation Inheritance Associations Roles Link attributes Software Engineering CSE470: Cheng 142 Object Modeling Approach Software Engineering CSE470: Cheng 143 Object Modeling Approach Start with a problem statement High-level requirements Define object model Identify objects and classes Prepare data dictionary Identify associations and aggregations Identify attributes of objects and links Organize and simplify using inheritance Iterate and refine the model Group classes into modules Software Engineering CSE470: Cheng 144 The Home Heating System Water Valve Water Pump Home Hot Water Controller Burner 90 Fuel Valve 80 Off 70 On Fuel 60 50 Control Panel Temp Sensor Home Heating Requirements The purpose of the software for the Home Heating System is to control the heating system that heats the rooms of a house. The software shall maintain the temperature of each room within a specified range by controlling the heat flow to individual rooms. The software shall control the heat in each room The room shall be heated when the temperature is 2F below desired temp The room shall no longer be heated when the temperature is 2F above desired temp The flow of heat to each room shall be individually controlled by opening and closing its water valve The valve shall be open when the room needs heat and closed otherwise The user shall set the desired temperature on the thermostat The operator shall be able to turn the heating system on and off The furnace must not run when the system is off Software Engineering CSE470: Cheng When the furnace is not running and a room needs heat, the software shall turn the furnace on To turn the furnace on the software shall follow these steps open the fuel valve turn the burner on The software shall turn the furnace off when heat is no longer needed in any room To turn the furnace off the software shall follow these steps close fuel valve turn burner off 146 Identify Object Classes Requirements Statements Extract Nouns Tentative Object Classes Eliminate Spurious Classes Object Classes Candidate Classes Water Pump Controller operator Hot Water Burner furnace house thermostat Home Heating System room heating system Fuel Valve Water Valve range temperature desired temp Fuel on-off switch Software Engineering CSE470: Cheng heat Home software Temp Sensor Control Panel 147 Eliminate Bad Classes Redundant classes Classes with ill defined boundaries Operations Classes we simply do not care about Vague classes Classes that represent the same thing with different words Irrelevant classes Roles Sequences of actions are often mistaken for classes The name of a class should reflect what it is, not the role it plays Implementation details Save that for implementation Attributes Things that describe individual objects Software Engineering CSE470: Cheng 148 Eliminate Classes Redundant Irrelevant heating system Fuel user software Vague heat Attributes heat flow Hot Water desired temp house temperature home range Operations Roles None Implementation None Fuel Valve None Burner furnace Water Pump Home Heating System room thermostat operator Temp Sensor Controller on-off switch Software Engineering CSE470: Cheng Water Valve Control Panel 149 Classes After Elimination Burner Fuel Valve Home Heating System Water Pump Room Thermostat Water Valve Furnace Temp Sensor Operator on-off switch Control Panel Controller Software Engineering CSE470: Cheng 150 Prepare Data Dictionary Water Tank The storage tank containing the water that circulates in the system. Pump-1 The pump pumping water from the Water Tank to the radiators in the rooms Software Engineering CSE470: Cheng 151 Possible Associations Not much information from the prose requirements A lot of information from the system design Software Engineering CSE470: Cheng A room consists of a thermometer and a radiator A radiator consists of a valve and a radiator element The home heating system consists of a furnace, rooms, a water pump, a control panel, and a controller The furnace consists of a fuel pump and a burner The control panel consists of an on-off switch and a thermostat The controller controls the fuel pump The controller controls the burner The controller controls the water pump The controller monitors the temperature in each room The controller opens and closes the valves in the rooms The operator sets the desired temperature The operator turns the system on and off The controller gets notified of the new desired temperature 152 Object Model Home Heating System Control Panel On-Off Switch 3Pushes Water Pump 3Runs Furnace Burner Thermostat Adjusts 8 Fuel Valve 1..* Room 3Opens/Closes 3Ignites Operator Notifies 8 Water Valve Temp Sensor 3Monitor 3Actuates Controller Object Model - Modified Home Heating System Control Panel Furnace On-Off Switch 3Pushes Burner Thermostat Adjusts8 Fuel Valve 1..* Temp Sensor 3Monitor Water Valve 3Heats Notifies8 1..* Operator 3Runs 3Opens/Closes 3Ignites 1..* Room Water Pump Controller Attributes Thermostat desired-temp On-Off switch setting Software Engineering CSE470: Cheng Temp Sensor temperature 155 Final OO Model Home Heating System Control Panel Furnace On-Off Switch Thermostat setting desired-temp 3 Pushes Adjusts 8 Burner Fuel Valve 1..* Temp Sensor temperature 3Monitor Water Valve 3Heats Notifies8 1..* Operator 3 Runs 3 Opens/Closes 3 Ignites 1..* Room Water Pump Controller Iterate the Model Keep on doing this until you, your customer, and your engineers are happy with the model Iterate Software Engineering CSE470: Cheng 157 Operation vs Method Operation: specifies object behavior Service: represented by set of operns. Message: object requests execution of an opern. from another object by sending it mesg. Method: mesg is matched up with method defined by the class to which the receiving object belongs (or any of its superclasses) Operations of class are public services offered by class. Methods of its classes are the implementations158of Software Engineering CSE470: Cheng these operations. OO Using UML: Dynamic Models Defining how the objects behave Software Engineering CSE470: Cheng 159 Overview The object model describes the structure of the system (objects, attributes, and operations) The dynamic model describes how the objects change state (how the attributes change) and in which order the state changes can take place Several models used to find the appropriate dynamic behavior Interaction diagrams Activity diagrams State Diagrams Uses finite state machines and expresses the changes in terms of events and states Software Engineering CSE470: Cheng 160 Interaction Diagrams Software Engineering CSE470: Cheng 161 We Will Cover Why interaction diagrams? Sequence diagrams Capturing use-cases Dealing with concurrency Collaboration diagrams When to use what When to use interaction diagrams Software Engineering CSE470: Cheng 162 Different Types of Interaction Diagrams An Interaction Diagram typically captures a usecase Sequence diagrams A sequence of user interactions Highlight the sequencing of the interactions between objects Collaboration diagrams Highlight the structure of the components (objects) involved in the interaction Software Engineering CSE470: Cheng 163 Home Heating Use-Case Use case: Actors: Type: Description: Power Up Home Owner (initiator) Primary and essential Cross Ref.: Use-Cases: Requirements XX, YY, and ZZ None The Home Owner turns the power on. Each room is temperature checked. If a room is below the the desired temperature the valve for the room is opened, the water pump started, the fuel valve opened, and the burner ignited. If the temperature in all rooms is above the desired temperature, no actions are taken. Software Engineering CSE470: Cheng 164 Sequence Diagrams a Home Owner the On-Off Switch the Controller a Room System On powerOn() *[for all rooms] tempStatus:=checkTemp() [tempStatus == low] pumpOn() [tempStatus == low] openValve() [tempStatus == low] startBurner() the Water Pump Example from Fowler an Order entry Window an Order an Order Line a Stock Item prepare() *[for all order lines] prepare() hasStock := check() [hasStock] remove() needsReorder := needsToReorder() [needsReorder] new [hasStock] new a Reorder Item a Delivery Item MH Concurrency new a Transaction new a Transaction Coordinator new a first Transaction Checker a second Transaction Checker new ok allDone? ok allValid allDone? Another Example a Home Owner the On-Off Switch System On the Controller the Water Pump powerOn() *[for each room in house] new a Room checkTemp() tempLow [tempLow] pumpOn() [tempLow] openValve() [tempLow] startBurner() MH Comment the Diagram When the owner turns the system on the on switch notifies the controller The controller creates a room object for each room in the building a Home Owner the On-Off Switch System On the Controller the Water Pump powerOn() *[for each room in house] new a Room checkTemp() The rooms sample the temperature in the toom every 5 s. When a low temp is detected the room notifies the controller. tempLow [tempLow] pumpOn() [tempLow] openValve() [tempLow] startBurner() MH Collaboration Diagrams :Order Entry Window 1 : prepare() :Order 5 : needsReorder := needsToReorder() 2 : *[for all order lines]: prepare() 3 : hasStock := check() Winter stock : Stock Item Winter line : Order Line 7 : [hasStock] :new :Delivery Item 4 : [hasStock]: remove() 6 : [needsReorder]: new a Reorder Item MH Conditional Behavior Something you will encounter trying to capture complex use-cases Split the diagram into several Split the use-case also Use the conditional message The user does something. If this something is X do this… If this something is Y do something else… If this something is Z… Could become messy Remember, clarity is the goal! Software Engineering CSE470: Cheng 171 Comparison Both diagrams capture the same information We prefer sequence diagrams People just have different preferences They clearly highlight the order of things Invaluable when reasoning about multi-tasking Others like collaboration diagrams Shows the static structure Very useful when organizing classes into packages We get the structure from the Class Diagrams Software Engineering CSE470: Cheng 172 When to Use Interaction Diagrams When you want to clarify and explore single usecases involving several objects Quickly becomes unruly if you do not watch it If you are interested in one object over many usecases -- state transition diagrams If you are interested in many objects over many use cases -- activity diagrams Software Engineering CSE470: Cheng 173 State Diagrams Software Engineering CSE470: Cheng 174 We Will Cover State Machines An alternate way of capturing scenarios Large classes of scenarios Syntax and Semantics When to use state machines Software Engineering CSE470: Cheng 175 Events, Conditions, and States Event: something that happens at a point in time Condition: something that has a duration Operator presses self-test button The alarm goes off The fuel level is high The alarm is on State : an abstraction of the attributes and links of an object (or entire system) The controller is in the state self-test after the self-test button has been pressed and the rest-button has not yet been pressed The tank is in the state too-low when the fuel level has been below level-low for alarm-threshold seconds Software Engineering CSE470: Cheng 176 Making a Phone Call Scenario To make a call, the caller lifts receiver. The caller gets a dial dial tone and the caller dials digit (x). The dial tone ends. The caller completes dialing the number. The callee phone begins ringing at the same time a ringing begins in caller phone. When the callee answers the called phone stops ringing and ringing ends in caller phone. The phones are now connected. The caller hangs up and the phones are disconnected. The callee hangs up. Software Engineering CSE470: Cheng 177 Partial Class Diagram 1..1 Line 1..1 Caller Phone 1..1 1..1 Software Engineering CSE470: Cheng Callee 178 Event Trace Caller Line Callee caller lifts receiver dial tone begins dials digit (4) dial tone ends dials digit (2) dials digit (3) dials digit (4) dials digit (5) ringing tone phone rings tone stops callee answers ringing stops phones connected phones connected phones disconnected caller hangs up phones disconnected callee hangs up State Diagram for Scenario on-hook Idle off-hook Dial tone digit(x) digit(x) Dialing valid-number Ringing called-phone-answers Connected called-phone-hangs-up Disconnected Scenario 2 Caller Line caller lifts receiver dial tone begins dials digit (4) dial tone ends dials digit (2) dials digit (3) dials digit (4) dials digit (5) busy tone caller hangs up Callee Modified State Machine on-hook Idle off-hook digit(x) Dial tone digit(x) Busy tone Dialing valid-number number-busy routed Connecting Ringing called-phone-answers Connected called-phone-hangs-up Disconnected Conditions Sometimes the state transitions are conditional Idle on-hook off-hook Dial tone digit(x) [x = 8] digit(x) digit(x) Dialing digit(x) [x != 8] Dial tone (external) Dialing valid-number Busy tone valid-number number-busy routed Software Engineering CSE470: Cheng digit(x) Ringing Connecting 183 Operations (AKA Actions) Idle Actions are performed when a transition is taken or performed while in a state Actions are terminated when leaving the state off-hook on-hook Dial tone digit(x) do/ sound dial tone on-hook on-hook Busy tone digit(x) number-busy do/ busy tone Dialing valid-number Connecting on-hook routed do/ find connection on-hook Ringing do/ ring bell called-phone-answers / connect line on-hook / disconnect line Connected called-phone-hangs-up / disconnect line on-hook Software Engineering CSE470: Cheng Disconnected 184 Hierarchical State Machines on-hook Idle Dial tone off-hook do/ sound dial tone dial(x) [x is a digit] Group states with similar characteristics Enables information hiding Simplifies the diagrams dial(x) [x = *] Make Call Establish call Dialing dial(x) valid-number number-busy on-hook Busy tone Connecting do/ find connection do/ busy tone routed Ringing do/ ring bell on-hook / disconnect line on-hook Connected called-phone-answers / connect line called-phone-hangs-up / disconnect line Disconnected Voice Mail Information Hiding on-hook Idle off-hook Establish call Dial tone Dialing do/ sound dial tone dial(x) [x is a digit] dial(x) [x = *] valid-number number-busy Make Call Busy tone Establish call Voice Mail on-hook dial(x) do/ busy tone Connecting do/ find connection routed Ringing on-hook / disconnect line on-hook Connected called-phone-answers / connect line do/ ring bell called-phone-hangs-up / disconnect line Disconnected Software Engineering CSE470: Cheng 186 Event Generalization Related events can inherit properties from each other If an event at a lower level occurs - the event at a higher level also occurred Event attributes mouse-up.location mouse-down.device mouse-button.time event time user-input device mouse-button location mouse-down Software Engineering CSE470: Cheng keyboard-key character mouse-up 187 Concurrency Some states represent several concurrent concepts Concurrency is supported by the state machines Concurrent state machines are separated by dashed lines Alarms Disabled out-of-bounds-event Alarms Enabled Visual Alarm reset On Off visual-on Aural Alarm reset On Off aural-on Software Engineering CSE470: Cheng 188 State Machines - Summary Events conditions over time abstraction of the attributes and associations something performed in a state Hierarchies Transitions Internal actions States Conditions instances in time allows abstraction and information hiding Parallelism models concurrent concepts Takes the state machine from one state to the next Triggered by events Guarded by conditions Cause actions to happen Software Engineering CSE470: Cheng 189 When to use State Machines When you want to describe the behavior of one object for all (or at least many) scenarios that affect that object Not good at showing the interaction between objects Use interaction diagrams or activity diagrams Do not use them for all classes Some methods prescribe this Very time consuming and questionable benefit Software Engineering CSE470: Cheng 190 Coming up with the State Diagrams Software Engineering CSE470: Cheng 191 Modeling Approach Prepare scenarios Identify events (often messages) Group into event classes Draw some sequence diagrams Work with the customer Start with normal scenarios Add abnormal scenarios Find objects with complex functionality you want to understand better Build a state diagram for the complex classes Software Engineering CSE470: Cheng 192 Scenario-1 Room Controller Fuel Valve Burner request-temp Every 5s respond-temp open-valve Temp Low start-burner pump-on open-water-valve request-temp Every 5s respond-temp pump-off Temp Normal close-water-valve stop-burner close-valve Water Pump Scenario-2 Control Panel Room Controller Fuel Valve Burner request-temp Every 5s Desired temp change Every 5s respond-temp desired-temp-change request-temp respond-temp open-valve start-burner Temp Low pump-on open-water-valve request-temp Every 5s respond-temp pump-off Temp Normal close-water-valve stop-burner close-valve Water Pump Dynamic Model Water Pump pump-on On Off pump-off Fuel Valve open-valve Open Closed close-valve Burner start-burner On Off stop-burner Software Engineering CSE470: Cheng 195 More Dynamic Model Room Water-Valve Temp-Sensor open-water-valve/ wv-open Idle Valve request-temp close-water-valve/ wv-close Software Engineering CSE470: Cheng temp-report(x)/ respond-temp(x) Processing Request 196 Even More Dynamic Model Controller Temperature timeout(5s)\ request-temp respond-temp(x)[x>desired-temp+2]/stop-heating Temp-Low Temp-Normal timeout(5s)\ request-temp respond-temp(x)[x<desired-temp-2]/start-heating Home Heating System timeout(1s)/ pump-on,open-water-valve timeout(1s)/start-burner Burner-On Fuel-Open All-Running stop-heating/ pump-off,close-water-valve start-heating/open-valve All-Off Water-Off Fuel-Off timeout(1s)/close-valve timeout(1s)/stop-burner Software Engineering CSE470: Cheng 197 Identify Key Operations Operations from the object model Accessing and setting attributes and associations (often not shown) Operations from actions and activities Operations from events All events represent some operation Operations from functions Each function typically represent one or more operations Shopping list operations Software Engineering CSE470: Cheng Actions and activities represent some processing activity within some object Inherent operations (what should be there) 198 Complete OO Model Home Heating System Control Panel Water Pump 3Runs Furnace operating() target-temp() on() off() On-Off Switch Thermostat setting desired-temp Burner Fuel Valve on() off() open() close() 1..* Room 3Pushes Adjusts 8 3Ignites Water Valve Temp Sensor temperature Software Engineering CSE470: Cheng 3Opens/Closes 3Monitor 1..* 3Heats Notifies 8 Operator open-valve() close-valve() 1..* room-temp() Controller 199 Iterate the Model Keep on doing this until you, your customer, and your engineers are happy with the model Iterate Software Engineering CSE470: Cheng 200 Activity Diagrams Software Engineering CSE470: Cheng 201 We Will Cover History of activity diagrams in UML A highly personal perspective Activity diagrams Swimlanes When to use activity diagrams When not to Software Engineering CSE470: Cheng 202 Activity Diagrams Shows how activities are connected together Mechanisms to express Shows the order of processing Captures parallelism Processing Synchronization Conditional selection of processing A glorified flowchart Software Engineering CSE470: Cheng 203 Why Activity Diagrams Very good question Suitable for modeling of business activities Not part of any previous (UML related) method Introduced to sell products UML and OO is becoming more prevalent in business applications Object frameworks are making an inroad Stay within one development approach and notation Generally a flowchart and I do not really see the need in OO modeling Probably because I do not do business systems Software Engineering CSE470: Cheng 204 Coffee Example Find Beverage [no coffee] Decision [no coke] [found coffee] [found coke] Put Coffee in Filter Add Water to Reservoir Get Cups Get Can of Coke Put Filter in Machine Turn On Machine ^coffePot.TurnOn Brew Coffee Drink Beverage Pour Coffee MH HACS Use-Cases Use case: Actors: Type: Description: Distribute Assignments Instructor (initiator), Student Primary and essential The Instructor completes an assignment and submits it to the system. The instructor will also submit the delivery date, due date, and the class the assignment is assigned for. The system will at the due date mail the assignment to the student. Cross Ref.: Requirements XX, YY, and ZZ 206 Software Engineering CSE470: Cheng Use-Cases: Configure HACS must be done before any user Activity Diagrams for Use Cases Write Assignment [submission time] Write Solution Submit Assignment Mail Assignment Submit Solved Assignment Submit Solution Mail Solution Grade Assignment Solve Assignment Review Solution Hit the Pub Swimlanes (Who Does What?) Instructor HACS Student Write Assignment [submission time] Write Solution Submit Assignment Mail Assignment Submit Solved Assignment Submit Solution Mail Solution Grade Assignment Software Engineering CSE470: Cheng Solve Assignment Review Solution Hit the Pub 208 Problems with Activity Diagrams They are glorified flowcharts Switching to the OO paradigm is hard enough as it is Very easy to make a traditional data-flow oriented design Extensive use of activity charts can make this shift even harder However... Very powerful when you know how to use them correctly Software Engineering CSE470: Cheng 209 When to Use Activity Diagrams Not clear how useful in OO modeling Particularly when modeling control systems Useful when Analyzing a use case (or collection of use cases) Understanding workflow in an organization Working with multi-threaded applications For instance, process control applications Do not use activity diagrams To figure out how objects collaborate See how objects behave over time Software Engineering CSE470: Cheng 210 Approaching a Problem Where do we start? How do we proceed? Software Engineering CSE470: Cheng 211 Where Do We Start? Start with the requirements Use-case analysis to better understand your requirements Capture your goals and possible constraints Environmental assumptions Find actors and a first round of use-cases Start conceptual modeling Conceptual class diagram Interaction diagrams to clarify use-cases Activity diagrams to understand major processing Software Engineering CSE470: Cheng 212 How Do We Continue? Refine use-cases Possibly some “real” use-cases Refine (or restructure) your class diagram Based on your hardware architecture For instance, client server Refine and expand your dynamic model Using interface mockups Until you are comfortable that you understand the required behavior Identify most operations and attributes Software Engineering CSE470: Cheng 213 How Do We Wrap Up? Refine the class diagram based on platform and language properties Identify all operations Navigability, public, private, etc Class libraries Not the trivial get, set, etc. Write a contract for each operation Define a collection of invariants for each class Implement Software Engineering CSE470: Cheng 214 Process Overview Transition Inception Elaboration Software Engineering CSE470: Cheng Construction n Many iterations Construction 3 Construction 2 Inception Elaboration Construction Construction 1 Transition 215 Requirements Analysis Defining the WHAT Software Engineering CSE470: Cheng 216 Requirements Specify functionality model objects and resources model behavior Specify data interfaces type, quantity, frequency, reliability providers, receivers operational profile (expected scenarios) stress profile (worst case scenarios) Software Engineering CSE470: Cheng 217 Requirements Specify interfaces Control interfaces (APIs) User interfaces - functionality and style Hardware interfaces Specify error handling Identify potential modifications Software Engineering CSE470: Cheng 218 Requirements Identify necessary constraints performance, security, reliability Identify areas of risk alternatives to be explored Specify validation plans Specify documentation to be provided Software Engineering CSE470: Cheng 219 Analysis Principles Document reason for specific requirements Prioritize requirements High, medium, low Ignore implementation details Need to know feasible solutions can be developed If feasibility is a concern, then propose alternatives to be explored Be prepared to change Software Engineering CSE470: Cheng 220 Reviewing a requirements document Is it ambiguous? Is it consistent? Is it complete? Carefully define terms and use these terms Vague requirements Omitted requirements Is it verifiable? Is it realistic? Does it plan for change? Software Engineering CSE470: Cheng Does it not overly constrain the problem? Have alternatives been considered and explored? Is it clearly presented? Precise, concise, clear diagram complex objects and behaviors Is it what the customer wants? 221 Why is requirements analysis difficult? Communication: misunderstandings between the customer and the analyst Analyst doesn’t understand the domain Customer doesn’t understand alternatives and trade-offs Problem complexity Inconsistencies in problem statement Omissions/incompleteness in problem statement Inappropriate detail in problem statement Software Engineering CSE470: Cheng 222 Why is requirements analysis difficult? Need to accommodate change Hard to predict change Hard to plan for change Hard to forsee the impact of change Software Engineering CSE470: Cheng 223 First Law of Software Engineering “No matter where you are in the system lifecycle, the system will change, and the desire to change it will persist throughout the lifecycle.” Software Engineering CSE470: Cheng 224 Reasons for changing requirements Poor communication Inaccurate requirements analysis Failure to consider alternatives New users New customer goals New customer environment New technology Competition Software is seen as malleable Changes made after the requirements are approved increase cost and schedule Software Engineering CSE470: Cheng 225 Requirements Products Specification document Agreement between customer and developer Validation criteria for software Preliminary users manual Prototype If user interaction is important If resources are available Review by customer and developer Iteration is almost always required Software Engineering CSE470: Cheng 226 Analysis: Steps to follow Obtain a problem statement Develop use cases (depict scenarios of use) Build an object model and data dictionary Develop a dynamic model state and sequence diagrams Verify, iterate, and refine the models Produce analysis document Software Engineering CSE470: Cheng 227 Use Cases High-level overview of system use Identify scenarios of usage Identify actors of the system: External entities (e.g., users, systems, etc.) Identify system activities Draw connections between actors and activities Identify dependencies between activities (i.e., extends, uses) Software Engineering CSE470: Cheng 228 Analysis: Object Model Organization of system into classes connected by associations Shows the static structure Organizes and decomposes system into more manageable subsystems Describes real world classes and relationships Software Engineering CSE470: Cheng 229 Analysis: Object Model Object model precedes the dynamic model because static structure is usually better defined less dependent on details more stable as the system evolves Software Engineering CSE470: Cheng 230 Analysis: Object Model Information comes from The problem statement and use cases Expert knowledge of the application domain Interviews with customer Consultation with experts Outside research performed by analyst General knowledge of the real world Software Engineering CSE470: Cheng 231 Object Model: Steps to follow Identify classes and associations nouns and verbs in a problem description Create data dictionary entry for each Add attributes Combine and organize classes using inheritance Software Engineering CSE470: Cheng 232 Analysis: Dynamic model Shows the time dependent behavior of the system and the objects in it Expressed in terms of states of objects and activities in states events and actions State diagram summarizes permissible event sequences for objects with important dynamic behavior Software Engineering CSE470: Cheng 233 Dynamic Model: Steps to follow Use cases provide scenarios of typical interaction sequences Identify events between objects (Sequence Diagram) Prepare an event trace for each scenario Build state diagrams Match events between objects to verify consistency Software Engineering CSE470: Cheng 234 Analysis: Iteration Analysis model will require multiple passes to complete Look for inconsistencies and revise Look for omissions/vagueness and revise Validate the final model with the customer Software Engineering CSE470: Cheng 235 Object Model: Four main system objects or classes Controller object might be made up of several controllers is the brains of the system. Takes input from the sensors and gives instructions to the actuators. Sensor object environmental objects that gives information to controller. Can be passive (thermometer) or active (button). Software Engineering CSE470: Cheng 236 Embedded Systems Details Software Engineering CSE470: Cheng 237 Object Model: Four main system objects (continued) Actuator object Environmental objects that are controlled by the controller. Can be turned on or influenced by controller. Examples: User indicator lights, motors, burners. User Interface object A display for the user. Can be made up of both sensors and actuators. Example: machine control panel Software Engineering CSE470: Cheng 238 Step One: Develop a high-level object model Embedded System * * Controller Sensor Button Actuator * User-Interface Pedal Inheritance Class * Association Software Engineering CSE470: Cheng Class Name Zero or more Attribute() Aggregation Operation() 239 Review of Dynamic Model A dynamic model is a type of state machine. System can only be in one state at a time. Arrows: Transitions from one state to another happen when events happen. Events are labeled on the transitions. Guards are conditions that keep a transition from happen, such as [is in neutral or park ] Software Engineering CSE470: Cheng 240 Step Two: Develop a systemlevel dynamic model ‘On’ button pushed [in neutral or park] Idle or off state State Running state ‘Off’ button pushed Transition [ condition ] Guard Software Engineering CSE470: Cheng 241 Example: Automotive Door Control The system controls the windows and door locking functions. All doors have window roll up and down controls. Driver’s door has window lock feature. Driver and front passenger have door lock and unlock toggle. Fob unit for locking and unlocking doors, with driver notification (horn honk and lights flash.) Three concurrent systems identified. Software Engineering CSE470: Cheng 242 Software Engineering CSE470: Cheng 243 Software Engineering CSE470: Cheng 244 Software Engineering CSE470: Cheng 245 Software Engineering CSE470: Cheng 246 Software Engineering CSE470: Cheng 247 Summary of development process The object model shows the real world objects grouped in classes with attributes and operations and associations. The dynamic model shows the control aspects with superstates refined into substates. Software Engineering CSE470: Cheng 250 Review of Embedded Systems Software controller that is interacting with its hardware environment through sensors and actuators. Concurrency and real time issues. Safety critical nature of many of these systems. Increased demand for these systems to be designed well. Software Engineering CSE470: Cheng 251 High level design: Initial thoughts for embedded systems. Assume there is a hardware environment. Assume that somehow the needed signals are coming from the environment (sensors.) Assume the needed hardware is there to respond to your signals (actuators.) Software Engineering CSE470: Cheng 252 Object Model Class attribute operation In UML the object model is the starting place for the modeling process. The object model will include objects and their relationships. The Object Model will be the static, structural aspect of the system. Software Engineering CSE470: Cheng 253 Identify Real World Objects Read over the problem description and find the nouns in the text. These nouns are candidates for objects in your object model. Discard unnecessary and incorrect classes. Object classes will include the controller (software unit that will be built), sensors, and actuators. Software Engineering CSE470: Cheng 254 Data Dictionary: needs to be written A written paragraph describing each modeling entity. Needed so that names are non-ambiguous. Software Engineering CSE470: Cheng 255 Class: Sensor Because of the common properties of all sensors, this can be a class of objects, called a superclass. Generalization - this superclass can be generalized into subclasses. Inheritance - each subclass will inherit the properties or features from the superclass. Examples: user interface (buttons etc), thermometers, hardware sensors. Software Engineering CSE470: Cheng 256 Class: Actuator Similarly the actuators will probably become a superclass. Generalization - The various actuators can be generalized into subclasses. Inheritance - each actuator subclass will inherit properties or features from the superclass. Examples: LEDs, motor controls, etc. Software Engineering CSE470: Cheng 257 The Controller At an abstract level, this would be only one object in most embedded systems. This object would be refined at lower levels of the modeling process into subsystems or sub-objects. Aggregation could be used to show the parts of the controller. Software Engineering CSE470: Cheng 258 Model itself Class attribute operation Graphically a class is shown as a box with the name on top. Attributes (middle third) and operations (bottom third) added eventually. Attributes and operations are not needed for highlevel object model. Software Engineering CSE470: Cheng 259 Find the Associations Interaction between objects must be shown by associations or lines draw with labels. ex: line between user button and associated LED. Many times these associations will be a physical connection between objects in an embedded system. Multiplicity must be shown eventually. Software Engineering CSE470: Cheng 260 Example turned on by Actuators LED Controller * reads * Motor Software Engineering CSE470: Cheng User buttons Sensors Water level 261 Conclusion about Object Model: Not very complex at first. More details will come as designer proceeds from abstraction to more and more concreteness. controller will be divided into more objects attributes and operations are identified and included. Starting place for OO Modeling. Sets the stage. Software Engineering CSE470: Cheng 262 Next step: Dynamic Model The dynamic model shows the control aspect of the system. Because embedded systems are mainly controllers, the dynamic model is the ‘key’ model for embedded systems. This model can show the timing aspects. Shows sequence of operations in response to external stimuli. Software Engineering CSE470: Cheng 263 Getting started on a Dynamic Model Helpful to make a scenario: sequence of events that happens in one execution of a system. Example: insert coins, make selection, pop dispensed. Interface (high-level prototyping) a rough draft of user interface will help thinking about the events in an embedded system. Software Engineering CSE470: Cheng 264 Interface (type of rapid prototyping) 0 1 2 3 4 5 6 7 8 8 enter receipts clear cancel cash slot ATM interface from Figure 8.17 by Rumbaugh Software Engineering CSE470: Cheng 265 continue getting started…. Next make an event trace. each object is a vertical line. events as horizontal arrow. time goes from top to bottom. Use previously discussed ‘creation tips.’ Software Engineering CSE470: Cheng 266 Example of an Event Trace User ATM Consortium Bank insert card request password enter password verify account account OK verify card with bank bank account OK request kind enter kind request amount enter amount process transaction process bank transactions bank transaction succeeds Event trace for ATM scenario Example from Figure 8.18 of Rumbaugh More Dynamic Modeling Software Engineering CSE470: Cheng 268 Dynamic Model - State Diagram Graphical representation of a finite state machine. Each ‘state’ represents all the values of the objects in the system. Changing states - transitioning on events. Events - external stimuli ex. button pushed; timer complete; tub full. Software Engineering CSE470: Cheng 269 Review of getting started: Scenario making: gets us started thinking about events. Interface (high-level prototyping): helps us to think about order of things. (happening in projects) Event trace: helps to know what object is doing what action. State Diagram creation tips. Software Engineering CSE470: Cheng 270 Dynamic Models for E.S. Dynamic Model for user buttons would be simplistic; button pushed on off modeling might not be needed. button Some environmental units might have behavior that pushed should be modeled. (like an engine shifting through speeds) For embedded systems - might only need one significant behavior model (for controller.) Complex models will be decomposed into more detailed behavioral models. Concurrency could be present within a model. Software Engineering CSE470: Cheng 271 How dynamic model relates to object model One state diagram for each class (with important behavior.) Each class has concurrent behavior. Aggregation in the Object Model implies concurrency in the Dynamic Model. Software Engineering CSE470: Cheng 272 Examples of Aggregation (5.17) Object model Car Ignition Transmission Brake Accelerator Each class will need a concurrent state diagram Software Engineering CSE470: Cheng 273 How to model concurrency within an object Car Ignition Off turn key to start [Transmission in Neutral] release key Starting On turn key off Transmission push R Neutral push N Reverse push N Forward stop upshift First push F upshift Second downshif t Third downshift Accelerator Brake depress accelerator Off release accelerator On depress brake Off On release brake How to hide complexity Not have a ‘flat’ state diagram Start abstract and then do subdiagrams. use bull’s eye Take one abstract state and expand it with state generalization. Software Engineering CSE470: Cheng 275 Example of nesting (and other syntax as well) coins in(amount) / set balance Collecting money Idle coins in(amount) / add to balance cancel / refund coins [item empty] select(item) [change<0] do: test item and compute change [change=0] do: dispense item do: move arm to correct row do: move arm to correct column [change>0] do: make change do: push item off shelf Example: lower-level state diagram for Dispense item activity Software Engineering CSE470: Cheng 276 State Generalization push R push N Reverse Neutral push F push N ex. level 0 Dynamic Model for a transmission. Forward Transmission push R push N Reverse Neutral push N Forward stop upshift First push F upshift Second downshif t Third downshift ex. level 1 Dynamic Model for a transmission. Software Engineering CSE470: Cheng 277 Notation on Transitions and in States do: activity do: activity 1 event1 (attribs) [condition1]/ action1 State2 Guards takes some time. associated with a state. State1 conditions - boolean [ guard ] Actions : You might need any or all of these for your project! instantaneous associated with an event. /action Software Engineering CSE470: Cheng 278 Checking for completeness and consistency Formal specifications do this better! Every state should have a way in and out. The mathematical format can allow automation of these types of checks. unless starting point or ending point. Look for one object’s Dynamic Model sending an event that doesn’t have any receiving transition in another object’s DM. Software Engineering CSE470: Cheng 279 Things to watch out for Think about input from concurrent objects at unexpected times. ex. If more than one ATM machine is trying to access the same account at the same time. User input when not planned. (OK to ignore, but make sure that is what is really wanted.) Take your scenarios and see if they work! Walk through seeing that all the object’s operations/messages has all the needed transitions. Software Engineering CSE470: Cheng 280 Topics Covered: Dynamic Model Synchronization schemes Exception Handling Timing including safety critical issues. Software Engineering CSE470: Cheng 281 Synchronization In concurrent processing, the actions of the objects are rarely independent of each other. One may need to stop and wait for another process to ‘catch up’ or get to a certain state. Example: In a nuclear power plant, the model would need to reflect waiting for rods to be in place before generating power. Software Engineering CSE470: Cheng 282 Synchronization of States by status detection B A A1 B1 event A2 [A is in state A2] B2 Transition between B1 and B2 will not fire until object A has entered state A2. Software Engineering CSE470: Cheng 283 Synchronization of States by a common event A B StateA1 StateB1 event1 StateA2 event1 StateB2 Firing of the two transitions in the two models will happen at the same time. Software Engineering CSE470: Cheng 284 Synchronization of States by common data A B StateA1 do: x:=0 event StateA2 do: x:= 1 StateB1 [x=1] StateB2 Transition from StateB1 to StateB2 will not fire until StateA2 has been done. (This assumes shared memory.) Software Engineering CSE470: Cheng 285 Exception Handling Events such as resets and hardware interrupts must be handled. These are called Exceptions. Crucial to terminate the behavior of an object. Needed if user can exit a sequence of states at anytime. Software Engineering CSE470: Cheng 286 Examples of exception handling Possible to modeling exiting all the substates of a superstate in UML. Ex. Pushing the N (neutral button) in any of the forward states of a transmission. 2 ways to exit: normal completion and exception. event1 Superstate substate1 substate2 normal exiting by completion exception event Software Engineering CSE470: Cheng 287 Timing Issues in Dynamic Model Sometimes the firing of a transition is time dependent, especially in embedded systems. Real-time systems might have transitions that are tied to a real-time clock. States might time-out after a certain length of time. Transitions might need to be stalled for a certain length of time. Software Engineering CSE470: Cheng 288 Timing (Safety critical) Safety critical real-time solutions example: transition out of ‘boiler on’ state after being in this state for 1 hour, even if one expects a transition on temperature>=expected. Boiler temperature >= expected On Off in ‘boiler on’ state >= 1 hour (Event on transition could just be labeled ‘1 hour’) Delays in Dynamic Model Sometimes a transition should not be fired for a certain amount of time. This timing constraint can be modeled as a guard on transition ex. [10 seconds since the exit from state A] This will delay the firing of the transition for 10 seconds. Software Engineering CSE470: Cheng 290 More Timing Issues in D. M. For a real-time system, the guard might refer to a real-time clock example: changing a traffic signal from day operation to night operation at 10 p.m. because there is no event on transition: ready to fire when the guard is true. Day superstate [time = 2200 hours] Night superstate [time = 0600 hours] Software Engineering CSE470: Cheng 291 Quality Assurance Software Engineering CSE470: Cheng 292 Software Qualities Maintainer Good Documentation Readable Code Good Design Functionality Ease of use Ease of learning Reliability Correctness Efficiency Low Cost Portability Increased productivity Customer User Software Engineering CSE470: Cheng 293 Software Quality Assurance Use of analysis to validate artifacts requirements, designs, code, test plans Technical reviews Document reviews Compliance to standards Control of changes Software Engineering CSE470: Cheng 294 Costs of Poor Quality Increased time to find and fix problems Increased cost to distribute modifications Increased customer support Product liability Failure in the market place Software Engineering CSE470: Cheng 295 QA Terminology Correctness Reliability Testing Debugging Failure Software Engineering CSE470: Cheng Fault Error Verification Validation V&V 296 Terminology Correctness: artifact is consistent with its specification Specification could be wrong or incomplete Rarely is software known to be correct Rarely is the specification correct Reliability: probability that the software is correct Statistical measure based on past performance e.g., mean time to failure Software Engineering CSE470: Cheng 297 More terminology Testing: entails executing the software on selected test cases Evaluate the results (oracle) Evaluate the performance Evaluate the ease of use Common Wisdom: Testing reveals bugs but does not guarantee the absence of bugs How should you select test cases? How do you know when to stop testing? Software Engineering CSE470: Cheng 298 More terminology Failure: an erroneous result incorrect outputs/response for given inputs/stimuli fails to meet real-time constraints Error: incorrect concept may cause failures if not corrected Fault: the cause of one or more failures discovered after release Software Engineering CSE470: Cheng 299 More terminology Debugging: the process of finding the cause of a “bug” and a way to fix it w/o introducing additional bugs! Verification: process of proving, using mathematical reasoning, that a program is “correct” is expensive and is not always possible is not foolproof Software Engineering CSE470: Cheng 300 More terminology Validation: process associated with showing that the software performs reasonably well V & V: verification & validation? more typically equated with validation Software Engineering CSE470: Cheng 301 Many different kinds of testing Unit testing: test individual components test stubs simulate called components test harness simulates “outer” context and maintains stubs Integration testing: combine components and test them follows build plan System testing: test whole system Software Engineering CSE470: Cheng 302 More kinds of testing Acceptance testing: testing to determine if the product is acceptable Regression testing: retesting after the system has been modified determine “old” test cases that must be re-executed determine what new test cases are required Software Engineering CSE470: Cheng 303 More kinds of testing Black box / functional testing: White box / structural testing: testing based on specifications testing based on looking at the artifact Both black box and white box testing are needed Software Engineering CSE470: Cheng 304 Testing is hard work Typically 50% of software development effort goes into testing How to identify “good” test cases? up to 85% for life-critical software high probability of finding a new error Objective is to find errors test case is “successful” if it finds a new error Software Engineering CSE470: Cheng 305 Testing is hard work (cont.) Psychologically difficult for a programmer to test his/her own code thoroughly Exhaustive testing requires testing all combinations of input values Sorting an array of size 10 containing integers in the range 1 . . 10 has 10! combinations (3,628,800 cases) Software Engineering CSE470: Cheng 306 Testing CAN: Uncover errors Show specifications are met for specific test cases Be an indication of overall reliability CANNOT: Prove that a program is error-free Software Engineering CSE470: Cheng 307 Testing Principles Tests should be traceable to requirements Tests should be planned long before testing begins Exhaustive testing is not possible 80% of all errors typically occur in 20% of the modules test cases should be chosen to maximize likelihood of finding an error Software Engineering CSE470: Cheng 308 Testing Principles (cont.) Testing should be done by someone other than the developers Developers do original testing SQA does independent testing usually black box testing Automated testing tools should be used Reduce testing costs Reduce likelihood of human error Software Engineering CSE470: Cheng 309 Testability Simple software is easier to test Output is sufficient to determine correct behavior Performs its own tests for internal errors minimize coupling, maximize cohesion raises meaningful exceptions All code is reachable Independent modules can be tested in isolation Documentation is complete and accurate Software Engineering CSE470: Cheng 310 Quality is an on-going concern You can’t build quality into a system after the fact Quality should be a consideration during every phase of development Plan for testing / validation in all phases requirements -> functional test cases design -> functional and structural test cases code -> enhanced func & struc test cases maintenance -> further enhanced func & struc test cases Software Engineering CSE470: Cheng 311 Debugging Find the cause of a failure and fix it Debugging is difficult because an art, not a science symptom may appear long after the fault occurs symptom may be difficult to reproduce symptom may be intermittent Unit testing helps localize errors Software Engineering CSE470: Cheng 312 Software Reviews Individuals read and comment on the software artifacts Very human intensive Overriding evidence shows that it improves quality and productivity reduces cost It is usually one of the first activities to be dropped when schedules get tight Software Engineering CSE470: Cheng 313 Software Reviews (cont.) Applicable to all software artifacts code inspections requirements and design reviews walk-throughs Recent research shows that particular kind of review, size of team, etc. doesn’t matter need at least one good, dedicated person doing the review Software Engineering CSE470: Cheng 314 Typical Review Team Developer -- presents the material Moderator -- keeps the review on track makes sure everyone abides by the process Secretary -- takes minutes, documents problems found Optionally Apprentice -- learning about the project Domain expert -- familiar with the domain and can verify assumptions Software Engineering CSE470: Cheng 315 Software Review Guidelines Review the artifact don’t attack the developer Stick to an agenda Limit debate Identify problems, not solutions Keep accurate notes Establish and follow evaluation guidelines Limit number of participants Software Engineering CSE470: Cheng 316 Technical Review Guidelines (cont.) Prepare beforehand Allocate resources for reviews both developers and reviewers people and time Possible outcomes accept product as is reject product outright accept product provisionally Software Engineering CSE470: Cheng 317 Sample evaluation Guidelines: Inspection Code Has the design been correctly translated to code? Are the language features used appropriately? Are coding standards followed? Are documentation standards followed? Are there misspellings or typos? Are the comments accurate and unambiguous? Software Engineering CSE470: Cheng 318 Sample evaluation Guidelines: Inspection (cont.) Code Are data types and declarations appropriate? Are all constants correct? Are all variables initialized before being used? Are there overly complex conditions? Is there unreachable code? Are there obvious inefficiencies? Software Engineering CSE470: Cheng 319 SQA Summary U.S. software costs $200 billion/year Need to improve software quality reduce costs V&V is over 50% of the cost Improving V&V should reduce costs significantly while improving quality Software Engineering CSE470: Cheng 320 Overview of Formal Methods Software Engineering CSE470: Cheng 321 Topics Introduction and terminology FM and Software Engineering Applications of FM Propositional and Predicate Logic Program derivation Intuitive program verification Algebraic Specifications Overview of Specification languages Software Engineering CSE470: Cheng 322 Terminology Methods: general guidelines governing an activity rigorous, systematic, and may be formal Techniques: are technical, mechanical, approaches may have restricted applicability Methodologies:combine methods. techniques Tools: can be built to support methodology Software Engineering CSE470: Cheng 323 Components of a Formal Method Formal systems. Development technique. formal languages with well-defined syntax well-defined semantics proof systems implementation produced from specification application of development steps refinement process Verification technique. verify implementation satisfies specification verify each development step Software Engineering CSE470: Cheng 324 Formal vs. Rigorous Formal based on mathematics (including logic) validity of statements can be mechanically checked Rigorous strictly follows the rules compliance can be audited Software Engineering CSE470: Cheng 325 Important characteristics of FM Abstraction Proof obligations Tool support Systematic process Software Engineering CSE470: Cheng 326 FM does not replace testing! Reduces burden on testing phases to detect all critical errors Facilitates more effective allocation of testing resources Can guide the selection of test cases Software Engineering CSE470: Cheng 327 Why Use Formal Methods Improve quality of software system Fitness for purpose Maintainability Ease of construction Higher confidence in software product Reveal ambiguity, incompleteness, and inconsistency in system Detect design flaws Determine correctness Software Engineering CSE470: Cheng 328 V&V and Traceability The Real World Validation Formal Specification Verification Code Software Engineering CSE470: Cheng 329 V&V and Traceability The Real World Validation Formal Specification Verification Traceability Code Software Engineering CSE470: Cheng 330 Traditional verification techniques not successful. Why not? Too much like math? (proofs, ugh!) Notation too hard to use Notation too hard to write out "Simple" things take a lot of effort "Complex" things seem impossible Program verification is an undecidable problem "If it works, why mess with it?" Software Engineering CSE470: Cheng 331 Potential solutions?: Need experimental evidence on large projects. Construction of support tools Early education!?!? Integration of formal methods in more than one phase of software engineering Improved (automated) theorem proving strategies Handle more than just functional properties MOST IMPORTANTLY: do not verify "after the fact" Software Engineering CSE470: Cheng 332 When and Where? Introduce FM into existing systems Verify critical properties Facilitate maintenance and reimplementation Introduce FM into new systems Capture requirements precisely Reduce ambiguity Guide software development process Basis for testing Formalize requirements analysis and design Software Engineering CSE470: Cheng 333 Rushby’s “Levels of Rigor” Level 0: No use of formal methods. Level 1: Use of concepts and notation from discrete mathematics. cleanroom, SCR (software cost reduction) Level 2: Use of formalized specification languages with some mechanized support tools. structured walk throughs, ‘formal’ inspections specification languages, ‘rigorous’ proofs Level 3: Use of fully formal specification languages with comprehensive support environments, including mechanized theorem proving or proof checking. Software Engineering CSE470: Cheng 334 Formal Semantics Formal semantics provide precise, machine-independent concepts Provide unambiguous specification techniques and a rigorous theory to support reliable reasoning. A formal definition of a language can suggest a method for constructing programs guaranteed to conform to their specifications. So, the purpose of formal specification is ... Software Engineering CSE470: Cheng 335 Purpose of Formal Specification The purpose of a formal specification is to state what a system should do without describing how to do it A formal specification may define a system as an abstract datatype. A formal specification should avoid implementation bias. Software Engineering CSE470: Cheng 336 Purpose of Formal Specification The purpose of a formal specification is to state what a system should do without describing how to do it A formal specification may define a system as an abstract datatype. A formal specification should avoid implementation bias. Software Engineering CSE470: Cheng 337 Formal Specifications Formal specifications serve as a contract documentation means of communication between client, specifier, and implementer Formal specifications are amenable to machine analysis and manipulation Software Engineering CSE470: Cheng 338 Too Little and Too Much There exists a balance between saying enough in a specification and saying too much. say enough so that implementers do not choose unacceptable implementations specifications should capture the requirements completely avoid implementation-bias by not restricting freedom of later designers Software Engineering CSE470: Cheng 339 Operational Approach Define an abstract machine having states, possibly several components, and some set of primitive instructions. Define the machine by specifying how the components of the state are changed by each instruction. Define the semantics of a particular programming language in terms of states. Abstract machines may be unrealistic from a practical point of view, but the simplistic definition prevents misunderstanding code later. Software Engineering CSE470: Cheng 340 Operational Approach con’t The semantic description of the programming language specifies a translation into this code. Trace through the translated program step-by-step to determine its precise effect. Languages defined in this way include PL/I (by the VDM method) Software Engineering CSE470: Cheng 341 The Axiomatic Approach Associate an "axiom" with each kind of statement in the programming language state what may be asserted after execution of that statement in terms of what was true before an example is the use of pre- and postconditions. Software Engineering CSE470: Cheng 342 Another View Model-Oriented: define system behavior by constructing model of system in terms of mathematical structures tuples, functions. sets, or sequences languages include VDM, Z, CSP, and Petri Nets Property-Oriented: define system behavior indirectly by stating a set of properties that the system must satisfy Software Engineering CSE470: Cheng 343 Two Types of PropertyOriented Approaches Axiomatic: use first-order predicate logic (pre- and postconditions) Algebraic: use axioms in equational form to describe properties Software Engineering CSE470: Cheng 344 Obvious Applications Computer Security Fault-tolerant systems (e.g. Nuclear reactors) Safety-critical system (e.g. diagnostic X-ray machine) Gain insight into hardware/software systems (e.g. oscilloscope) Basically, wherever the cost of failure is high: including systems that are critical in some way replicated many times fixed into hardware, or dependent on quality for commercial reasons Software Engineering CSE470: Cheng 345 Relevant Areas of Research Programming environments Formal methods in software development Tools that support construction of formal specifications Design tools that will generate formal specifications Problem/specification decomposition Procedural and data abstraction Synthesis of efficient code "Smart" user interfaces (user-friendly ones!!) Methods for determining reuse (of design/specifications/code) Software Engineering CSE470: Cheng 346 Model Checking Software Engineering CSE470: Cheng 347 Model Checking Used in studying behaviors of reactive systems Typically involves three steps: Create a finite state model (FSM) of the system design Specify critical correctness properties Validate the model w/r to the specifications Software Engineering CSE470: Cheng 348 Create a FSM FSM languages focus on expressing concurrency, synchronization, and communication abstract details of internal computations must be precise and unambiguous (formally defined syntax and semantics) We will use Promela for giving system descriptions Software Engineering CSE470: Cheng 349 Specify correctness properties Safety properties: Nothing “bad” ever happens Formalized using state invariants execution never reaches a “bad” state Liveness properties: Something “good” eventually happens Formalized using temporal logic special logic for describing sequences Software Engineering CSE470: Cheng 350 Validate the model “Execute” the model to test it simulate executions of the system check satisfaction of safety properties along simulated executions Exhaustive analysis generate reachability graph to verify safety and liveness properties Generate counterexamples to illustrate failures Software Engineering CSE470: Cheng 351 Home Heating System Software Engineering CSE470: Cheng 352 Example properties Pump is never on unless Burner is also on Whenever Sensor calls resp-temp(LOW), eventually Controller becomes all-on Software Engineering CSE470: Cheng 353 Reachability Graph Graph of global states that can be “reached” during execution global state contains a state for each concurrent “process” transitions show how an event or action transforms the global state Analyze global state space to verify safety properties Analyze paths through the RG to verify liveness properties Software Engineering CSE470: Cheng 354 Promela The system description language of SPIN Designed for modeling data communication protocols System described as a collection of concurrent processes Processes communicate and synchronize via message channels and global variables Software Engineering CSE470: Cheng 355 Promela Specify macro definitions #define signal 0 Declare symbolic constants mtype = { ON, OFF, LOW, OK } Declare a synchronous message channel chan pump_in = [0] of { mtype } Software Engineering CSE470: Cheng 356 Promela Create a process instance active proctype pump ( ) { statements } Send a message pump_in!ON Receive a message pump_in?ON Software Engineering CSE470: Cheng 357 Promela version of HHS Software Engineering CSE470: Cheng 358 Promela version of HHS Software Engineering CSE470: Cheng 359 Promela version of HHS Software Engineering CSE470: Cheng 360 SPIN simulation of HHS SPIN automatically generates sequence diagrams to represent executions random guided interactive Automates tracing between system views sequence diagram Promela description state diagram textual execution traces Software Engineering CSE470: Cheng 361 Verification of a safety property Pump is never on unless Burner is also on Software Engineering CSE470: Cheng 362 Verification of a liveness property Whenever Sensor calls resp-temp(LOW), eventually Controller becomes all-on Software Engineering CSE470: Cheng 363 Verification of a liveness property Software Engineering CSE470: Cheng 364 System Design Software Engineering CSE470: Cheng 365 Design: HOW to implement a system Goals: Satisfy the requirements Satisfy the customer Reduce development costs Provide reliability Support maintainability Plan for future modifications Software Engineering CSE470: Cheng 366 Design Issues Architecture User Interface Operations Data Representations Data Types Software Engineering CSE470: Cheng Algorithms 367 Design System design (high level design) Focus on architecture Identification of subsystems Object design (lower level design) Modules and their implementations Focus on data representations and algorithms Software Engineering CSE470: Cheng 368 System Design Choose high-level strategy for solving problem and building solution Decide how to organize the system into subsystems Identify concurrency / tasks Allocate subsystems to HW and SW components Software Engineering CSE470: Cheng 369 System Design Major conceptual and policy decisions Approach for management of data stores Access mechanism for global resources Software control mechanism Handle boundary conditions Prioritize trade-offs Software Engineering CSE470: Cheng 370 Design Principles Consider alternative approaches Do pro and con analysis Delay decisions until superior choice is clear Isolate decisions so alternative implementations can be evaluated later Avoid unnecessary embellishments But don’t oversimplify Software Engineering CSE470: Cheng 371 Design Principles (cont.) Make design traceable to requirements Use uniform documentation style Reuse existing designs when possible Keep design simple unless performance, maintainability, etc. DEMAND otherwise Software Engineering CSE470: Cheng 372 Design Principles (cont.) Define interfaces between modules carefully Consider how to handle the unexpected Don’t code!! Document decisions Review, review, review . . . Software Engineering CSE470: Cheng 373 System Architecture Overall organization of system into subsystems Decide basic interaction patterns Numerous architectural styles for different applications Architecture provides context for detailed design decisions Software Engineering CSE470: Cheng 374 Subsystem Identification Divide system into a manageable number of components Each major component is a subsystem Subsystem groups components with common properties/function Software Engineering CSE470: Cheng 375 Subsystem Collection of Classes Associations Operations Events Constraints Software Engineering CSE470: Cheng Interrelated Good cohesion Well-defined, small interface with other subsystems Low coupling Identified by the service it provides 376 Subsystem Discussion Provide services for other sub-systems Group of related functions Share a common purpose Divide system into components (>20) Subsystems are decomposed . . . Module is the lowest level of subsystem Software Engineering CSE470: Cheng 377 Subsystem Relationships Client-Server relationship Client subsystems actively drive the system by requesting services provided by a server subsystem Peer-to-peer relationship Subsystems interact and communicate to accomplish a common goal Software Engineering CSE470: Cheng 378 Client-Server Relationship Server supplies services for clients Need not know identity of clients Need not know interface of clients Client calls server Client knows interface of server Server performs some service and returns a result Software Engineering CSE470: Cheng 379 Peer-to-Peer Relationship Subsystems call one another The results of/responses to calls may not be immediately visible Subsystems must know the interfaces of other subsystems More likely to have communication dependencies Software Engineering CSE470: Cheng 380 Strategies for Decompositions Layers: Horizontal decomposition Open Closed Partitions: Vertical decomposition System topology: General decompositions Software Engineering CSE470: Cheng 381 Layered Subsystems Set of “virtual” worlds Each layer is defined in terms of the layer(s) below it Knowledge is one way: Layer knows about layer(s) below it Objects within layer can be independent Lower layer (server) supplies services for objects (clients) in upper layer(s) Software Engineering CSE470: Cheng 382 Example: Layered architecture Interactive Graphics Application Windows Operations Screen Operations Pixel Operations Device I/O Operations Software Engineering CSE470: Cheng 383 Closed Architectures Each layer is built only in terms of the immediate lower layer Reduces dependencies between layers Facilitates change Software Engineering CSE470: Cheng 384 Open Architectures Layer can use any lower layer Reduces the need to redefine operations at each level More efficient /compact code System is less robust/harder to change Software Engineering CSE470: Cheng 385 Properties of Layered Architectures Top and bottom layers specified by the problem statement Top layer is the desired system Bottom layer is defined by available resources (e.g. HW, OS, libraries) Easier to port to other HW/SW platforms Software Engineering CSE470: Cheng 386 Partitioned Architectures Divide system into weakly-coupled subsystems Each provides specific services Vertical decomposition of problem Software Engineering CSE470: Cheng 387 Ex: Partitioned Architecture Operating System Virtual File Process Memory Device System Control Manage- Control ment Software Engineering CSE470: Cheng 388 Typical Application Architecture Application package Window graphics User dialogue control Screen graphics Simulation package Pixel graphics Operating system Computer hardware Software Engineering CSE470: Cheng 389 System Topology Describe information flow Can use DFD to model flow Some common topologies Pipeline (batch) Star topology Software Engineering CSE470: Cheng 390 Ex: Pipeline Topology Compiler: source program Lexical analyzer token stream Semantic analyzer abstract syntax tree Code generator code sequence Software Engineering CSE470: Cheng Code optimizer object code 391 Ex: Star Toplogy Monitoring system: Alarm Sensors sensor status commands, SafeHome data software Control panel display information Software Engineering CSE470: Cheng On/Off signals, alarm type Telephone line number tones 392 Modularity Organize modules according to resources/objects/data types Provide cleanly defined interfaces operations, methods, procedures, ... Hide implementation details Simplify program understanding Simplify program maintainance Software Engineering CSE470: Cheng 393 Abstraction Control abstraction Procedural abstraction structured control statements exception handling concurrency constructs procedures and functions Data abstraction user defined types Software Engineering CSE470: Cheng 394 Abstraction (cont.) Abstract data types encapsulation of data Abstract objects subtyping generalization/inheritance Software Engineering CSE470: Cheng 395 Cohesion Contents of a module should be cohesive Improves maintainability Easier to understand Reduces complexity of design Supports reuse Software Engineering CSE470: Cheng 396 (Weak) Types of cohesiveness Coincidentally cohesive Logically cohesive contiguous lines of code not exceeding a maximum size all output routines Temporally cohesive all initialization routines Software Engineering CSE470: Cheng 397 (Better) Types of cohesiveness Procedurally cohesive Communicationally cohesive routines called in sequence work on same chunk of data Functionally cohesive work on same data abstraction at a consistent level of abstraction Software Engineering CSE470: Cheng 398 Example: Poor Cohesion package Output is procedure DisplayDice( . . .); procedure DisplayBoard( . . .); I/O device Dice Output Software Engineering CSE470: Cheng Board 399 Example: Good Cohesion package Dice is procedure Display ( . . .); procedure Roll( . . .); Dice I/O device Board Software Engineering CSE470: Cheng 400 Coupling Connections between modules Bad coupling Global variables Flag parameters Direct manipulation of data structures by multiple classes Software Engineering CSE470: Cheng 401 Coupling (cont.) Good coupling Procedure calls Short argument lists Objects as parameters Good coupling improves maintain-ability Easier to localize errors, modify implementations of an objects, ... Software Engineering CSE470: Cheng 402 Information Hiding Hide decisions likely to change Black box Data representations, algorithmic details, system dependencies Input is known Output is predictable Mechanism is unknown Improves maintainability Software Engineering CSE470: Cheng 403 Information Hiding Software Engineering CSE470: Cheng 404 Abstract data types Modules (Classes, packages) Encapsulate data structures and their operations Good cohesion Good coupling implement a single abstraction pass abstract objects as parameters Black boxes hide data representations and algorithms Software Engineering CSE470: Cheng 405 Identifying Concurrency Inherent concurrency May involve synchronization Multiple objects receive events at the same time with out interacting Example: User may issue commands through control panel at same time that the sensor is sending status information to the SafeHome system Software Engineering CSE470: Cheng 406 Determining Concurrent Tasks Thread of control Path through state diagram with only one active object at any time Threads of control are implemented as tasks Interdependent objects Examine state diagram to identify objects that can be implemented in a task Software Engineering CSE470: Cheng 407 Management of Data Stores Data stores permit separations between subsystems Internal or external Common types of data stores Files Databases Software Engineering CSE470: Cheng 408 File Data Stores When to use a database Require access to voluminous data at fine levels of detail by multiple users Access can be efficiently managed with DBMS commands Application must port across many HW and OS platforms Store is to be accessed by multiple application programs Software Engineering CSE470: Cheng 409 Database Data Stores Advantages Infrastructure support Common interface Standard access language (SQL) Disadvantages Performance penalty Awkward programming language Software Engineering CSE470: Cheng 410 File Data Stores When to use file data stores Data does not fit structure of DBMS Voluminous data that is low in information density “Raw” data Volatile data only retained for a short time Software Engineering CSE470: Cheng 411 Global Resources Identify global resources and determine access patterns Examples physical units (processors, tape drives) available space (disk, screen, buttons) logical names (object IDs, filenames) access to shared data (database, file) Software Engineering CSE470: Cheng 412 Software Control Mechanism How SW will control interactions between objects Internal control External control flow of control within a process flow of externally-visible events among objects Uniform control style for objects Software Engineering CSE470: Cheng 413 Internal Control Under control of programmer Structured for convenience efficiency, clarity, reliability, . . . Common types of control flow Procedure calls Quasi-concurrent inter-task calls Concurrent inter-task calls Software Engineering CSE470: Cheng 414 External Control Procedure-driven Event-driven Concurrent systems systems systems Software Engineering CSE470: Cheng 415 Procedure-driven systems Control resides within the program code procedure issues request, waits for reply, then continues execution System state defined by program counter, stack of procedure calls, local variables Software Engineering CSE470: Cheng 416 Event-Driven Systems Control resides within a central dispatcher calls to the dispatcher send output or enable input dispatcher invokes procedures when events occur (“call back”) state maintained using global variables, or by dispatcher for procedures Software Engineering CSE470: Cheng 417 Concurrent Systems Control resides concurrently in independent tasks Events are implemented as messages between tasks OS schedules tasks for execution Software Engineering CSE470: Cheng 418 Boundary Conditions Initialization Termination Constants, parameters, global variables, tasks, guardians, class hierarchy Release external resources, notify other tasks Failure Clean up and log failure info Software Engineering CSE470: Cheng 419 Identify Trade-off Priorities Establish priorities for choosing between incompatible goals Implement minimal functionality initially and embellish as appropriate Isolate decision points for later evaluation Trade efficiency for simplicity, reliability, . . . Software Engineering CSE470: Cheng 420 Chapter 7, Object Design Software Engineering CSE470: Cheng 421 Object Design Object design is the process of adding details to the requirements analysis and making implementation decisions The object designer must choose among different ways to implement the analysis model with the goal to minimize execution time, memory and other measures of cost. Requirements Analysis: Use cases, functional and dynamic model deliver operations for object model Object Design: We iterate on where to put these operations in the object model Object Design serves as the basis of implementation Software Engineering CSE470: Cheng 422 Object Design: Closing the Gap System Problem Application objects Requir ements gap Solution objects Custom objects Object design gap Off-the-shelf components System design gap 423 Software Engineering CSE470: Cheng Machine Object Design Issues Full definition of associations Full definition of classes Choice of algorithms and data structures Detection of new application-domain independent classes (example: Cache) Optimization Increase of inheritance Decision on control Packaging Software Engineering CSE470: Cheng 424 Terminology of Activities Object-Oriented Methodologies System Design Object Design Decomposition into subsystems Implementation language chosen Data structures and algorithms chosen SA/SD uses different terminology: Preliminary Design Decomposition into subsystems Data structures are chosen Detailed Design Algorithms are chosen Data structures are refined Implementation language is chosen Typically in parallel with preliminary design, not separate stage Object Design Activities 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address 426 performance criteria such as response time or memory Software Engineering CSE470: Cheng Service Specification Requirements analysis Identifies attributes and operations without specifying their types or their parameters. Object design Add visibility information Add type signature information Add contracts Software Engineering CSE470: Cheng 427 Add Visibility UML defines three levels of visibility: Private: A private attribute can be accessed only by the class in which it is defined. A private operation can be invoked only by the class in which it is defined. Private attributes and operations cannot be accessed by subclasses or other classes. Protected: A protected attribute or operation can be accessed by the class in which it is defined and on any descendent 428 Software Engineering CSE470: Cheng of the class. Information Hiding Heuristics Build firewalls around classes Apply “Need to know” principle. The fewer an operation knows Carefully define public interfaces for classes as well as subsystems the less likely it will be affected by any changes the easier the class can be changed Trade-off Information hiding vs efficiency Software Engineering CSE470: Cheng 429 Information Hiding Design Principles Only the operations of a class are allowed to manipulate its attributes Hide external objects at subsystem boundary Access attributes only via operations. Define abstract class interfaces which mediate between system and external world as well as between subsystems Do not apply an operation to the result of another operation. Write a new operation that combines the two operations. Software Engineering CSE470: Cheng 430 Add Type Signature Information Hashtable -numElements:int +put() +get() +remove() +containsKey() +size() Hashtable -numElements:int +put(key:Object,entry:Object) +get(key:Object):Object +remove(key:Object) +containsKey(key:Object):boolean +size():int Software Engineering CSE470: Cheng 431 Contracts Contracts on a class enable caller and callee to share the same assumptions about the class. Contracts include three types of constraints: Invariant: A predicate that is always true for all instances of a class. Invariants are constraints associated with classes or interfaces. Invariants are used to specify consistency constraints among class attributes. Precondition: A predicate that must be true before an operation is invoked. Preconditions are associated with a specific operation. Preconditions are used to specify constraints that a caller Software Engineering CSE470: Cheng must meet before calling an432 Expressing constraints in UML OCL (Object Constraint Language) OCL allows constraints to be formally specified on single model elements or groups of model elements A constraint is expressed as an OCL expression returning the value true or false. OCL is not a procedural language (cannot constrain control flow). is a class OCL expressions Context for Hashtable operation put(): OCL expression Invariant: context Hashtable inv: numElements >= 0 Precondition: operation context Hashtable::put(key, entry) pre:!containsKey(key) Software Engineering CSE470: Cheng Post-condition: 433 Expressing Constraints in UML A constraint can also be depicted as a note <<invariant>> attached to the constrained UML element by>= 0a numElements HashTable dependency relationship. <<precondition>> <<postcondition>> !containsKey(key) <<precondition>> containsKey(key) <<precondition>> containsKey(key) numElements:int put(key,entry:Object) get(key):Object remove(key:Object) containsKey(key:Object):boolean size():int Software Engineering CSE470: Cheng get(key) == entry <<postcondition>> !containsKey(key) 434 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address 435 performance criteria such as response time or memory Software Engineering CSE470: Cheng Component Selection Select existing off-the-shelf class libraries, frameworks or components Adjust the class libraries, framework or components Change the API if you have the source code. Use the adapter or bridge pattern if you don’t have access Software Engineering CSE470: Cheng 436 Reuse... Look for existing classes in class libraries Select data structures appropriate to the algorithms JSAPI, JTAPI, .... Container classes Arrays, lists, queues, stacks, sets, trees, ... Define new internal classes and operations only if necessary Complex operations defined in terms of lower-level operations might need new classes and operations Software Engineering CSE470: Cheng 437 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address 438 performance criteria such as response time or memory Software Engineering CSE470: Cheng Restructuring Activities This Lecture Realizing associations Revisiting inheritance to increase reuse Revising inheritance to remove implementation dependencies Software Engineering CSE470: Cheng 439 Increase Inheritance Rearrange and adjust classes and operations to prepare for inheritance Abstract common behavior out of groups of classes If a set of operations or attributes are repeated in 2 classes the classes might be special instances of a more general class. Be prepared to change a subsystem (collection of classes) into a superclass in an inheritance hierarchy. Software Engineering CSE470: Cheng 440 Building a super class from several classes Prepare for inheritance. All operations must have the same signature but often the signatures do not match: Some operations have fewer arguments than others: Use overloading (Possible in Java) Similar attributes in the classes have different names: Rename attribute and change all the operations. Operations defined in one class but no in the other: Use virtual functions and class function overriding. Abstract out the common behavior (set of operations with same signature) and create a superclass out of it. Superclasses are desirable. They Software Engineering CSE470: Cheng 441 Implement Associations Strategy for implementing associations: Be as uniform as possible Individual decision for each association Example of uniform implementation 1-to-1 association: 1-to-many association: Role names are treated like attributes in the classes and translate to references Translate to Vector Qualified association: Translate to Hash table Software Engineering CSE470: Cheng 442 Unidirectional 1-to-1 Association Object design model befor e transformation ZoomInAction 1 1 MapArea Object design model after transformation ZoomInAction Software Engineering CSE470: Cheng MapArea targetMap:MapArea 443 Bidirectional 1-to-1 Association Object design model befor e transformation ZoomInAction 1 1 MapArea Object design model after transformation ZoomInAction -targetMap:MapArea +getTargetMap() +setTargetMap(map) Software Engineering CSE470: Cheng MapArea -zoomIn:ZoomInAction +getZoomInAction() +setZoomInAction(action 444 1-to-Many Association Object design model before Layer transformation 1 * LayerElement Object design model after transformation Layer -layerElements:Set +elements() +addElement(le) +removeElement(le) Software Engineering CSE470: Cheng LayerElement -containedIn:Layer +getLayer() +setLayer(l) 445 Qualification Object design model before transformation Scenario simname * 0..1 SimulationRun Object design model after transformation Scenario -runs:Hashtable +elements() +addRun(simname,sr:SimulationRun) +removeRun(simname,sr:SimulationRun) Software Engineering CSE470: Cheng SimulationRun -scenarios:Vector +elements() +addScenario(s:Scenario) +removeScenario(s:Scenario) 446 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address 447 performance criteria such as response time or memory Software Engineering CSE470: Cheng Design Optimizations Design optimizations are an important part of the object design phase: The requirements analysis model is semantically correct but often too inefficient if directly implemented. Optimization activities during object design: 1. Add redundant associations to minimize access cost 2. Rearrange computations for greater efficiency 3. Store derived attributes to save computation time As an object designer you must strike a balance between efficiency and clarity. Optimizations will make Software Engineering CSE470: Cheng your models more obscure 448 Design Optimization Activities 1. Add redundant associations: What are the most frequent operations? ( Sensor data lookup?) How often is the operation called? (30 times a month, every 50 milliseconds) 2. Rearrange execution order Eliminate dead paths as early as possible (Use knowledge of distributions, frequency of path traversals) Narrow search as soon as possible Check if execution order of loop should be reversed 3. Turn classes into attributes Software Engineering CSE470: Cheng 449 Implement Application domain classes To collapse or not collapse: Attribute or association? Object design choices: Implement entity as embedded attribute Implement entity as separate class with associations to other classes Associations are more flexible than attributes but often introduce unnecessary indirection. Software Engineering CSE470: Cheng 450 Optimization Activities: Collapsing Objects SocialSecurity Person ID:String Person SSN:String Software Engineering CSE470: Cheng 451 To Collapse or not to Collapse? Collapse a class into an attribute if the only operations defined on the attributes are Set() and Get(). Software Engineering CSE470: Cheng 452 Design Optimizations (continued) Store derived attributes Example: Define new classes to store information locally (database cache) Problem with derived attributes: Derived attributes must be updated when base values change. There are 3 ways to deal with the update problem: Explicit code: Implementor determines affected derived attributes (push) Periodic computation: Recompute derived attribute occasionally (pull) Active value: An attribute can designate set of dependent 453 Software Engineering CSE470: Cheng values which are automatically updated when active value is Optimization Activities: Delaying Complex Computations Image filename:String data:byte[] width() height() paint() Image filename:String width() height() paint() ImageProxy image 1 filename:String width() height() paint() Software Engineering CSE470: Cheng 0..1 RealImage data:byte[] width() height() paint() 454 Documenting the Object Design: The Object Design Document (ODD) Object design document ODD Management issues Same as RAD +... … + additions to object, functional and dynamic models (from solution domain) … + Navigational map for object model … + Javadoc documentation for all classes Update the RAD models in the RAD? Should the ODD be a separate document? Who is the target audience for these documents (Customer, developer?) If time is short: Focus on the Navigational Map and Javadoc documentation? Example of acceptable ODD: http://macbruegge1.informatik.tuSoftware Engineering CSE470: Cheng 455 Documenting Object Design: Conventions EachODD subsystem in a system provides a service (see Chapter on System Design) Describes the set of operations provided by the subsystem Specifying a service operation as Signature: Name of operation, fully typed parameter list and return type Abstract: Describes the operation Pre: Precondition for calling the operation Post: Postcondition describing important state after the execution of the operation Use JavaDoc forCSE470: the Cheng specification of service Software Engineering 456 JavaDoc Add documentation comments to the source code. A doc comment consists of characters between /** and */ When JavaDoc parses a doc comment, leading * characters on each line are discarded. First, blanks and tabs preceding the initial * characters are also discarded. Doc comments may include HTML tags Example of a doc comment: /** Software Engineering CSE470: Cheng 457 More on Java Doc Doc comments are only recognized when placed immediately before class, interface, constructor, method or field declarations. When you embed HTML tags within a doc comment, you should not use heading tags such as <h1> and <h2>, because JavaDoc creates an entire structured document and these structural tags interfere with the formatting of the generated document. Class and Interface Doc Tags 458 Software Engineering CSE470: Cheng Constructor and Method Doc Tags Class and Interface Doc Tags @author name-text Creates an “Author” entry. @version version-text Creates a “Version” entry. @see classname Creates a hyperlink “See Also classname” @since since-text Adds a “Since” entry. Usually used to specify that a feature or change exists since the release number of the software specified in the “since-text” @deprecated deprecated-text Adds a comment that this method can no longer be459 Software Engineering CSE470: Cheng used. Convention is to describe method that serves Constructor and Method Doc Tags Can contain @see tag, @since tag, @deprecated as well as: @param parameter-name description Adds a parameter to the "Parameters" section. The description may be continued on the next line. @return description Adds a "Returns" section, which contains the description of the return value. @exception fully-qualified-class-name description Adds a "Throws" section, which contains the name of the exception that may be thrown by the method. The 460 exception is linked to its class documentation. Software Engineering CSE470: Cheng /** Example of a Class Doc Comment * A class representing a window on the screen. * For example: * <pre> * Window win = new Window(parent); * win.show(); * </pre> * * @author Sami Shaio * @version %I%, %G% * @see java.awt.BaseWindow * @see java.awt.Button 461 */ Engineering CSE470: Cheng Software /** Example of a Method Doc Comment * Returns the character at the specified index. An index * ranges from <code>0</code> to <code>length() - 1</code>. * * @param index the index of the desired character. * @return the desired character. * @exception StringIndexOutOfRangeException * if the index is not in the range <code>0</code> Software Engineering CSE470: Cheng * to <code>length()-1</code>. 462 Example of a Field Doc Comment A field comment can contain only the @see, @since and @deprecated tags /** * The X-coordinate of the window. * * @see window#1 */ int x = 1263732; Software Engineering CSE470: Cheng 463 Example: Specifying a Service in Java /** Office is a physical structure in a building. It is possible to create an instance of a office; add an occupant; get the name and the number of occupants */ public class Office { /** Adds an occupant to the office */ * @param NAME name is a nonempty string */ public void AddOccupant(string name); /** @Return Returns the name of the office. Requires, that Office has been initialized with a name */ public string GetName(); ....Software Engineering CSE470: Cheng 464 Implementation of Application Domain Classes New objects are often needed during object design: Use of Design patterns lead to new classes The implementation of algorithms may necessitate objects to hold values New low-level operations may be needed during the decomposition of high-level operations Example: The EraseArea() operation offered by a drawing program. Conceptually very simple Implementation Software Engineering CSE470: Cheng Area represented by pixels 465 Application Domain vs Solution Domain Objects Requirements Analysis (Language of Application Domain) Object Design (Language of Solution Domain) Incident Report Incident Report Text box Software Engineering CSE470: Cheng Menu Scrollbar 466 Package it all up Pack up design into discrete physical units that can be edited, compiled, linked, reused Construct physical modules Ideally use one package for each subsystem System decomposition might not be good for implementation. Two design principles for packaging Minimize coupling: Classes in client-supplier relationships are usually loosely coupled Large number of parameters in some methods mean strong coupling (> 4-5) Avoid global data Software Engineering CSE470: Cheng Maximize cohesiveness: 467 Packaging Heuristics Each subsystem service is made available by one or more interface objects within the package Start with one interface object for each subsystem service Try to limit the number of interface operations (7+-2) If the subsystem service has too many operations, reconsider the number of interface objects If you have too many interface objects, reconsider the number of subsystems Difference between interface objects and Java 468 Software Engineering CSE470: Cheng interfaces Summary Object design closes the gap between the requirements and the machine. Object design is the process of adding details to the requirements analysis and making implementation decisions Object design includes: 1. Service specification 2. Component selection 3. Object model restructuring 4. Object model optimization 469 Object design is documented in the Object Design Software Engineering CSE470: Cheng Chapter 7, Object Design Software Engineering CSE470: Cheng 470 Object Design Object design is the process of adding details to the requirements analysis and making implementation decisions The object designer must choose among different ways to implement the analysis model with the goal to minimize execution time, memory and other measures of cost. Requirements Analysis: Use cases, functional and dynamic model deliver operations for object model 471 SoftwareDesign: Engineering CSE470: Object WeCheng iterate on where to put these Object Design: Closing the Gap System Problem Application objects Requir ements gap Solution objects Custom objects Object design gap Off-the-shelf components System design gap Software Engineering CSE470: Cheng Machine 472 Object Design Issues Full definition of associations Full definition of classes Choice of algorithms and data structures Detection of new application-domain independent classes (example: Cache) Optimization Increase of inheritance Decision on control Packaging Software Engineering CSE470: Cheng 473 Terminology of Activities Object-Oriented Methodologies System Design Object Design Decomposition into subsystems Implementation language chosen Data structures and algorithms chosen SA/SD uses different terminology: Preliminary Design Decomposition into subsystems Data structures are chosen Detailed Design Algorithms are chosen Data structures are refined Implementation language is chosen Typically in parallel with preliminary design, not separate stage Software Engineering CSE470: Cheng 474 Object Design Activities 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address performance criteria such as response time or memory utilization. Software Engineering CSE470: Cheng 475 Service Specification Requirements analysis Identifies attributes and operations without specifying their types or their parameters. Object design Add visibility information Add type signature information Add contracts Software Engineering CSE470: Cheng 476 Add Visibility UML defines three levels of visibility: Private: Protected: A private attribute can be accessed only by the class in which it is defined. A private operation can be invoked only by the class in which it is defined. Private attributes and operations cannot be accessed by subclasses or other classes. A protected attribute or operation can be accessed by the class in which it is defined and on any descendent of the class. Public: A public attribute or operation can be accessed by any class. Software Engineering CSE470: Cheng 477 Information Hiding Heuristics Build firewalls around classes Apply “Need to know” principle. The fewer an operation knows Carefully define public interfaces for classes as well as subsystems the less likely it will be affected by any changes the easier the class can be changed Trade-off Information hiding vs efficiency Software Engineering CSE470: Cheng 478 Information Hiding Design Principles Only the operations of a class are allowed to manipulate its attributes Hide external objects at subsystem boundary Access attributes only via operations. Define abstract class interfaces which mediate between system and external world as well as between subsystems Do not apply an operation to the result of another operation. Write a new operation that combines the two operations. Software Engineering CSE470: Cheng 479 Add Type Signature Information Hashtable -numElements:int +put() +get() +remove() +containsKey() +size() Hashtable -numElements:int +put(key:Object,entry:Object) +get(key:Object):Object +remove(key:Object) +containsKey(key:Object):boolean +size():int Software Engineering CSE470: Cheng 480 Contracts Contracts on a class enable caller and callee to share the same assumptions about the class. Contracts include three types of constraints: Invariant: A predicate that is always true for all instances of a class. Invariants are constraints associated with classes or interfaces. Invariants are used to specify consistency constraints among class attributes. Precondition: A predicate that must be true before an operation is invoked. Preconditions are associated with a specific operation. Preconditions are used to specify constraints that a caller must meet before calling an operation. Postcondition: A predicate that must be true after an operation is invoked. Postconditions are associated with a specific operation. Postconditions are used to specify constraints that the object must ensure after the invocation of the operation. Software Engineering CSE470: Cheng 481 Expressing constraints in UML OCL (Object Constraint Language) OCL allows constraints to be formally specified on single model elements or groups of model elements A constraint is expressed as an OCL expression returning the value true or false. OCL is not a procedural language (cannot constrain control flow). OCL expressions for Hashtable operation put(): Invariant: context Hashtable inv: numElements >= 0 Context is a class OCL expression operation Precondition: context Hashtable::put(key, entry) pre:!containsKey(key) Post-condition: context Hashtable::put(key, entry) post: containsKey(key) and get(key) = entry 482 Software Engineering CSE470: Cheng Expressing Constraints in UML A constraint can also be depicted as a note attached to the constrained UML element by a dependency relationship. <<invariant>> numElements >= 0 <<precondition>> !containsKey(key) <<precondition>> containsKey(key) <<precondition>> containsKey(key) HashTable numElements:int put(key,entry:Object) get(key):Object remove(key:Object) containsKey(key:Object):boolean size():int Software Engineering CSE470: Cheng <<postcondition>> get(key) == entry <<postcondition>> !containsKey(key) 483 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address performance criteria such as response time or memory utilization. Software Engineering CSE470: Cheng 484 Component Selection Select existing off-the-shelf class libraries, frameworks or components Adjust the class libraries, framework or components Change the API if you have the source code. Use the adapter or bridge pattern if you don’t have access Software Engineering CSE470: Cheng 485 Reuse... Look for existing classes in class libraries Select data structures appropriate to the algorithms JSAPI, JTAPI, .... Container classes Arrays, lists, queues, stacks, sets, trees, ... Define new internal classes and operations only if necessary Complex operations defined in terms of lower-level operations might need new classes and operations Software Engineering CSE470: Cheng 486 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address performance criteria such as response time or memory utilization. Software Engineering CSE470: Cheng 487 Restructuring Activities This Lecture Realizing associations Revisiting inheritance to increase reuse Revising inheritance to remove implementation dependencies Software Engineering CSE470: Cheng 488 Increase Inheritance Rearrange and adjust classes and operations to prepare for inheritance Abstract common behavior out of groups of classes If a set of operations or attributes are repeated in 2 classes the classes might be special instances of a more general class. Be prepared to change a subsystem (collection of classes) into a superclass in an inheritance hierarchy. Software Engineering CSE470: Cheng 489 Building a super class from several classes Prepare for inheritance. All operations must have the same signature but often the signatures do not match: Some operations have fewer arguments than others: Use overloading (Possible in Java) Similar attributes in the classes have different names: Rename attribute and change all the operations. Operations defined in one class but no in the other: Use virtual functions and class function overriding. Abstract out the common behavior (set of operations with same signature) and create a superclass out of it. Superclasses are desirable. They increase modularity, extensibility and reusability improve configuration management Software Engineering CSE470: Cheng 490 Implement Associations Strategy for implementing associations: Be as uniform as possible Individual decision for each association Example of uniform implementation 1-to-1 association: 1-to-many association: Role names are treated like attributes in the classes and translate to references Translate to Vector Qualified association: Translate to Hash table Software Engineering CSE470: Cheng 491 Unidirectional 1-to-1 Association Object design model befor e transformation ZoomInAction 1 1 MapArea Object design model after transformation ZoomInAction Software Engineering CSE470: Cheng MapArea targetMap:MapArea 492 Bidirectional 1-to-1 Association Object design model befor e transformation ZoomInAction 1 1 MapArea Object design model after transformation ZoomInAction -targetMap:MapArea +getTargetMap() +setTargetMap(map) Software Engineering CSE470: Cheng MapArea -zoomIn:ZoomInAction +getZoomInAction() +setZoomInAction(action 493 1-to-Many Association Object design model before Layer transformation 1 * LayerElement Object design model after transformation Layer -layerElements:Set +elements() +addElement(le) +removeElement(le) Software Engineering CSE470: Cheng LayerElement -containedIn:Layer +getLayer() +setLayer(l) 494 Qualification Object design model before transformation Scenario simname * 0..1 SimulationRun Object design model after transformation Scenario -runs:Hashtable +elements() +addRun(simname,sr:SimulationRun) +removeRun(simname,sr:SimulationRun) Software Engineering CSE470: Cheng SimulationRun -scenarios:Vector +elements() +addScenario(s:Scenario) +removeScenario(s:Scenario) 495 Object Design Areas 1. Service specification Describes precisely each class interface 2. Component selection Identify off-the-shelf components and additional solution objects 3. Object model restructuring Transforms the object design model to improve its understandability and extensibility 4. Object model optimization Transforms the object design model to address performance criteria such as response time or memory utilization. Software Engineering CSE470: Cheng 496 Design Optimizations Design optimizations are an important part of the object design phase: The requirements analysis model is semantically correct but often too inefficient if directly implemented. Optimization activities during object design: 1. Add redundant associations to minimize access cost 2. Rearrange computations for greater efficiency 3. Store derived attributes to save computation time As an object designer you must strike a balance between efficiency and clarity. Optimizations will make your models more obscure Software Engineering CSE470: Cheng 497 Design Optimization Activities 1. Add redundant associations: What are the most frequent operations? ( Sensor data lookup?) How often is the operation called? (30 times a month, every 50 milliseconds) 2. Rearrange execution order Eliminate dead paths as early as possible (Use knowledge of distributions, frequency of path traversals) Narrow search as soon as possible Check if execution order of loop should be reversed 3. Turn classes into attributes Software Engineering CSE470: Cheng 498 Implement Application domain classes To collapse or not collapse: Attribute or association? Object design choices: Implement entity as embedded attribute Implement entity as separate class with associations to other classes Associations are more flexible than attributes but often introduce unnecessary indirection. Software Engineering CSE470: Cheng 499 Optimization Activities: Collapsing Objects SocialSecurity Person ID:String Person SSN:String Software Engineering CSE470: Cheng 500 To Collapse or not to Collapse? Collapse a class into an attribute if the only operations defined on the attributes are Set() and Get(). Software Engineering CSE470: Cheng 501 Design Optimizations (continued) Store derived attributes Example: Define new classes to store information locally (database cache) Problem with derived attributes: Derived attributes must be updated when base values change. There are 3 ways to deal with the update problem: Explicit code: Implementor determines affected derived attributes (push) Periodic computation: Recompute derived attribute occasionally (pull) Active value: An attribute can designate set of dependent values which are automatically updated when active value is changed (notification, data trigger) Software Engineering CSE470: Cheng 502 Optimization Activities: Delaying Complex Computations Image filename:String data:byte[] width() height() paint() Image filename:String width() height() paint() ImageProxy filename:String width() height() paint() Software Engineering CSE470: Cheng image 1 0..1 RealImage data:byte[] width() height() paint() 503 Documenting the Object Design: The Object Design Document (ODD) Object design document Same as RAD +... … + additions to object, functional and dynamic models (from solution domain) … + Navigational map for object model … + Javadoc documentation for all classes ODD Management issues Update the RAD models in the RAD? Should the ODD be a separate document? Who is the target audience for these documents (Customer, developer?) If time is short: Focus on the Navigational Map and Javadoc documentation? Software Engineering CSE470: Cheng 504 Documenting Object Design: ODD Conventions Each subsystem in a system provides a service (see Chapter on System Design) Describes the set of operations provided by the subsystem Specifying a service operation as Signature: Name of operation, fully typed parameter list and return type Abstract: Describes the operation Pre: Precondition for calling the operation Post: Postcondition describing important state after the execution of the operation Software Engineering CSE470: Cheng 505 For your information slides (Examples in Java) Beginning Software Engineering CSE470: Cheng 506 JavaDoc Add documentation comments to the source code. A doc comment consists of characters between /** and */ When JavaDoc parses a doc comment, leading * characters on each line are discarded. First, blanks and tabs preceding the initial * characters are also discarded. Doc comments may include HTML tags Example of a doc comment: /** * This is a <b> doc </b> comment */ Software Engineering CSE470: Cheng 507 More on Java Doc Doc comments are only recognized when placed immediately before class, interface, constructor, method or field declarations. When you embed HTML tags within a doc comment, you should not use heading tags such as <h1> and <h2>, because JavaDoc creates an entire structured document and these structural tags interfere with the formatting of the generated document. Class and Interface Doc Tags Constructor and Method Doc Tags Software Engineering CSE470: Cheng 508 Class and Interface Doc Tags @author name-text Creates an “Author” entry. @version version-text Creates a “Version” entry. @see classname Creates a hyperlink “See Also classname” @since since-text Adds a “Since” entry. Usually used to specify that a feature or change exists since the release number of the software specified in the “sincetext” @deprecated deprecated-text Adds a comment that this method can no longer be used. Convention is to describe method that serves as replacement Example: @deprecated Replaced by setBounds(int, int, int, int). Software Engineering CSE470: Cheng 509 Constructor and Method Doc Tags Can contain @see tag, @since tag, @deprecated as well as: @param parameter-name description Adds a parameter to the "Parameters" section. The description may be continued on the next line. @return description Adds a "Returns" section, which contains the description of the return value. @exception fully-qualified-class-name description Adds a "Throws" section, which contains the name of the exception that may be thrown by the method. The exception is linked to its class documentation. @see classname Adds a hyperlink "See Also" entry to the method. Software Engineering CSE470: Cheng 510 Example of a Class Doc Comment /** * A class representing a window on the screen. * For example: * <pre> * Window win = new Window(parent); * win.show(); * </pre> * * @author Sami Shaio * @version %I%, %G% * @see java.awt.BaseWindow * @see java.awt.Button */ class Window extends BaseWindow { ... } Software Engineering CSE470: Cheng 511 /** Example of a Method Doc Comment * Returns the character at the specified index. An index * ranges from <code>0</code> to <code>length() 1</code>. * * @param index the index of the desired character. * @return the desired character. * @exception StringIndexOutOfRangeException * if the index is not in the range <code>0</code> * to <code>length()-1</code>. * @see java.lang.Character#charValue() */ public char charAt(int index) { ... } 512 Software Engineering CSE470: Cheng Example of a Field Doc Comment A field comment can contain only the @see, @since and @deprecated tags /** * The X-coordinate of the window. * * @see window#1 */ int x = 1263732; Software Engineering CSE470: Cheng 513 Example: Specifying a Service in Java /** Office is a physical structure in a building. It is possible to create an instance of a office; add an occupant; get the name and the number of occupants */ public class Office { /** Adds an occupant to the office */ * @param NAME name is a nonempty string */ public void AddOccupant(string name); /** @Return Returns the name of the office. Requires, that Office has been initialized with a name */ public string GetName(); ....Software Engineering CSE470: Cheng 514 Implementation of Application Domain Classes New objects are often needed during object design: Use of Design patterns lead to new classes The implementation of algorithms may necessitate objects to hold values New low-level operations may be needed during the decomposition of high-level operations Example: The EraseArea() operation offered by a drawing program. Conceptually very simple Implementation Area represented by pixels Repair () cleans up objects partially covered by the erased area Redraw() draws objects uncovered by the erasure Draw() erases pixels in background color not covered by other objects Software Engineering CSE470: Cheng 515 For your information slides (Examples in Java) End Software Engineering CSE470: Cheng 516 Application Domain vs Solution Domain Objects Requirements Analysis (Language of Application Domain) Object Design (Language of Solution Domain) Incident Report Incident Report Text box Software Engineering CSE470: Cheng Menu Scrollbar 517 Package it all up Pack up design into discrete physical units that can be edited, compiled, linked, reused Construct physical modules Ideally use one package for each subsystem System decomposition might not be good for implementation. Two design principles for packaging Minimize coupling: Classes in client-supplier relationships are usually loosely coupled Large number of parameters in some methods mean strong coupling (> 4-5) Avoid global data Maximize cohesiveness: Classes closely connected by associations => same package Software Engineering CSE470: Cheng 518 Packaging Heuristics Each subsystem service is made available by one or more interface objects within the package Start with one interface object for each subsystem service Try to limit the number of interface operations (7+-2) If the subsystem service has too many operations, reconsider the number of interface objects If you have too many interface objects, reconsider the number of subsystems Difference between interface objects and Java interfaces Interface object : Used during requirements analysis, system design and object design. Denotes a service or API Java interface: Used during implementation in Java (A Java interface may or may not implement an interface object) Software Engineering CSE470: Cheng 519 Summary Object design closes the gap between the requirements and the machine. Object design is the process of adding details to the requirements analysis and making implementation decisions Object design includes: 1. Service specification 2. Component selection 3. Object model restructuring 4. Object model optimization Object design is documented in the Object Design Document, which can be generated using tools such as JavaDoc. Software Engineering CSE470: Cheng 520 Chapter 9, Testing Software Engineering CSE470: Cheng 521 Outline Terminology Types of errors Dealing with errors Quality assurance vs Testing Component Testing System testing Function testing Structure Testing Performance testing Acceptance testing Installation testing Unit testing Integration testing Testing Strategy Design Patterns & Software Engineering CSE470: Cheng 522 Terminology Reliability: The measure of success with which the observed behavior of a system confirms to some specification of its behavior. Failure: Any deviation of the observed behavior from the specified behavior. Error: The system is in a state such that further processing by the system will lead to a failure. Fault (Bug): The mechanical or algorithmic cause of an error. Software Engineering CSE470: Cheng There are many different types of errors and 523 What is this? Software Engineering CSE470: Cheng 524 Erroneous State (“Error”) Software Engineering CSE470: Cheng 525 Algorithmic Fault Software Engineering CSE470: Cheng 526 Mechanical Fault Software Engineering CSE470: Cheng 527 How do we deal with Errors and Faults? Software Engineering CSE470: Cheng 528 Verification? Software Engineering CSE470: Cheng 529 Modular Redundancy? Software Engineering CSE470: Cheng 530 Declaring the Bug as a Feature? Software Engineering CSE470: Cheng 531 Patching? Software Engineering CSE470: Cheng 532 Testing? Software Engineering CSE470: Cheng 533 Examples of Faults and Errors Faults in the Interface specification Mismatch between what the client needs and what the server offers Mismatch between requirements and implementation Algorithmic Faults Missing initialization Branching errors (too soon, too late) Missing test for nil Software Engineering CSE470: Cheng Mechanical Faults (very hard to find) Documentation does not match actual conditions or operating procedures Errors Stress or overload errors Capacity or boundary errors Timing errors Throughput or performance errors 534 Dealing with Errors Verification: Modular redundancy: Bad practice Patching Expensive Declaring a bug to be a “feature” Assumes hypothetical environment that does not match real environment Proof might be buggy (omits important constraints; simply wrong) Slows down performance Testing (this lecture) Testing is never good enough Software Engineering CSE470: Cheng 535 Another View on How to Deal with Errors Error prevention (before the system is released): Error detection (while system is running): Use good programming methodology to reduce complexity Use version control to prevent inconsistent system Apply verification to prevent algorithmic bugs Testing: Create failures in a planned way Debugging: Start with an unplanned failures Monitoring: Deliver information about state. Find performance bugs Error recovery (recover from failure once the system is released): Data base systems (atomic transactions) Modular redundancy Recovery blocks Software Engineering CSE470: Cheng 536 Some Observations It is impossible to completely test any nontrivial module or any system Theoretical limitations: Halting problem Practial limitations: Prohibitive in time and cost Testing can only show the presence of bugs, not their absence (Dijkstra) Software Engineering CSE470: Cheng 537 Testing takes creativity Testing often viewed as dirty work. To develop an effective test, one must have: Testing is done best by independent testers We often develop a certain mental attitude that the program should in a certain way when in fact it does not. Programmer often stick to the data set that makes the program work Detailed understanding of the system Knowledge of the testing techniques Skill to apply these techniques in an effective and efficient manner "Don’t mess up my code!" A program often does not work when tried by somebody else. Don't let this be the end-user. Software Engineering CSE470: Cheng 538 Testing Activities Subsystem Code Subsystem Code Unit Test Unit Test Tested Subsystem Tested Subsystem Requirements Analysis Document System Design Document Integration Test Functional Test Integrated Subsystems User Manual Functioning System Tested Subsystem Subsystem Code Unit Test Software Engineering CSE470: Cheng All tests by developer 539 Testing Activities ctd Client’s Understanding of Requirements Global Requirements Functioning System Performance Test Validated System User Environment Accepted System Acceptance Test Installation Test Usable System Tests by client Tests by developer User’s understanding System in Use Tests (?) by user Software Engineering CSE470: Cheng 540 Fault Handling Techniques Fault Handling Fault Avoidance Design Methodology Verification Fault Detection Fault Tolerance Atomic Transactions Reviews Modular Redundancy Configuration Management Debugging Testing Component Testing Integration Testing Software Engineering CSE470: Cheng System Testing Correctness Debugging Performance Debugging 541 Quality Assurance encompasses Testing Quality Assurance Usability Testing Scenario Testing Fault Avoidance Verification Prototype Testing Product Testing Fault Tolerance Atomic Transactions Configuration Management Modular Redundancy Fault Detection Reviews Walkthrough Inspection Component Testing Software Engineering CSE470: Cheng Debugging Testing Integration Testing System Testing Correctness Debugging Performance Debugging 542 Component Testing Unit Testing: Individual subsystem Carried out by developers Goal: Confirm that subsystems is correctly coded and carries out the intended functionality Integration Testing: Groups of subsystems (collection of classes) and eventually the entire system Carried out by developers Goal: Test the interface among the subsystem Software Engineering CSE470: Cheng 543 System Testing System Testing: Acceptance Testing: The entire system Carried out by developers Goal: Determine if the system meets the requirements (functional and global) Evaluates the system delivered by developers Carried out by the client. May involve executing typical transactions on site on a trial basis Goal: Demonstrate that the system meets customer requirements and is ready to use Implementation (Coding) and testing go hand in hand Software Engineering CSE470: Cheng 544 Unit Testing Informal: Static Analysis: Incremental coding Hand execution: Reading the source code Walk-Through (informal presentation to others) Code Inspection (formal presentation to others) Automated Tools checking for syntactic and semantic errors departure from coding standards Dynamic Analysis: Black-box testing (Test the input/output behavior) White-box testing (Test the internal logic of the subsystem or object) Data-structure based testing (Data types determine test cases) Software Engineering CSE470: Cheng 545 Black-box Testing Focus: I/O behavior. If for any given input, we can predict the output, then the module passes the test. Almost always impossible to generate all possible inputs ("test cases") Goal: Reduce number of test cases by equivalence partitioning: Divide input conditions into equivalence classes Choose test cases for each equivalence class. (Example: If an object is supposed to accept a negative number, testing one negative number is enough) Software Engineering CSE470: Cheng 546 Black-box Testing (Continued) Selection of equivalence classes (No rules, only guidelines): Input is valid across range of values. Select test cases from 3 equivalence classes: Input is valid if it is from a discrete set. Select test cases from 2 equivalence classes: Below the range Within the range Above the range Valid discrete value Invalid discrete value Another solution to select only a limited amount of test cases: Get knowledge about the inner workings of the unit being tested => white-box testing Software Engineering CSE470: Cheng 547 White-box Testing Focus: Thoroughness (Coverage). Every statement in the component is executed at least once. Four types of white-box testing Statement Testing Loop Testing Path Testing Branch Testing Software Engineering CSE470: Cheng 548 White-box Testing (Continued) Statement Testing (Algebraic Testing): Test single statements (Choice of operators in polynomials, etc) Loop Testing: Path testing: Cause execution of the loop to be skipped completely. (Exception: Repeat loops) Loop to be executed exactly once Loop to be executed more than once Make sure all paths in the program are executed Branch Testing (Conditional Testing): Make sure that each possible outcome from a condition is tested at least once if ( i = TRUE) printf("YES\n"); else printf("NO\n"); Test cases: 1) i = TRUE; 2) i = FALSE Software Engineering CSE470: Cheng 549 White-box Testing Example FindMean(float Mean, FILE ScoreFile) { SumOfScores = 0.0; NumberOfScores = 0; Mean = 0; Read(Scor eFile, Score); /*Read in and sum the scores*/ while (! EOF(ScoreFile) { if ( Score > 0.0 ) { SumOfScores = SumOfScores + Score; NumberOfScores++; } Read(ScoreFile, Score); } /* Compute the mean and print the result */ if (NumberOfScores > 0 ) { Mean = SumOfScores/NumberOfScores; printf("The mean score is %f \n", Mean); } else printf("No scores found in file\n"); } Software Engineering CSE470: Cheng 550 White-box Example: Determining the Paths FindMean (FILE ScoreFile) { float SumOfScores = 0.0; int NumberOfScores = 0; 1 float Mean=0.0; float Score; Read(ScoreFile, Score); 2 while (! EOF(ScoreFile) { 3 if (Score > 0.0 ) { SumOfScores = SumOfScores + Score; NumberOfScores++; } 5 Read(ScoreFile, Score); 4 6 } /* Compute the mean and print the result */ 7 if (NumberOfScores > 0) { Mean = SumOfScores / NumberOfScores; printf(“ The mean score is %f\n”, Mean); } else printf (“No scores found in file\n”); 9 } 8 Constructing the Logic Flow Diagram Start 1 F 2 T 3 T F 5 4 6 7 T F 9 8 Exit Software Engineering CSE470: Cheng 552 Finding the Test Cases Start 1 a (Covered by any data) 2 b (Data set must contain at least one value) (Positive score) d c 4 (Data set must f be empty) 3 6 7 (Total score < 0.0) i 8 e (Negative score) 5 h (Reached if either f or g e is reached) j (Total score > 0.0) 9 k l Exit Software Engineering CSE470: Cheng 553 Test Cases Test case 1 : ? (To execute loop exactly once) Test case 2 : ? (To skip loop body) Test case 3: ?,? (to execute loop more than once) These 3 test cases cover all control flow paths Software Engineering CSE470: Cheng 554 Comparison of White & Blackbox Testing White-box Testing: Potentially infinite number of paths have to be tested White-box testing often tests what is done, instead of what should be done Cannot detect missing use cases Black-box Testing: Potential combinatorical explosion of test cases (valid & invalid data) Often not clear whether the selected test cases uncover a particular error Does not discover extraneous use cases ("features") Software Engineering CSE470: Cheng Both types of testing are needed White-box testing and black box testing are the extreme ends of a testing continuum. Any choice of test case lies in between and depends on the following: Number of possible logical paths Nature of input data Amount of computation Complexity of algorithms and data structures 555 The 4 Testing Steps 1. Select what has to be measured Completeness of requirements Code tested for reliability Design tested for cohesion 3. Develop test cases 2. Decide how the testing is done Code inspection Proofs Black-box, white box, Select integration testing strategy (big bang, bottom up, top down, sandwich) Software Engineering CSE470: Cheng A test case is a set of test data or situations that will be used to exercise the unit (code, module, system) being tested or about the attribute being measured 4. Create the test oracle An oracle contains of the predicted results for a set of test cases The test oracle has to be written down before the actual testing takes place 556 Guidance for Test Case Selection Use analysis knowledge about functional requirements (blackbox): Use cases Expected input data Invalid input data Use implementation knowledge about algorithms: Force division by zero Use sequence of test cases for interrupt handler Use design knowledge about system structure, algorithms, data structures (white-box): Control structures Test branches, loops, ... Data structures Test records fields, arrays, ... Software Engineering CSE470: Cheng 557 Unit-testing Heuristics 1. Create unit tests as soon as object design is completed: Black-box test: Test the use cases & functional model White-box test: Test the dynamic model Data-structure test: Test the object model 2. Develop the test cases Goal: Find the minimal number of test cases to cover as many paths as possible 3. Cross-check the test cases to eliminate duplicates Don't waste your time! Software Engineering CSE470: Cheng 4. Desk check your source code Reduces testing time 5. Create a test harness Test drivers and test stubs are needed for integration testing 6. Describe the test oracle Often the result of the first successfully executed test 7. Execute the test cases Don’t forget regression testing Re-execute test cases every time a change is made. 8. Compare the results of the test with the test oracle Automate as much as possible 558 Component-Based Testing Strategy The entire system is viewed as a collection of subsystems (sets of classes) determined during the system and object design. The order in which the subsystems are selected for testing and integration determines the testing strategy Big bang integration (Nonincremental) Bottom up integration Top down integration Sandwich testing Variations of the above For the selection use the system decomposition from the System Design Software Engineering CSE470: Cheng 559 Using the Bridge Pattern to enable early Integration Testing Use the bridge pattern to provide multiple implementations under the same interface. Interface to a component that is incomplete, not yet known or unavailable during testing VIP Seat Interface (in Vehicle Subsystem) Stub Code Software Engineering CSE470: Cheng Seat Implementation Simulated Seat (SA/RT) Real Seat 560 Example: Three Layer Call Hierarchy A C B E Layer I F Software Engineering CSE470: Cheng D Layer II G Layer III 561 Integration Testing: Big-Bang Approach Unit Test UI Don’t try this! Unit Test Billing Unit Test Learning Unit Test Event Service System Test PAID Unit Test Network Unit Test Database Software Engineering CSE470: Cheng 562 Bottom-up Testing Strategy The subsystem in the lowest layer of the call hierarchy are tested individually Then the next subsystems are tested that call the previously tested subsystems This is done repeatedly until all subsystems are included in the testing Special program needed to do the testing, Test Driver: A routine that calls a particular subsystem and passes a test case to it Software Engineering CSE470: Cheng 563 Bottom-up Integration A Layer I C B Test E E Test B, E, F F D G Layer II Layer III Test F Test C Test A, B, C, D, E, F, G Test D,G Test G Software Engineering CSE470: Cheng 564 Pros and Cons of bottom up integration testing Bad for functionally decomposed systems: Tests the most important subsystem last Useful for integrating the following systems Object-oriented systems real-time systems systems with strict performance requirements Software Engineering CSE470: Cheng 565 Top-down Testing Strategy Test the top layer or the controlling subsystem first Then combine all the subsystems that are called by the tested subsystems and test the resulting collection of subsystems Do this until all subsystems are incorporated into the test Special program is needed to do the testing, Test stub : A program or a method that simulates the activity of a missing subsystem by answering to the calling sequence of the calling subsystem and returning back fake data. Software Engineering CSE470: Cheng 566 Top-down Integration Testing A Layer I C B E Test A Test A, B, C, D F D G Layer II Layer III Test A, B, C, D, E, F, G Layer I Layer I + II All Layers Software Engineering CSE470: Cheng 567 Pros and Cons of top-down integration testing Test cases can be defined in terms of the functionality of the system (functional requirements) Writing stubs can be difficult: Stubs must allow all possible conditions to be tested. Possibly a very large number of stubs may be required, especially if the lowest level of the system contains many methods. One solution to avoid too many stubs: Modified top-down testing strategy Test each layer of the system decomposition individually before merging the layers Disadvantage of modified top-down testing: Both, stubs and drivers are needed Software Engineering CSE470: Cheng 568 Sandwich Testing Strategy Combines top-down strategy with bottom-up strategy The system is view as having three layers A target layer in the middle A layer above the target A layer below the target Testing converges at the target layer How do you select the target layer if there are more than 3 layers? Heuristic: Try to minimize the number of stubs and drivers Software Engineering CSE470: Cheng 569 Selecting Layers for the PAID system Top Layer: User Interface Middle Layer: Billing, Learning,Event Service Bottom Layer Network, Database Software Engineering CSE470: Cheng 570 Sandwich Testing Strategy A Layer I C B D Layer II Test E E Bottom Layer Tests F G Layer III Test B, E, F Test F Test D,G Test A, B, C, D, E, F, G Test G Top Layer Tests Test A Software Engineering CSE470: Cheng 571 Pros and Cons of Sandwich Testing Top and Bottom Layer Tests can be done in parallel Does not test the individual subsystems thoroughly before integration Solution: Modified sandwich testing strategy Software Engineering CSE470: Cheng 572 Modified Sandwich Testing Strategy Test in parallel: Middle layer with drivers and stubs Top layer with stubs Bottom layer with drivers Test in parallel: Top layer accessing middle layer (top layer replaces drivers) Bottom accessed by middle layer (bottom layer replaces stubs) Software Engineering CSE470: Cheng 573 Modified Sandwich Testing Strategy Double Test I A Layer I Test B C B D Layer II Test E Triple Test I Test B, E, F Triple Test I E F Double Test II Test D,G Test G Test A Test C Double Test I Layer III Double Test II Test F Test D G Test A, B, C, D, E, F, G Scheduling Sandwich Tests: Example of a Dependency Chart Unit Tests Double Tests Triple Tests SystemTests Steps in Component-Based Testing 1. Based on the integration strategy, select a component to . be tested. Unit test all the classes in the component. 2. Put selected component together; do any preliminary fixup necessary to make the integration test operational (drivers, stubs) 3. Do functional testing: Define test cases that exercise all uses cases with the selected component Software Engineering CSE470: Cheng 4. Do structural testing: Define test cases that exercise the selected component 5. Execute performance tests 6. Keep records of the test cases and testing activities. 7. Repeat steps 1 to 7 until the full system is tested. The primary goal of integration testing is to identify errors in the (current) component configuration. 576 Which Integration Strategy should you use? Factors to consider Amount of test harness (stubs &drivers) Location of critical parts in the system Availability of hardware Availability of components Scheduling concerns Bottom up approach good for object oriented design methodologies Test driver interfaces must match component interfaces ... Software Engineering CSE470: Cheng ...Top-level components are usually important and cannot be neglected up to the end of testing Detection of design errors postponed until end of testing Top down approach Test cases can be defined in terms of functions examined Need to maintain correctness of test stubs Writing stubs can be difficult 577 System Testing Functional Testing Structure Testing Performance Testing Acceptance Testing Installation Testing Impact of requirements on system testing: The more explicit the requirements, the easier they are to test. Quality of use cases determines the ease of functional testing Quality of subsystem decomposition determines the ease of structure testing Quality of nonfunctional requirements and constraints determines the ease of performance tests: Software Engineering CSE470: Cheng 578 Structure Testing Essentially the same as white box testing. Goal: Cover all paths in the system design Exercise all input and output parameters of each component. Exercise all components and all calls (each component is called at least once and every component is called by all possible callers.) Use conditional and iteration testing as in unit testing. Software Engineering CSE470: Cheng 579 Functional Testing . Essentially the same as black box testing Goal: Test functionality of system Test cases are designed from the requirements analysis document (better: user manual) and centered . around requirements and key functions (use cases) The system is treated as black box. Unit test cases can be reused, but in end user oriented new test cases have to be developed as well. 580 Software Engineering CSE470: Cheng Performance Testing Stress Testing Test the various software and hardware configurations Try to violate security requirements Software Engineering CSE470: Cheng Test reliability, maintain- ability & availability of the system Recovery testing Test backward compatibility with existing systems Security testing Test tolerances for heat, humidity, motion, portability Quality testing Evaluate response times and time to perform a function Environmental test Compatibility test Configuration testing Test what happens if large amounts of data are handled Timing testing Volume testing Stress limits of system (maximum # of users, peak demands, extended operation) Tests system’s response to presence of errors or loss of data. Human factors testing Tests user interface with user 581 Test Cases for Performance Testing Push the (integrated) system to its limits. Goal: Try to break the subsystem Test how the system behaves when overloaded. Try unusual orders of execution Call a receive() before send() Check the system’s response to large volumes of data Can bottlenecks be identified? (First candidates for redesign in the next iteration If the system is supposed to handle 1000 items, try it with 1001 items. What is the amount of time spent in different use cases? Are typical cases executed in a timely fashion? Software Engineering CSE470: Cheng 582 Acceptance Testing Goal: Demonstrate system is ready for operational use Choice of tests is made by client/sponsor Many tests can be taken from integration testing Acceptance test is performed by the client, not by the developer. Majority of all bugs in software is typically found by the client after the system is in use, not by the developers or testers. Therefore two kinds of additional tests: Alpha test: Software Engineering CSE470: Cheng Sponsor uses the software at the developer’s site. Software used in a controlled setting, with the developer always ready to fix bugs. Beta test: Conducted at sponsor’s site (developer is not present) Software gets a realistic workout in target environ- ment Potential customer might get discouraged 583 Testing has its own Life Cycle Establish the test objectives Design the test cases Write the test cases Test the test cases Execute the tests Evaluate the test results Change the system Do regression testing Software Engineering CSE470: Cheng 584 Test Team Professional Tester Programmer too familiar with code Analyst Test User Team System Designer Configuration Management Specialist Software Engineering CSE470: Cheng 585 Summary Testing is still a black art, but many rules and heuristics are available Testing consists of component-testing (unit testing, integration testing) and system testing Design Patterns can be used for componentbased testing Testing has its own lifecycle Software Engineering CSE470: Cheng 586