• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
SOFTWARE ENGINEERING
 

SOFTWARE ENGINEERING

on

  • 4,228 views

This is sofware engg , 3rd sem MBA , it has basics and important topics it will help you specially during exams ...all the best

This is sofware engg , 3rd sem MBA , it has basics and important topics it will help you specially during exams ...all the best

Statistics

Views

Total Views
4,228
Views on SlideShare
4,227
Embed Views
1

Actions

Likes
1
Downloads
118
Comments
1

1 Embed 1

http://www.docseek.net 1

Accessibility

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    SOFTWARE ENGINEERING SOFTWARE ENGINEERING Document Transcript

    • What is software?Computer programs and associated documentationSoftware products may be developed for a particular customer ormay be developed for a general market Software products may be•Generic - developed to be sold to a range of different customers•Bespoke (custom) - developed for a single customer according totheir specificationWhat is software engineering?Software engineering is an engineering discipline, which isconcerned with all aspects of software production Softwareengineers should adopt a systematic and organised approach totheir work and use appropriate tools and techniques depending onthe problem to be solved, the development constraints and theresources available.What is the difference between software engineering andcomputer science?Computer science is concerned with theory and fundamentals;software engineering is concerned with the practicalities ofdeveloping and delivering useful software Computer sciencetheories are currently insufficient to act as a completeunderpinning for software engineeringWhat is the difference between software engineering andsystem engineering?System engineering is concerned with all aspects of computer-based systems development including hardware, software andprocess engineering. Software engineering is part of this processSystem engineers are involved in system specification,architectural design, integration and deployment.What is a software process?A set of activities whose goal is the development or evolution ofsoftware Generic activities in all software processes are:
    • •Specification - what the system should do and its developmentconstraints•Development - production of the software system•Validation - checking that the software is what the customerwants•Evolution - changing the software in response to changingdemandsWhat is a software process model?A simplified representation of a software process, presented from aspecific perspectiveExamples of process perspectives are•Workflow perspective - sequence of activities•Data-flow perspective - information flow•Role/action perspective - who does what Generic process models•Waterfall•Evolutionary development•Formal transformation•Integration from reusable componentsWhat are the costs of software engineering?Roughly 60% of costs are development costs, 40% are testingcosts. For custom software, evolution costs often exceeddevelopment costs Costs vary depending on the type of systembeing developed and the requirements of system attributes such asperformance and system reliability Distribution of costs dependson the development model that is used.What are software engineering methods?Structured approaches to software development which includesystem models, notations, rules, design advice and processguidanceModel descriptions•Descriptions of graphical models, which should be producedRules
    • •Constraints applied to system modelsRecommendations•Advice on good design practice Process guidance•What activities to followWhat is CASE (Computer-Aided Software Engineering)?Software systems which are intended to provide automated supportfor software process activities. CASE systems are often used formethod support.Upper-CASE•Tools to support the early process activities of requirements anddesignLower-CASE•Tools to support later activities such as programming, debuggingand testingWhat are the attributes of good software?The software should deliver the required functionality andperformance to the user and should be maintainable, dependableand usableMaintainability•Software must evolve to meet changing needsDependability•Software must be trustworthyEfficiency•Software should not make wasteful use of system resourcesUsability•Software must be usable by the users for which it was designedWhat are the key challenges facing software engineering?Coping with legacy systems, coping with increasing diversity andcoping with demands for reduced delivery times Legacy systems•Old, valuable systems must be maintained and updatedHeterogeneity
    • •Systems are distributed and include a mix of hardware andsoftware Delivery•There is increasing pressure for faster delivery of softwareProfessional and ethical responsibilitySoftware engineering involves wider responsibilities than simplythe application of technical skills Software engineers must behavein an honest and ethically responsible way if they are to berespected as professionals Ethical behaviour is more than simplyupholding the law.Issues of professional responsibilityConfidentiality•Engineers should normally respect the confidentiality of theiremployers or clients irrespective of whether or not a formalconfidentiality agreement has been signed.Competence•Engineers should not misrepresent their level of competence.They should not knowingly accept work, which is out with, theircompetence.Intellectual property rights•Engineers should be aware of local laws governing the use ofintellectual property such as patents, copyright, etc. They should becareful to ensure that the intellectual property of employers andclients is protected.Computer misuse•Software engineers should not use their technical skills to misuseother people’s computers. Computer misuse ranges from relativelytrivial (game playing on an employer’s machine, say) to extremelyserious (dissemination of viruses).ACM/IEEE Code of EthicsThe professional societies in the US have cooperated to produce acode of ethical practice. Members of these organisations sign up to
    • the code of practice when they join.The Code contains eightPrinciples related to the behaviour of and decisions made byprofessional software engineers, including practitioners, educators,managers, supervisors and policy makers, as well as trainees andstudents of the profession.Code of ethics – preamblePreamble•The short version of the code summarizes aspirations at a highlevel of the abstraction;the clauses that are included in the fullversion give examples and details of how these aspirations changethe way we act as software engineering professionals. Without theaspirations, the details can become legalistic and tedious; withoutthe details, the aspirations can become high sounding but empty;together, the aspirations and the details form a cohesive code.•Software engineers shall commit themselves to making theanalysis, specification,design, development, testing andmaintenance of software a beneficial and respectedprofession. In accordance with their commitment to the health,safety and welfare of the public, software engineers shall adhere tothe following Eight Principles:Code of ethics – principles1. PUBLIC•Software engineers shall act consistently with the public interest.2. CLIENTS AND EMPLOYER•Software engineers shall act in a manner that is in the bestinterests of their client and employer consistent with the publicinterest.3. PRODUCT•Software engineers shall ensure that their products and relatedmodifications meet the highest professional standards possible.4. JUDGMENT•Software engineers shall maintain integrity and independence intheir professional judgment.5. MANAGEMENT
    • •Software engineering managers and leaders shall subscribe to andpromote an ethical approach to the management of softwaredevelopment and maintenance.6. PROFESSION•Software engineers shall advance the integrity and reputation ofthe profession consistent with the public interest.7. COLLEAGUES•Software engineers shall be fair to and supportive of theircolleagues.8. SELF•Software engineers shall participate in lifelong learning regardingthe practice of their profession and shall promote an ethicalapproach to the practice of the profession.Ethical dilemmasDisagreement in principle with the policies of senior managementYour employer acts in an unethical way and releases a safety-critical system without finishing the testing of the systemParticipation in the development of military weapons systems ornuclear systemsLecture - 2 Software ProcessesThe software processA structured set of activities required to develop a software system•Specification•Design•Validation / verification•EvolutionA software process model is an abstract representation of aprocess. It presents a description of a process from some particularperspective Models should be as simple as possible, but noSimpler. – A. Einstein
    • Models for fundamental process activitiesSoftware specification/requirements engineeringSoftware development (design and implementation)Software verification and validationSoftware evolutionSoftware specificationThe process of establishing what services are required and theconstraints on the system’s operation and developmentRequirements engineering process•Feasibility (technical and otherwise) study•Requirements elicitation and analysis•Requirements specification (documentation)•Requirements validationThe requirements engineering processFeasibility study Requirement solicitation and analysisrequirements specification Requirements validation Feasibilityreport System models User and system requirements RequirementsdocumentSoftware design and implementationThe process of producing an executable system based on thespecificationSoftware design – design a software structure that realizes thespecificationImplementation – translate this structure into an executableprogramThe activities of specification, design, and implementation areclosely related and may be inter-leaved.Design process activities“High-Level” design activities•Architectural design – subsystems and their relationships areidentified
    • •Abstract specification – of each sub-system’s services•Interface design – among sub-systems “Low-Level” designactivities•Component design – services allocated to different componentsand their interfaces are designed•Data structure design•Algorithm designThe software design process • Architectural design • Abstract specification • Interface design • Component design • Data structure • Design Algorithm • Design System architecture • Software specification • Interface specification • Component specification • Data structure specification • Algorithm specification • Requirements specification • Design activities • Design productsDesign methodsSystematic (canned) approaches to developing a software designThe design is usually documented as a set of graphical modelsPossible models•Data-flow model•Entity-relation-attribute model•Structural model•Object modelsProgramming and debugging
    • Translating a design into a program and removing errors from thatprogram (compare with Clean room SE) Programming is a“personal activity” – a there is no generic programming processProgrammers carry out some program testing to discover faults(“unit testing”), and remove faults in the debugging processThe debugging process Software verification & validation • Locate error • Design error repair • Repair error • Re-test program • Verification and validation (V&V) determines whether or not a system (1) conforms to its specification and (2) meets the needs of the customer. • Involves inspection / review processes and (machine-based) testing Testing involves executing system elements with test cases that are derived from specifications and/or program logic.Testing stagesUnit/Module testing - individual function/procedures are tested(unit/module) Integration testing Component testing - functionallyrelated units/modules are tested together (component) IntegrationtestingSub-system/product testing - sub-systems or products are tested(product/sub-system) Integration testing System testing - testing ofthe system as a whole, including user acceptance testSoftware evolutionSoftware is inherently flexible and subject to change. Asrequirements change through changing business circumstances, thesoftware that supports the business must also evolve and change.The distinction between development and evolution is increasinglyirrelevant as fewer and fewer systems are completely new.Assess existing systems
    • Define system requirementsPropose system changesModify systemsNew systemExisting systemsAutomated process support (CASE)Computer-aided software engineering (CASE) is software tosupport software development and evolution processes Activityautomation•Graphical editors for system model development•Data dictionaries for name management•GUI builders for user interface construction•Debuggers to support program faultfinding•Automated translators to generate new versions of a program(e.g., restructuring tools)CASE technologyCASE technology has led to significant improvements in thesoftware process, but not the order of magnitude improvementsthat were once predicted.•Software engineering involves design activity requiring creativethought – this is not readily automatable•Software engineering is a team activity and, for large projects,much time is spent in team interactions. CASE technology doesnot support this well.CASE classificationClassification helps us understand the different types of CASEtools / systems and their support for process activitiesFunctional perspective – tools are classified according to theirspecific functionProcess perspective – tools are classified according to processactivities that are supported
    • Integration perspective – CASE systems are classified according totheir breadth of support for the software processCASE integrationTools – support individual process tasks such as design consistencychecking, text editing, etc.Workbenches – support a process phase such as specification ordesign, Normally include a number of integrated toolsEnvironments – support all or a substantial part of an entiresoftware process. Normally include several integratedworkbenchesTools, workbenches, environmentsSingle-method workbenchesGeneral-purpose workbenchesMulti-method workbenchesLanguage-specific workbenchesAnalysis and Programming TestingdesignIntegrated environmentsProcess-centred environmentsFileEditors Compilers comparatorsTools Workbenches EnvironmentsCASE technologyLecture-3: Project Management
    • • Organizing, planning and scheduling software projectsSoftware project management• Concerned with activities involved in ensuring that software isdelivered on time, within budget and in accordance with therequirements of the organizations developing and procuring thesoftware.• Project management is needed because software development isalways subject to budget and schedule constraints that are set bythe organization developing the software.Software management distinctions• The product is intangible.• The product is uniquely flexible.• Software engineering is not recognized as an engineeringdiscipline with the same status as mechanical, electricalengineering, etc.• The software development process is notstandardized.• Many software projects are “one-off” projects.Management activities• Proposal writing (to fund new projects)• Project planning and scheduling• Project costing and preparing bids• Project monitoring and reviews• Personnel selection and evaluation• Report writing and presentations• Attending lots and lots of meetingsManagement commonalities
    • • These activities are not peculiar to softwaremanagement.• Many techniques of engineering project management are equallyapplicable to software project management.• Technically complex engineering systems tend to suffer frommost of the same problems as software systems.Project staffing• May not be possible to appoint the ideal people to work on aproject…•Project budget may not allow for use of highly paid staff.•Those with appropriate skills / experience may not be available.•An organization may wish to develop employee skills byassigning inexperienced staff.• Managers have to work within these constraints especially when(as is currently the case) there is an international shortage ofskilled IT staff.Project planning• Probably the most time-consuming project management activity(or at least it should be).• Continuous activity from initial concept to system delivery. Plansmust be regularly revised as new information becomes available.• Different types of sub-plans may be developed to support a mainsoftware project plan concerned with overall schedule and budget.Types of project sub-plansPlan DescriptionQuality plan Describes the quality procedures and standards that will be used in a projct.Validation plan Describes the approach, resources & schedule used for system validation .Configuration Describes the configuration mgmt
    • management plan procedure and structure to be used.Maintenance plan Predicts the maintenance requirements Of the system, maintenance costs and Effort requiredStaff development plan Describes how the skills and experience Of the project team members will be developed.Project planning• “The plan is nothing – the planning is everything.”Project planning processEstablish the project constraintsMake initial assessments of the project parametersDefine project milestones and deliverableswhile project has not been completed or cancelledDraw up project scheduleInitiate activities according to scheduleWait ( for a while )Review project progressRevise estimates of project parametersUpdate the project scheduleRe-negotiate project constraints and deliverablesif ( problems arise )thenInitiate technical review and possible revisionend ifend loopProject plan document structure:• Introduction (goals, constraints, etc.)• Project organisation• Risk analysis• Hardware and software resource requirements• Work breakdown
    • • Project schedule• Monitoring and reporting mechanismsActivity organization• Activities in a project should be associated with tangible outputsfor management to judge progress (i.e., to provide processvisibility)• Milestones are the unequivocal end-points of process activities.• Deliverables are project results delivered to customers. (Thereare also internal deliverables.)• The waterfall model allows for the straightforward definition ofmilestones (“a deliverable oriented model”).• Deliverables are always milestones, but milestones are notnecessarily deliverablesMilestones in the RE processProject scheduling• Split project into tasks and estimate time and resources requiredto complete each.• Tasks should not be too small or too large they should last on theorder of weeks for projects lasting months.• Organize as concurrent activities to make optimal use ofworkforce.• Minimize task dependencies to avoid potential delays.• Dependent on project managers’ intuition and experience
    • The project scheduling processScheduling problems• Estimating the difficulty of problems, and hence the cost ofdeveloping solutions, is hard.• Progress is generally not proportional to the number of peopleworking on a task.• Adding people to a late project can make it later. (due tocoordination overhead)• The unexpected always happens. Always allow for differentcontingencies in planning.Bar charts and activity networks• Graphical notations are often used to illustrate project schedules.• Activity charts (a.k.a. PERT* charts) show task dependencies,durations, and the critical path.• Bar charts (a.k.a. GANTT charts) generally show resource (e.g.,people) assignments and calendar time. • Program Evaluation and Review TechniqueTask durations and dependenciesTask Duration (days) DependenciesT1 8T2 15T3 15 T1 (M1)
    • T4 10T5 10 T2, T4 (M2)T6 5 T1, T2 (M3)T7 20 T1 (M1)T8 25 T4 (M5)T9 15 T3, T6 (M4)T10 15 T5, T7 (M7)T11 7 T9 (M6)T12 10 T11 (M8)Activity network
    • Risk management
    • • Risk management is concerned with identifying risks and drawingup plans to minimize their effect on a project.• A risk is a probability that some adverse circumstance will occur.•Project risks affect schedule or resources.•Product risks affect the quality or performance of the softwarebeing developed.•Business risks affect the organisation developing or procuring thesoftware. (Taxonomy based on Effect)Software risksRisk Risk type DescriptionStaff turnover Project Experienced staff will leave the projectbefore it is finished.Management change Project There will be a change oforganisational management with different priorities.Hardware unavailability Project Hardware which is essential forthe project will not be delivered on schedule.Requirements change Project and product There will be a largernumber of changes to the requirements than anticipated.Specification delays Project and product Specifications of essentialinterfaces are not available on scheduleSize underestimate Project and product The size of the system hasbeen underestimated.CASE tool underperformance Product CASE tools which supportthe project do not perform as anticipated • Technology change Business The underlying technology on which the system is built is superseded by new technology. • Product competition Business A competitive product is marketed before the system is completed.The risk management process• Risk identification – identify project, product and business risks• Risk analysis – assess the likelihood and consequences of theserisks
    • • Risk planning – draw up plans to avoid or minimise the effectsof the risk• Risk monitoring – monitor the risks throughout the projectRisk Risk analysis Risk planning identification Risk monitoringRisk identification• Technology risks• People risks• Organizational risks• Requirements risks• Estimation risks (Taxonomy based on Source)Risks and risk typesRisk type Possible risksTechnology : The database used in the system cannotprocess as many transactions per second as expected.Software components which should be reused containdefects which limit their functionality.People :It is impossible to recruit staff with the skills required.Key staff are ill and unavailable at critical times. Requiredtraining for staff is not available.Organisational :The organisation is restructured so thatdifferent management are responsible for the project.Organisational financial problems force reductions in theproject budget.Tools: The code generated by CASE tools is inefficient.CASE tools cannot be integrated.Requirements :Changes to requirements which requiremajor design rework are proposed. Customers fail tounderstand the impact of requirements changes.Estimation:The time required to develop the software isunderestimated. The rate of defect repair is underestimated.The size of the software is underestimated.Risk analysis• Assess probability and seriousness of each risk.
    • • Probability may be very low, low, moderate, high or very high.• Risk effects might be catastrophic, serious, tolerable orinsignificant.risk planning• Consider each risk and develop a strategy to manage that risk.• Avoidance strategies – the probability that the risk will arise isreduced.• Minimisation strategies – the impact of the risk on the project orproduct is• Contingency plans – if the risk arises, contingency plans areplans to deal withRisk Probability EffectRisk management strategiesRisk Strategy
    • Organisational financial problems : Prepare a briefingdocument for senior management showing how the project ismaking a very important contribution to the goals of theusiness.Recruitment problems:Alert customer of potential difficultiesand the possibility of delays, investigate buying-incomponents.Staff illness: Reorganise team so that there is more overlapof work and people therefore understand each other’s jobs.Defective components:Replace potentially defectivecomponents with bought-in components of known reliability.Requirements changes: Derive traceability information toassess requirements change impact, maximize informationhiding in the design.Organisational restructuring: Prepare a briefing document forsenior management showing how the project is making avery important contribution to the goals of the business.Database performance :Investigate the possibility of buyinga higher-performance database.Underestimated development time:Investigate buying incomponents, investigate use of a program generator.Risk type Potential indicatorsTechnology : Late delivery of hardware or support software,many reported technology problemsPeople: Poor staff morale, poor relationships amongst teammember, job availabilityOrganisational :organisational gossip, lack of action bysenior managementTools: reluctance by team members to use tools, complaintsabout CASE tools, demands for higher-poweredworkstationsRequirements: many requirements change requests,customer complaints Estimation failure to meet agreedschedule, failure to clear reported
    • DefectsLecture-4: Software RequirementsRequirements engineering• The process of eliciting, analysing, documenting, and validatingthe servicesrequired of a system and the constraints under which it willoperate and bedeveloped.• Descriptions of these services and constraints are therequirements for thesystem.• Requirements may be high-level and abstract, or detailed andmathematical• The hardest single part of building a software system is decidingprecisely what tobuild. No other part of the conceptual work is as difficult… Noother part of thework so cripples the resulting system if done wrong. No other partis moredifficult to rectify later.– Fred Brooks, “No Silver Bullet…”Why is Requirements Engineering so hard?• Difficulty of anticipation• Unknown or conflicting requirements / priorities• Conflicts between users and procurers• Fragmented nature of requirements• Complexity / number of distinct requirements• Some analogies:_Working a dynamically changing jigsaw puzzle _Blind men describing an elephant _Different medical specialists describing an ill patient Types of requirements • Requirements range from being high-level and abstract to detailed and
    • mathematical.• This is inevitable as requirements may serve multiple uses._May be the basis for a bid for a contract – must be open to interpretation _May be the basis for the contract itself -- must be defined in detail _May be the basis for design and implementation – must bridge requirements engineering and design activities • User requirements – statements in natural language plus diagrams of system services and constraints. Written primarily for customers. • System requirements – structured document setting out detailed descriptions of services and constraints precisely. May serve as a contract between client and developer. • Software design specification – implementation oriented abstract description of software design, which may utilize formal (mathematical) notations. Written for developers. User and system requirements t 1 e . r T s h e e l s
    • cotfstwaanreimounstrpprroevsiednetanmea
    • annseotferneaplrefsielnet,intgha1n.d21.
    • eafceccetssoifngteaxttesrenlaelcfiioln
    • esicrteoataepdpbyyohtehetrotlooalsss.o1c.
    • i1aTehdeuistehrshheoutlydpbeeofp1r.o2vitdh
    • eedwxittehrfaalcifliilteietsottohdeffii
    • lneetehpertsyepnetodeonbef1b.y2ehxetesre
    • nlaelcfeidleisc.o1n.eerett.ttwtrtxesentinganaspecificicon2 oolwhichmayEachexter
    • nalfiletypema1.21.31.21.41.21.5yhaveanassociatedappliedtothefile.Eachexternal filetypemayberepresentedastheuser’sdisplay.Facilities shoexternWfhenala
    • fileushnuldbtypeeeptorobevidedforthdecsfinedbeleyeiconretheuisegor.prRequirements readersClient managersSystem end-usersClient engineersContractor managersSystem architectsSystem end-usersClient engineers
    • System architectsSoftware developersClient engineers (perhaps)SystemarchitectsUser requirementsSystem requirementsSoftware designFunctional and non-functional requirements• Functional requirements – services the system should provide,how it should reactto particular inputs, or how it should behave in particularsituations.• Non-functional requirements – constraints on services orfunctions (e.g., responsetime) or constraints on development process (e.g., use of aparticular CASEtoolset).• Domain requirements – functional or non-functionalrequirements derived fromapplication domain (e.g., legal requirements or physical lawsExamples of functional requirements• The user shall be able to search either all of the initial set ofdatabases or select asubset from it.• The system shall provide appropriate viewers for the user to readdocuments inthe document store.• Every order shall be allocated a unique identifier (ORDER_ID),which the usershall be able to copy to the account’s permanent storage areaRequirements imprecision• Problems arise when requirements are not precisely stated.• Ambiguous requirements may be interpreted in different ways.• Consider the term “appropriate viewers”
    •  _User intention – special purpose viewer for each different document type  _Developer interpretation – provide a text viewer that shows the contents of the documents Requirements completeness and consistency • In principle, a requirements specification should be both complete and consistent.  _Complete – all required services and constraints are defined.  _Consistent – no conflicts or contradictions in the requirements. • In practice, this is nearly impossible. Non-functional requirements • Define system attributes (e.g., reliability, response time) and constraints (e.g., MTTF ≥ 5K transactions, response time ≤ 2 seconds). • Attributes are often emergent system properties – i.e., only observable when the entire system is operational. • Process constraints may mandate a particular CASE system, programming language, or development method. • Non-functional requirements may be more critical than functional requirements. If not met, the system may be useless. Non-functional classifications • Product requirements – specify product behaviour • Organizational requirements – derived from policies / procedures in customer’s or developer’s organization (e.g., process constraints) • External requirements – derived from factors external to the product and its development process (e.g., interoperability requirements, legislative requirements) Non-functional classifications U il
    • rPerformancerequirementsSpacerequirementssab ityequirementsEf ficiencyrequirementsReliabilityrequirementsPortabilityrequirementsInteroperabilityrequirementsEthicalrequirementsLegislativerequirementsImplementationrequirementsStandardsrequirementsDeliveryrequirementsSafetyrequirementsPrivacyrequirementsProductrequirementsOr ganizationalrequirementsExternalrequirements
    • Non-functionalrequirementsExamples• Product requirement:4.C.8 it shall be possible for all necessary communication betweenthe APSE andthe userto be expressed in the standard Ada character set.• Organisational requirement:9.3.2 the system development process and deliverable documentsshall conform totheprocess and deliverables defined in XYZCo-SP-STAN-95.• External requirement:7.6.5 the system shall not disclose any personal information aboutcustomersapart fromtheir name and reference number to the operators of the system.Goals versus requirements• General goals such as “system should be user friendly” or“system should havefast response time” are not verifiable.• Goals should be translated into quantitative requirements thatcan be objectivelytested.Examples• A system goal: The system should be easy to use by experiencedcontrollers andshould be organized in such a way that user errors are minimized.• A verifiable non-functional requirement: Experiencedcontrollers shall be ableto use all the system functions after a total of two hours training.After thistraining, the average number of errors made by experienced usersshall not
    • exceed two per day.Requirements measuresRequirement interactionsProperty MeasureSpeed Processed transactions/secondUser/Event response timeScreen refresh timeSize K BytesNumber of RAM chipsEase of use Training timeNumber of help framesReliability Mean time to failureProbability of unavailabilityRate of failure occurrenceAvailabilityRobustness Time to restart after failurePercentage of events causing failureProbability of data corruption on failurePortability Percentage of target dependent statementsNumber of target systems• Competing / conflicting requirements are common with complexsystems.• Spacecraft system example:_To minimize weight, the number of chips in the unit should be minimized. _To minimize power consumption, low-power chips should be used. _But using low-power chips means that more chips have to be used. Which is the most critical requirement? • For this reason, preferred points in the solution space should be identified. Domain requirements • Derived from the application domain rather than user needs.
    • • May be new functional requirements or constraints on existingrequirements.• If domain requirements are not satisfied, the system may beunworkable.Library system domain requirements• There shall be a standard user interface to all databases, whichshall be based onthe Z39.50 standard.• Because of copyright restrictions, some documents must bedeleted immediatelyon arrival. Depending on the user’s requirements, thesedocuments will either beprinted locally on the system server for manually forwarding to theuser or routedto a network printer.Train protection system domain requirement• The deceleration of the train shall be computed as: _Dtrain = Dcontrol + Dgradient where Dgradient is 9.81m/s2 * compensated gradient/alpha and where the values of 9.81m/s2 /alpha are known for different types of train. Domain requirements problems • Understandability – requirements are expressed in the language of the application domain and may not be understood by software engineers. • Implicitness – domain experts may not communicate such requirements because they are so obvious (to the experts). User requirements “shoulds” • Should be understandable by system users who don’t have detailed technical knowledge. • Should only specify external system behaviour.
    • • Should be written using natural language, forms, and simpleintuitive diagrams.Some potential problems with using natural language• Lack of clarity – expressing requirements precisely is difficultwithout makingthe document wordy and difficult to read.• Requirements confusion – functions, constraints, goals, anddesign info may notbe clearly distinguished.• Requirements amalgamation – several different requirementsmay be lumpedtogether.Guidelines for writing user requirements• Adopt a standard format and use it for all requirements.• Use language in a consistent way. E.g., use shall for mandatoryrequirements,should for desirable requirements.• Use text highlighting to identify key parts of the requirement.• Avoid the use of computer jargon.System requirements• More detailed descriptions of user requirements• May serve as the basis for a contract• Starting point for system design & implementation• May utilize different system models such as object or dataflowSystem requirements and design information• In principle, system requirements should state what the systemshould do, and nothow it should be designed.• In practice, however, some design info may be incorporated,since:_Sub-systems may be defined to help structure the requirements. _Interoperability requirements may constrain the design. _Use of a specific design model may be a requirement MORE potential problems with using natural language
    • • Ambiguity – the readers and writers of a requirement mustinterpret the samewords in the same way. NL is naturally ambiguous so this is verydifficult.• Over-flexibility – the same requirement may be stated in anumber of differentways. The reader must determine when requirements are the sameand when theyare different.• Lacks of modularisation – NL structures are inadequate tostructure systemrequirements sufficiently.Alternatives to NL specificationNotation DescriptionStructurednaturallanguageThis approach depends on defining standard forms ortemplates to express the requirements specification.DesigndescriptionlanguagesThis approach uses a language like a programminglanguage but with more abstract features to specify therequirements by defining an operational model of thesystem.GraphicalnotationsA graphical language, supplemented by text annotations isused to define the functional requirements for the system.An early example of such a graphical language was SADT(Ross, 1977; Schoman and Ross, 1977). More recently,use-case descriptions (Jacobsen, Christerson et al., 1993)have been used. I discuss these in the following chapter.Mathematical
    • specificationsThese are notations based on mathematical conceptssuch as finite-state machines or sets. These unambiguousspecifications reduce the arguments between customerand contractor about system functionality. However, mostcustomers don’t understand formal specifications and arereluctant to accept it as a system contract. I discuss formalspecification in Chapter 9.Program Description Languages (PDLs)• Requirements are specified operationally using pseudo-code.• Shows what is required by illustrating how the requirementscould be satisfied.• Especially useful when specifying a process that involves anordered sequence ofactions, or when describing hardware and software interfaces.Part of an ATM specificationclass ATM {// declarations herepublic static void main (String args[]) throws InvalidCard {try {thisCard.read () ; // may throw InvalidCard exceptionpin = KeyPad.readPin () ; attempts = 1 ;while ( !thisCard.pin.equals (pin) & attempts < 4 ){ pin = KeyPad.readPin () ; attempts = attempts + 1 ;}if (!thisCard.pin.equals (pin))throw new InvalidCard ("Bad PIN");thisBalance = thisCard.getBalance () ;do { Screen.prompt (" Please select a service ") ;service = Screen.touchKey () ;switch (service) {case Services.withdrawalWithReceipt:receiptRequired = true ;PDL disadvantages
    • • PDL may not be sufficiently expressive to illustrate requirementsin a concise anunderstandable way.• Notation is only understandable to people with programminglanguageknowledge.• The specification may be taken as a design prescription ratherthan a model tofacilitate requirements understanding.Interface specification• Used to specify operating interfaces with other systems. _Procedural interfaces  _Data structures that are exchanged  _Data representations • Also used to specify functional behaviour. • Formal notations are effective for interface specification – e.g., pre- and postconditions PDL interface description Example: interface and operational specifications of a function interface PrintServer { // defines an abstract printer server // requires: interface Printer, interface PrintDoc // provides: initialize, print, displayPrintQueue, cancelPrintJob, switchPrinter void initialize ( Printer p ) ; void print ( Printer p, PrintDoc d ) ; void displayPrintQueue ( Printer p ) ; void cancelPrintJob (Printer p, PrintDoc d) ; void switchPrinter (Printer p1, Printer p2, PrintDoc d) ; } //PrintServer Function: Set BIG to the largest value in array A [1.. N] Interface specification: pre-condition: N ≥ 1 post-condition: there exists an i in [1,N] such that BIG=A [i] & for every in
    • [1,N], BIG ≥ A [j] & A is unchangedOperational specification:if N ≥ 1 then doBIG: = A [1]for i = 2 to N doif A [i] > BIG then BIG: = A [i] end ifend forend ifThe requirements document (SRS)• The official statement of what is required of the systemdevelopers.• Should include both user and system requirements.• NOT a design document. As much as possible, it should set outWHAT thesystem should do rather than HOW it should do it.Users of a requirements documentUs e t he req ui rem ent sd oc um e n t to pl a n a bi d forS peci fy t he req uirem en ts andread th em to c h eck t ha t t heym e e t th e ir n eeds . Th eys pe c ify c h ang es to th erequ irem en tsS y stem c us to m e rsRequirements document requirements• Specify external system behaviour• Specify implementation constraints• Easy to change (!)• Serve as reference tool for maintenance• Record forethought about the life cycle of the system i.e. predictchanges• Characterise responses to unexpected eventsIEEE requirements standard• Introduction• General description
    • • Specific requirements• Appendices• Index• This is a generic structure that must be instantiated for specificsystemsRequirements document structure• Preface (readers, version, change history)• Introduction• Glossary• User requirements definition• System requirements specification• System models• System evolution• Appendices• IndexKey points• Requirements set out what the system should do and defineconstraints on itsoperation and implementation.• Functional requirements set out services the system shouldprovide• Non-functional requirements constrain the system beingdeveloped or thedevelopment process• User requirements are high-level statements of what the systemshould do• User requirements should be written in natural language, tablesand diagrams.• System requirements are intended to communicate the functionsthat the systemshould provide.• System requirements may be written in structured naturallanguage, a PDL or in aformal language.
    • • A software requirements document (SRS) is the agreed statementof systemrequirementsActivitiesActivity 1:- Discuss the problems of using natural language fordefining user and systemrequirements and show, using small examples, how structuringnatural language intoforms can help avoid some of these difficulties.Activity 2:- Discuss ambiguities or omissions in the followingstatements ofrequirements for part of a ticket issuing system.An automated ticket issuing system sells rail tickets. Users selecttheir destination,and input a credit card and a personal identification number. Therail ticket is issued andtheir credit card account charged with its cost. When the userpresses the start button, amenu display of potential destinations is activated along with amessage to the user toselect a destination. Once a destination has been selected, users arerequested to inputtheir credit card. Its validity is checked and the user is thenrequested to input a personalidentifier. When the credit transaction has been validated, theticket is issued.Activity 3:- Rewrite the above description using the structuredapproach described in thischapter. Resolve the identified ambiguities in some appropriateway.Activity 4:- Write system requirements for the above system usinga Java based notation.You may make any reasonable assumptions about the system. Payparticular attention tospecifying user errors.
    • Activity 5:- Using the technique suggested here where naturallanguage is presented in astandard way, write plausible user requirements for the followingfunctions:• An unattended petrol (gas) pump system that includes a creditcard reader. Thecustomer swipes the card through the reader then specifies theamount of fuelrequired. The fuel is delivered and the customer’s account debited.• The cash dispensing functioning a bank auto teller machine.• The spell checking and correcting functioning a word processor.Activity 6:- Describe three different types of non-functionalrequirement, which may beplaced on a system. Give examples of each of these types ofrequirement.Activity 7:- Write a set of non-functional requirements for theticket issuing systemdescribed above, setting out its expected reliability and its responsetime.Activity 8:- You have taken a job with a software user who hascontracted your previousemployer to develop a system for them. You discover that yourcompan7y’sinterpretation of the requirements is different form theinterpretation taken by yourprevious employer. Discuss what you should do in such a situation.You know that thecosts to your current employer will increases in the ambiguities arenot resolved. Youhave also a responsibility of confidentiality to your previousemployer.Lecture-5: Requirements Engineering ProcessObjectives• To describe the principal requirements engineering activities
    • • To introduce techniques for requirements elicitation andanalysis• To describe requirements validation• To discuss the role of requirements management in support ofotherrequirements engineering processesTopics covered• Feasibility studies• Requirements elicitation and analysis• Requirements validation• Requirements managementRequirements engineering processes• The processes used for RE vary widely depending on theapplication domain,the people involved and the organization developing therequirements.• However, there are a number of generic activities common tomost processes: _Feasibility study  _Requirements elicitation and analysis  _Requirements specification  _Requirements validation Feasibility study • Determines whether or not the proposed undertaking is worthwhile. • Aims to answer three basic questions:  _Would the system contribute to overall organizational objectives?  _Could the system be engineered using current technology and within budget?  _Could the system be integrated with other systems already in use? Feasibility study issues • How would the organization cope if the system weren’t implemented?
    • • What are the current process problems and how would thesystem help withthese?• What will the integration problems be?• Is new technology needed? New skills?• What must be supported by the system, and what need not besupported?Elicitation and analysis• Involves working with customers to learn about the applicationdomain, theservices needed and the system’s operational constraints.• May also involve end-users, managers, maintenancepersonnel, domainexperts, trade unions, etc. (That is, any stakeholders.)Problems of elicitation and analysis• Getting all, and only, the right people involved.• Stakeholders often don’t know what they really want (“I’llknow when I see it”).• Stakeholders express requirements in their own terms.• Stakeholders may have conflicting requirements.• Requirements change during the analysis process. Newstakeholders may emerge and the business environment mayevolve.• Organizational and political factors may influence the systemrequirements.The elicitation and analysis processViewpoint-oriented elicitation• Stakeholders represent different ways of looking at a problem(viewpoints)• A multi-perspective analysis is important, as there is no singlecorrect way toanalyse system requirements.• Provides a natural way to structure the elicitation process.Types of viewpoints
    • • Data sources or sinks – viewpoints are responsible for producingor consumingdata. Analysis involves checking that assumptions about sourcesand sinks arevalid.• Representation frameworks – viewpoints represented bydifferent system models(i.e., dataflow, ER, finite state machine, etc.). Each model yieldsdifferentinsights into the system.• Receivers of services – viewpoints are external to the systemand receiveservices from it. Natural to think of end-users as external servicereceivers.Method-based RE• “Structured methods” to elicit, analyse, and documentrequirements.• Examples include:_Ross’ Structured Analysis (SA), _Volere Requirements Process (www.volere.co.uk) _Knowledge Acquisition and Sharing for Requirement Engineering (KARE) (www.kare.org), _Somerville’s Viewpoint-Oriented Requirements Definition (VORD), and _The baut’s Scenario-Based Requirements Engineering (SBRE)_ Volere Requirements Process Volere requirement shell KARE workbench architecture Somerville’s VORD method VORD standard forms Scenarios • Depict examples or scripts of possible system behaviour. • People often relate to these more readily than to abstract statements of
    • requirements.• Particularly useful in dealing with fragmentary, incomplete, orconflictingrequirements.Scenario descriptions• System state at the beginning of the scenario.• Sequence of events for a specific case of some generic task thesystem is requiredto accomplish.• Any relevant concurrent activities.• System state at the completion of the scenario.A simple scenario• t0: The user enters values for input array A. The values are [1, 23,-4, 7, 19]. Thevalue of output variable BIG remains ‘undefined’.• t1: The user executes program MAX.• t2: The value of variable BIG is 23 and the values of A are [1, 23,-4, 7, 19].Scenario-Based Requirements Engineering (SBRE)• Marcel support environment allows rapid construction of anoperationalspecification of the desired system and its environment.• Based on a forward chaining rule-based language.• An interpreter executes the specification to produce naturallanguage basedscenarios of system behavior.SBRE rule templateSBRE scenario generationScenario representation in VORD• VORD supports the graphical description of multi-threaded“event scenarios” todocument system behaviour:_Data provided and delivered _Control information _Exception processing
    • _The next expected event • Multi-threading supports description of exceptions. Scenario for a “start transaction” event UML use-cases and sequence diagrams • Use-cases are a graphical notation for representing abstract scenarios in the UML. • They identify the actors in an interaction and describe the interaction itself. • A set of use-cases should describe all types of interactions with the system. • Sequence diagrams may be used to add detail to use-cases by showing the sequence of event processing. Library use-cases Catalogue management sequence diagram Social and organizational factors • All software systems are used in a social and organizational context. This can influence or even dominate the system requirements. • Good analysts must be sensitive to these factors, but there is currently no systematic way to tackle their analysis. Example • Consider a system, which allows senior management to access information without going through middle managers. • Managerial status. Senior managers may feel that they are too important to use a keyboard. This may limit the type of system interface used. • Managerial responsibilities. Managers may have no uninterrupted time when they can learn to use the system • Organizational resistance. Middle managers who will be made redundant may
    • deliberately provide misleading or incomplete information so thatthe system willfail.Ethnography• A social scientists spends considerable time observing andanalysing how peopleactually work.• People do not have to explain or articulate what they do.• Social and organizational factors of importance may be observed.• Ethnographic studies have shown that work is usually richerand more complexthan suggested by simple system models.Focused ethnography• Developed during a project studying the air traffic controlprocess.• Combines ethnography with prototyping.• Prototype development raises issues, which focus theethnographic analysis.• Problem with ethnography alone: it studies existing practices,which may not berelevant when a new system is put into place.Requirements validation• Concerned with whether or not the requirements define a systemthat the customerreally wants.• Requirements error costs are high, so validation is veryimportant. (Fixing arequirements error after delivery may cost up to 100 times that offixing an errorduring implementation.)Requirements checking• Validity. Does the system provide the functions which bestsupport thecustomer’s needs?• Consistency. Are there any requirements conflicts?
    • • Completeness. Are all functions required by the customerincluded?• Realism. Can the requirements be implemented given availablebudget andtechnology?• Verifiability. Can the requirements be tested?Requirements validation techniques• Requirements reviews / inspections – systematic manual analysisof therequirements.• Prototyping – using an executable model of the system to checkrequirements.• Test-case generation – developing tests for requirements to checktestability.• Automated consistency analysis – checking the consistency of astructuredrequirements description.Requirements reviews / inspections• Regular reviews should be held while the requirements definitionis beingformulated.• Both client and contractor staff should be involved in reviews.(Stakeholders)• Reviews may be formal (with completed documents) orinformal. Goodcommunications between developers, customers and users canresolve problemsat an early stage.Review check-list• Verifiability. Is the requirement realistically testable?• Comprehensibility. Is the requirement properly understood?• Traceability. Is the origin of the requirement clearly stated?• Adaptability. Can the requirement be changed with minimumimpact on otherrequirements? (Especially when change is anticipated!)
    • Requirements management• Requirements management is the process of managing changingrequirementsduring the requirements engineering process and systemdevelopment.• New requirements emerge during the process as business needschange and abetter understanding of the system is developed.• The priority of requirements from different viewpoints changesduring thedevelopment process.• The business and technical environment of the system changesduring itsdevelopment.Enduring and volatile requirements• Enduring requirements. Stable requirements derived from thecore activity of thecustomer organization. E.g., a hospital will always have doctors,nurses, etc.May be derived from domain models.• Volatile requirements. Requirements which change duringdevelopment or whenthe system is in use. E.g., requirements derived from the latesthealth-care policy.Classification of requirements• Mutable requirements – those that change due to changes in thesystem’senvironment.• Emergent requirements – those that emerge as understanding ofthe systemdevelops.• Consequential requirements – those that result from theintroduction of thesystem.
    • • Compatibility requirements – those that depend on other systemsororganizational processes.Requirements management planning• During requirements management planning, you must decide on:_Requirements identification – how requirements will be individually identified.  _A change management process – a process to be followed when analysing the impact and costs of a requirements change.  _Traceability policies – the amount of information about requirements relationships that is maintained.  _CASE tool support – the tool support required to help manage requirements change. Traceability • Traceability is concerned with the relationships between requirements, their sources, and the system design. • Source traceability – links from requirements to stakeholders who proposed these requirements. • Requirements traceability – links between dependent requirements. • Design traceability – links from the requirements to the design. CASE tool support • Requirements storage – requirements should be managed in a secure, managed data store. • Change management – the process of change management is a workflow process whose stages can be defined and information flow between the stages partially automated.
    • • Traceability management – automated discovery anddocumentation ofrelationships between requirementsRequirements change management• Should apply to all proposed changes to the requirements.• Principal stages:_Problem analysis – discuss identified requirements problem and propose specific change(s). _Change analysis and costing – assess effects of change on other requirements. _Change implementation – modify requirements document and others to reflect change. Requirements change management Key points • The requirements engineering process includes a feasibility study, elicitation and analysis, specification, and validation. • Requirements analysis is an iterative process involving domain understanding, requirements collection, classification, structuring, prioritization and validation. • Systems have multiple stakeholders with different viewpoints and requirements. • Social and organization factors influence system requirements. • Requirements validation is concerned with checks for validity, consistency, complete-ness, realism, and verifiability. • Business, organizational, and technical changes inevitably lead to changing requirements. • Requirements management involves careful planning and a change management process.
    • ActivitiesActivity 1:- Suggest who might be stakeholders in a universitystudent records system.Explain why it is almost inevitable that the requirements ofdifferent stakeholders willconflict in some ways.Activity 2:- A software system is to be developed to automate alibrary catalogue. Thissystem will contain information about all the books in a library andwill be usable bylibrary staff and by book borrows and reasons the system shouldsupport cataloguebrowsing, querying, and should provide facilities allowing users tosend messages tolibrary staff reserving a book which is on loan. Identify theprincipal viewpoints, whichmight be taken into account in the specification of this system andshow theirrelationships using a viewpoint hierarchy diagram.Activity 3:- For three of the viewpoints identified in the librarycataloguing system,suggest services which might be provided to that viewpoint, datawhich the viewpointmight provide and events which control the delivery of theseservices.Activity 4 :- Using your own knowledge of how an ATM is used,develop a set of usecases that could be used to derive the requirements for an ATMsystem.Activity 5:- Discuss an example of a type of system where socialand political factorsmight strongly influence the system requirements. Explain whythese factors areimportant in your example.
    • Activity 6:- Who should be involved in a requirements review?Draw a process modelshowing how a requirements review might be organized.Activity 7:- Why do tractability matrices become difficult tomange when there are manysystem requirements? Design a requirements structuringmechanism, based onviewpoints, which might help reduce the scale of this problem.Activity 8:- When emergency changes have to be made to systemsoftware may have tobe modified before changes to the requirements have beenapproved. Suggest a model ofa process for making these modifications, which ensures that therequirements documentand the system implementation do not become inconsistent.Activity 9:- Your company uses a standard analysis method whichis normally applied inall requirements analyses. In your work, you find that this methodcannot represent socialfactors, which are significant in the system you are analyzing. Youpoint out to yourmanager who makes clear that the standard should be followed.Discuss what you shoulddo in such a situations.Lecture-6: System models• Abstract descriptions of systems whose requirementsare beinganalysedObjectives• To explain why the context of a system should be modelled aspart of the REprocess• To describe behavioural modelling, data modelling and objectmodelling
    • • To introduce some of the notations used in the Unified ModellingLanguage(UML)• To show how CASE workbenches support system modellingTopics covered• Context models• Behavioural models• Data models• Object models• CASE workbenchesSystem modelling• System modelling helps the analyst to understand thefunctionality of the systemand models are used to communicate with customers• Different models present the system from different perspectives•External perspective showing the system’s context or environment•Behavioural perspective showing the behaviour of the system•Structural perspective showing the system or data architectureStructured methods• Structured methods incorporate system modelling as an inherentpart of themethod• Methods define a set of models, a process for deriving thesemodels and rules andguidelines that should apply to the models• CASE tools support system modelling as part of a structuredmethodMethod weaknesses• They do not model non-functional system requirements• They do not usually include information about whether a methodis appropriatefor a given problem• The may produce too much documentation• The system models are sometimes too detailed and difficult forusers to
    • understandModel types• Data processing model showing how the data is processed atdifferent stages• Composition model showing how entities are composed of otherentities• Architectural model showing principal sub-systems• Classification model showing how entities have commoncharacteristics• Stimulus/response model showing the system’s reaction to eventsContext models• Context models are used to illustrate the boundaries of a system• Social and organisational concerns may affect the decision onwhere to positionsystem boundaries• Architectural models show the a system and its relationship withother systemsThe context of an ATM systemAuto-tellersystemSecuritysystemMaintenancesystemUsagedatabaseBranchcountersystemBranchaccountingsystemAccountdatabaseProcess models
    • • Process models show the overall process and the processes thatare supported bythe system• Data flow models may be used to show the processes and theflow of informationfrom one process to anotherEquipment procurement processGet costestimatesAcceptdelivery ofequipmentCheckdelivereditemsValidatespecificationSpecifyequipmentrequiredChoosesupplierPlaceequipmentorderInstallequipmentFindsuppliersSupplierdatabaseAcceptdeliveredequipmentEquipment
    • databaseEquipmentspec.Checkedspec.DeliverynoteDeliverynoteOrdernotificationInstallationinstructionsInstallationacceptanceEquipmentdetailsChecked andsigned order formOrderdetails +Blank orderformSpec. +supplier +estimateSupplier listEquipmentspec.Behavioural models• Behavioural models are used to describe the overall behaviour ofa system• Two types of behavioural model are shown here•Data-processing models that show how data is processed as itmoves through
    • the system•State machine models that show the systems response to events• Both of these models are required for a description of thesystem’s behaviourData-processing models• Data flow diagrams are used to model the system’s dataprocessing• These show the processing steps as data flows through a system• Intrinsic part of many analysis methods• Simple and intuitive notation that customers can understand• Show end-to-end processing of dataOrder processing DFDCompleteorder formOrderdetails +blankorder formValidateorderRecordorderSend tosupplierAdjustavailablebudgetBudgetfileOrdersfileCompletedorder formSignedorder form
    • Signedorder formChecked andsigned order+ ordernotificationOrderamount+ accountdetailsSignedorder formOrderdetailsData flow diagrams• DFDs model the system from a functional perspective• Tracking and documenting how the data associated with aprocess is helpful todevelop an overall understanding of the system• Data flow diagrams may also be used in showing the dataexchange between asystem and other systems in its environmentCASE toolset DFDDesigneditorDesigncross checkerDesignanalyserReportgeneratorDesigndatabaseCode skeletongenerator
    • DesigndatabaseInputdesignValiddesignCheckeddesignDesignanalysisUserreportandReferenceddesignsCheckeddesign OutputcodeState machine models• These model the behaviour of the system in response to externaland internalevents• They show the system’s responses to stimuli so are often used formodelling realtimesystems• State machine models show system states as nodes and events asarcs betweenthese nodes. When an event occurs, the system moves from onestate to another• State charts are an integral part of the UMLMicrowave oven modelFull powerEnableddo: operateoven
    • FullpowerHalfpowerHalfpowerFullpowerNumberTimerDooropenDoorclosedDoorclosedDooropenStartdo: set power= 600Half powerdo: set power= 300Set timedo: get numberexit: set timeDisabledOperationTimerCancelWaitingdo: displaytimeWaiting
    • do: displaytimedo: displayReadydo: displayWaitingMicrowave oven state descriptionState DescriptionWaiting The oven is waiting for input. The display shows thecurrent time.Half power The oven power is set to 300 watts. The display shows‘Halfpower’.Full power The oven power is set to 600 watts. The display shows‘Fullpower’.Set time The cooking time is set to the user’s input value. Thedisplayshows the cooking time selected and is updated as the time is set.Disabled Oven operation is disabled for safety. Interior oven lightis on.Display shows ‘Not ready’.Enabled Oven operation is enabled. Interior oven light is off.Displayshows ‘Ready to cook’.Operation Oven in operation. Interior oven light is on. Displayshows thetimer countdown. On completion of cooking, the buzzer issounded for 5 seconds. Oven light is on. Display shows ‘Cookingcomplete’ while buzzer is sounding.Microwave oven stimuliStimulus DescriptionHalf power The user has pressed the half power buttonFull power The user has pressed the full power buttonTimer The user has pressed one of the timer buttons
    • Number The user has pressed a numeric keyDoor open The oven door switch is not closedDoor closed The oven door switch is closedStart The user has pressed the start buttonCancel The user has pressed the cancel buttonState charts• Allow the decomposition of a model into sub-models (seefollowing slide)• A brief description of the actions is included following the ‘do’ ineach state• Can be complemented by tables describing the states and thestimuliMicrowave oven operationCookdo: rungeneratorDonedo: buzzer onfor 5 secs.WaitingAlarmdo: displayeventdo: checkstatusCheckingTurntablefaultEmitterfaultDisabledOKTimeoutTimeOperation
    • Dooropen CancelSemantic data models• Used to describe the logical structure of data processed by thesystem• Entity-relation-attribute model sets out the entities in the system,the relationshipsbetween these entities and the entity attributes• Widely used in database design. Can readily be implementedusing relationaldatabases• No specific notation provided in the UML but objects andassociations can beusedSoftware design semantic modelDesignnamedescriptionC-dateM-dateLinknametypeNodenametypelinkshas-links211nLabelnametexticonhas-labels has-labels
    • 1n1nhas-nodes is-a has-links1n1n11Data dictionaries• Data dictionaries are lists of all of the names used in the systemmodels.Descriptions of the entities, relationships and attributes are alsoincluded• Advantages•Support name management and avoid duplication•Store of organisational knowledge linking analysis, design andimplementation• Many CASE workbenches support data dictionariesData dictionary entriesName Description Type Datehas-labels1:N relation between entities of typeNode or Link and entities of typeLabel.Relation 5.10.1998LabelHolds structured or unstructuredinformation about nodes or links.Labels are represented by an icon(which can be a transparent box) andassociated text.Entity 8.12.1998
    • LinkA 1:1 relation between designentities represented as nodes. Linksare typed and may be named.Relation 8.12.1998name(label)Each label has a name whichidentifies the type of label. The namemust be unique within the set of labeltypes used in a design.Attribute 8.12.1998name(node)Each node has a name which must beunique within a design. The namemay be up to 64 characters long.Attribute 15.11.1998Object models• Object models describe the system in terms of object classes• An object class is an abstraction over a set of objects withcommon attributes andthe services (operations) provided by each object• Various object models may be produced•Inheritance models•Aggregation models•Interaction models• Natural ways of reflecting the real-world entities manipulated bythe system• More abstract entities are more difficult to model using thisapproach• Object class identification is recognised as a difficult processrequiring a deepunderstanding of the application domain
    • • Object classes reflecting domain entities are reusable acrosssystemsInheritance models• Organise the domain object classes into a hierarchy• Classes at the top of the hierarchy reflect the common features ofall classes• Object classes inherit their attributes and services from one ormore super-classes.These may then be specialised as necessary• Class hierarchy design is a difficult process if duplication indifferent branches isto be avoidedThe Unified Modelling Language• Devised by the developers of widely used object-orientedanalysis and designmethods• Has become an effective standard for object-oriented modelling• Notation•Object classes are rectangles with the name at the top, attributes inthe middlesection andoperations in the bottom section•Relationships between object classes (known as associations) areshown as lineslinking objects•Inheritance is referred to as generalisation and is shown ‘upwards’rather than‘downwards’ in ahierarchyLibrary class hierarchyAuthorEditionPublication dateISBNBook
    • YearIssueMagazineDirectorDate of releaseDistributorFilmVersionPlatformComputerprogramTitlePublisherTitleMediumPublished itemCatalogue numberAcquisition dateCostTypeStatusNumber of copiesLibrary itemAcquire ()Catalogue ()Dispose ()Issue ()Return ()Recorded itemUser class hierarchyNameAddressPhoneRegistration #Library user
    • Register ()De-register ()Multiple inheritance• Rather than inheriting the attributes and services from a singleparent class, asystem, which supports multiple inheritance, allows object classesto inherit fromseveral super-classes• Can lead to semantic conflicts where attributes/services with thesame name indifferent super-classes have different semantics• Makes class hierarchy reorganisation more complex# TapesTalking bookAuthorEditionPublication dateISBNBookSpeakerDurationRecording dateVoice recordingObject aggregation• Aggregation model shows how classes, which are collections, arecomposed ofother classes• Similar to the part-of relationship in semantic data modelsObject behaviour modellingVideotapeTape ids.LecturenotesTextOHP slides
    • SlidesAssignmentCreditsSolutionsTextDiagramsExercisesoblemsDescriptionCourse titleNumberYearInstructorStudy pack#Pr• A behavioural model shows the interactions between objects toproduce someparticular system behaviour that is specified as a use-case• Sequence diagrams (or collaboration diagrams) in the UML areused to modelinteraction between objectsIssue of electronic items:Library UserEcat:CatalogLookupIssueDisplay:Library Item Lib1:NetServerIssue licenceAccept licenceCompressCASE workbenches
    • • A coherent set of tools that is designed to support relatedsoftware processactivities such as analysis, design or testing• Analysis and design workbenches support system modellingduring bothrequirements engineering and system design• These workbenches may support a specific design method or mayprovide supportfor a creating several different types of system modelAn analysis and design workbenchAnalysis workbench components• Diagram editorsCentralinformationrepositoryCodegeneratorQuerylanguagefacilitiesStructureddiagrammingtoolsDatadictionaryReportgenerationfacilitiesDesign, analysisand checkingtoolsFormscreationtoolsImport/export
    • facilities• Model analysis and checking tools• Repository and associated query language• Data dictionary• Report definition and generation tools• Forms definition tools• Import/export translators• Code generation toolsKey points• A model is an abstract system view. Complementary types ofmodel providedifferent system information• Context models show the position of a system in its environmentwith othersystems and processes• Data flow models may be used to model the data processing in asystem• State machine models model the system’s behaviour in responseto internal orexternal events• Semantic data models describe the logical structure of data,which is imported toor exported by the systems• Object models describe logical system entities, their classificationandaggregation• Object models describe the logical system entities and theirclassification andaggregation• CASE workbenches support the development of system modelsActivitiesActivity 1:- Draw a context model for a patient information systemin a hospital. Youmay make any reasonable assumptions about the other hospitalsystems, which are
    • available, but your model must include a patient admissions systemand an image storagesystem for X-rays.Activity 2:- Based on your experience with a bank ATM, draw adata-flow diagrammodeling the data processing involved when a customer withdrawscash form themachine.Activity 3:- Model the data processing which might take place inan electronic mailsystem. You should model the mail sending and mail receivingprocessing separately.Activity 4:- Draw state machine models of the control softwarefor:• An automatic washing machine, which has different programs fordifferent typesof clothes.• The software for ac compact disc player.• A telephone answering machine on an LED display. The systemshould allow thetelephone owner to dial in, type a sequence of numbers (identifiedas tones) andhave the recorded messages replayed over the phone.Activity 5:- Develop an object model including a class hierarchydiagram and anaggregation diagram showing the principal components of apersonal computer systemand its system software.Activity 6:- Develop a sequence diagram showing the interactionsinvolved when astudent registers for a course in a university. Courses may have alimited number ofplaces so the registration process must include checks that placesare available. Assume
    • that the student accesses an electronic course catalogue to find outabout availablecourses.Activity 7:- Describe three modeling activities that may besupported by a CASEworkbench for some analysis method. Suggest three activities thatcannot be automated.Lecture-7: Software PrototypingObjectives• To describe the use of prototypes in different types ofdevelopment projects• To discuss evolutionary and throw-away prototyping• To introduce three rapid prototyping techniques: _high-level language development,  _database programming, and  _component reuse • To explain the need for user interface prototyping Topics covered • Prototyping in the software process • Rapid prototyping techniques • User interface prototyping What is prototyping? • Some traditional features: _An iterative process emphasizing »Rapid development, »Evaluative use, »Feedback, and »Modification _Learning (based on feedback) _Consideration of alternatives _Concreteness (a “real system” is developed and presented to real users) • Boundary between prototyping and normal system development blurs when an evolutionary (e.g., agile) development approach is used.
    • Uses of prototypes• Principal use is to help customers and developers betterunderstand systemrequirements._Experimentation stimulates anticipation of how a system could be used. _Attempting to use functions together to accomplish some task can easily reveal requirements problems. • Other potential uses: _Evaluating proposed solutions for feasibility (Experimental Prototyping) _“Back-to-back” system testing _Training users before system delivery • Prototyping is most often undertaken as a risk reduction activity. Classifying prototypes • By purpose: _Throw-away prototyping – to elicit and validate requirements _Evolutionary prototyping – to deliver an acceptable, working system to end-users _Experimental prototyping – to evaluate proposed solutions for feasibility, performance, etc. Simulation, prototyping, and scenarios • What are the differences between prototyping and simulation? • What is the connection between simulation models / prototypes, and scenarios? _Simulation models are automatic scenario generators. _Prototypes facilitate manual scenario generation. Prototyping benefits • Misunderstandings exposed. • Difficult to use or confusing services identified • Missing services detected • Incomplete and/or inconsistent requirements found by analysts as prototype is
    • being developed. Can demo feasibility and usefulness• Basis for writing a system specificationPrototyping processE s t abl is hp ro to ty peo bj ec t iv e sD e f i nep ro to ty pef un c ti on a li tyD eve lo pp ro to ty peE v a lu a t ep ro to ty peP ro to ty pi ngp la nO u t li ned ef i n i ti onEx e c ut ab lep ro to ty peE v a lu ati onr e po r tPrototyping outcomes• Improved system usability• Closer match to the system needed• Improved design quality (maybe…)• Improved maintainability (maybe…)• Reduced overall development effort (maybe…but correctivemaintenance costsare usually reduced)Prototyping in the software process• Evolutionary prototyping – prototype is produced and refinedthrough a numberof stages to become the final system.• Throwaway prototyping – prototype is produced to help elucidate/ validate
    • requirements and then discarded. The system is then developedusing some otherdevelopment process.Starting points• In evolutionary prototyping, development starts with thoserequirements, whichare best understood.• In throwaway prototyping, development starts with thoserequirements, which areleast understood.Approaches to prototypingEvolutionary prototypingEv o lu tion aryp ro to typingTh row-awayPro to typingDeliveredsys temExecutable Prototyp e +Sy stem Speci ficat io nOu t lineRequ irement s• Often used when a specification cannot be developed in advance(e.g., AI systemsand GUI applications).• System is developed as a series of prototype versions delivered tothe customerfor assessment.• Verification is unnecessary as there is no specification.• Validation involves assessing the adequacy of the system.Build prototypesystemDevelop abstractspecificationUse prototype
    • systemDeliversystemSystemadequate?YESN• Techniques for rapid system development are used such as CASEtools and 4GLs.• User interfaces are usually developed using a GUI developmenttoolkit.Advantages of evolutionary prototyping over normal systemdevelopment• Accelerated delivery – quick availability is sometimes moreimportant than detailsof functionality or maintainability.• User engagement – system is more likely to meet userrequirements and users aremore likely to want to make it work.Evolutionary prototyping problems• Management problems_Poor fit with existing waterfall management model _Specialized developer skills required • Maintenance problems – continual change tends to corrupt system structure so long-term maintenance is expensive. • Contractual problems – no system requirements specification to serve as basis for contract Incremental development revisited • System developed and delivered in increments after establishing an overall architecture. • Users experiment with delivered increments while others are being developed.
    • • Intended to combine advantages of prototyping with a moremanageable processand maintainable system structure.Incremental development processValidateincrementBuild systemincrementSpecify systemincrementDesign systemarchitectureDefine systemdeliverablesSystemcomplete?IntegrateincrementValidatesystemDeliver finalsystemYESNOThrow-away prototyping• Used to reduce requirements risk.• Initial prototype is developed from outline requirements,delivered forexperiment, and modified until risk is acceptably lowOutlinerequirementsDevelopprototypeEvaluateprototype
    • SpecifysystemDevelopsoftwareValidatesystemDeliveredsoftwaresystemReusablecomponentsThrow-away prototype delivery• Developers may be pressurized to deliver a throw-awayprototype as the finalsystem.• This is very problematic..._It may be impossible to meet non-functional requirements. _The prototype is almost certainly undocumented. _The system may be poorly structured and therefore difficult to maintain. _Normal quality standards may not have been applied. Prototypes AS specifications? • Some parts of the requirements (e.g., safety-critical functions) may be impossible to prototype and so don’t appear in the specification. • An implementation has no legal standing as a contract. • Non-functional requirements cannot be adequately represented in a system prototype. Implementation techniques • Various techniques may be used for rapid development: _Dynamic high-level language development _Database programming (4GL’s) _Component and application assembly • These are not mutually exclusive – they are often used together.
    • • Visual programming is an inherent part of most prototypedevelopment systems.Dynamic high-level languages• Include powerful data management facilities – often type less andinterpretive• Require large run-time support system – not normally used forlarge systemdevelopment.• Some offer excellent GUI development facilities.• Some have an integrated support environment whose facilitiesmay be used in theprototype.• Examples: Lisp (list structure based), Prolog (logic based), andSmalltalk (objectoriented)Choice of prototyping language• What is the application domain? (e.g., NLP?, matrixmanipulation?)• What user interaction is required? (text-based? Web-based?)• What support environment comes with the language? (e.g., tools,components)• What support environment comes with the language? (e.g., tools,components)• Different parts of the system may be programmed in differentlanguages.However, there may be problems with language communications.• A multi-paradigm language (e.g., LOOPS) can reduce thisproblem.Database programming languages• Domain specific languages for business systems based around adatabasemanagement system• Normally include a database query language, a screengenerator, a reportgenerator and a spreadsheet.• May be integrated with a CASE toolset
    • • The language + environment is some-times known as a fourth-generationlanguage (4GL)• Cost-effective for small to medium sized business systems• Examples include Informix, Appgen, Sculptor, and Power-4GL.DBprogramminglanguageInterfacegenerator SpreadsheetReportgeneratorDatabase management systemFourth-generation languageComponent and application assembly• Prototypes can be created quickly from a set of reusablecomponents plus somemechanism to “glue” these components together.• The composition mechanism must include control facilities and amechanism forcomponent communication• Must take into account the availability and functionality ofexisting componentsPrototyping with reuse• Application level development_Entire application systems are integrated with the prototype so that their functionality can be shared. _For example, if text preparation is required, a standard word processor can be used. • Component level development _Individual components are integrated within a standard framework to implement the system
    • _Framework can be a scripting language or an integration framework such as CORBA, DCOM, or Java Beans Reusable component composition Component composition framework Executable prototype Reusable software components Control and integration code Compound documents • For some applications, a prototype can be created by developing a compound document. • This is a document with active elements (such as a spreadsheet) that allow user computations. • Each active element has an associated application, which is invoked when that element is selected. • The document itself is the integrator for the different applications. Application linking in compound documents Compounddocument W o rd p roc e s so r S p r ea d sh e e t A u d i o p l a y e r Text1Text2Text3 Text4Text5 Table1 Table2 Sound1 Sound2
    • Visual programming• Scripting languages such as Visual Basic support visualprogramming where theprototype is developed by creating a user interface from standarditems andassociating components with these items.• A large library of components exists to support this type ofdevelopment• These may be tailored to suit the specific applicationrequirements.Visual programming with reuseFile Edit Views Layout Options HelpGeneralIndexHypertextDate component display componentRange checkingscriptTree displaycomponent12th January 20003.876Draw canvascomponentUser promptcomponent +scriptProblems with visual development• Difficult to coordinate team-based development• No explicit system architecture (hidden)• Complex dependencies between parts of the program can causemaintainabilityproblems.User interface prototyping
    • • It is impossible to pre-specify the look and feel of a user interfacein an effectiveway. Prototyping is essential.• UI development consumes an increasing part of overall systemdevelopment costs• User interface generators may be used to “draw” the interface andsimulate itsfunctionality with components associated with interface entities.• Web interfaces may be prototyped using a web site editor.Key points• A prototype can be used to give end-users a concrete impressionof the system’scapabilities.• Prototyping is becoming increasingly used for systemdevelopment where rapiddevelopment is essential.• Throw-away prototyping is used to understand the systemrequirements.• In evolutionary prototyping, the system is developed by evolvingan initialversion to the final version.• Rapid development of prototypes is essential. This may requireleaving outfunctionality or relaxing non-functional constraints.• Prototyping techniques include the use of very high-levellanguages, databaseprogramming and prototype construction from reusablecomponents.• Prototyping is essential for parts of the system such as the userinterface, whichcannot be effectively pre-specified. Users must be involved inprototypeevaluationActivities
    • Activity 1:- You have been asked to investigate the feasibility ofprototyping in thesoftware development process in your organization. Write a reportfor your managerdiscussing the classes of project where prototyping should be usedand setting out theexpected costs and benefits form using prototyping.Activity 2:- Explain why, for large systems development, it isrecommended thatprototypes should be throw away prototypes.Activity 3:- Under what circumstances would you recommend thatprototyping should beused as a means of validating system requirements?Activity 4:- Suggest difficulties that might arise when prototypingreal time embeddedcomputer systems :Activity 5:- Discuss prototyping using reusable components andsuggest problems whichmay arise using this approach. What is the most effective way tospecify reusablecomponents?Activity 6:- You have been asked by a charity to prototype asystem that keeps track oftall donations they have received. This system has to maintain thenames and addresses ofdonors, their particular interests, the amount donated, and when itwas donation (e.g. itmust be spent on a particular project) and the system must keeptrack of these donationsand how they were spent. Discuss how you would prototype thissystem bearing in mindthat the charity has a mixture of paid workers and volunteers.Many of the volunteers areretirees who have had little or no computer experience.
    • Activity 7:- You have developed a throw prototype system for aclient who is very happywith it. However, she suggests that there is no need to developanother system but thatyou should deliver the prototype and offers an excellent price forthe system. You knowthat there may be future problems with maintaining the system.Discuss how you mightrespond to this customer.Lecture-8: Formal SpecificationsObjectives• To explain why formal specification helps discover problems insystemrequirements.• To describe the use of: _Algebraic specification techniques, and  _Model-based specification techniques (including simple pre and post conditions). Topics covered • Formal specification in the software process • Interface specification • Behavioural specification Formal methods • Formal specification is part of a more general collection of techniques known as “formal methods.” • All are based on the mathematical representations and analysis of requirements and software. • Formal methods include: _Formal specification _Specification analysis and property proofs _Transformational development _Program verification (program correctness proofs)
    • • Specifications are expressed with precisely defined vocabulary,syntax, andsemantics.Acceptance and use• Formal methods have not become mainstream as was oncepredicted, especially inthe US._Other, less costly software engineering techniques (e.g., inspections / reviews) have been successful at increasing system quality. (Hence, the need for formal methods has been reduced.) _Market changes have made time-to-market rather than quality the key issue for many systems. (Formal methods do not reduce time-to-market.) _The scope of formal methods is limited. They are not well suited to specifying user interfaces. (Many interactive applications are “GUI-heavy” today.) _Formal methods are hard to scale up to very large systems. (Although this is rarely necessary.) _The costs of introducing formal methods are high. _Thus, the risks of adopting formal methods on most projects outweigh the benefits. • However, formal specification is an excellent way to find requirements errors and to express requirements unambiguously. • Projects, which use formal methods invariably, report fewer errors in the delivered software. • In systems where failure must be avoided, the use of formal methods is justified and likely to be cost-effective. • Thus, the use of formal methods is increasing in critical system development where safety, reliability, and security are important. Formal specification in the software process
    • RequirementsspecificationFo rmalspecificationSystemmodellingAr chitecturaldesignRequirementsdefinitionHigh-le veldesignFormal specification techniques• Algebraic approach – the system is specified in terms of itsoperations and theirrelationships via axioms.Sequential ConcurrentAlgebraic Larch (Guttag, Horning etal., 1985; Guttag,Horning et al., 1993),OBJ (Futatsugi, Goguenet al., 1985)Lotos (Bolognesi andBrinksma, 1987),Model-based Z (Spivey, 1992)VDM (Jones, 1980)B (Wordsworth, 1996)CSP (Hoare, 1985)Petri Nets (Peterson,1981)• Model-based approach (including simple pre- and post-conditions) – the systemis specified in terms of a state model and operations are defined interms ofchanges to system state.
    • Formal specification languagesSequential ConcurrentAlgebraic Larch (Guttag, Horning etal., 1985; Guttag, Horninget al., 1993),OBJ (Futatsugi, Goguenet al., 1985)Lotos (Bolognesi andBrinksma, 1987),Model-based Z (Spivey, 1992)VDM (Jones, 1980)B (Wordsworth, 1996)CSP (Hoare, 1985)Petri Nets (Peterson,1981)Use of formal specification• Formal specification is a rigorous process and requires moreeffort in the earlyphases of software development.• This reduces requirements errors as ambiguities, incompleteness,andinconsistencies are discovered and resolved.• Hence, rework due to requirements problems is greatly reduced.Development costs with formal specificationSp eci ficat io nDes ig n andImplementat io nValidat io nSp eci ficat io nDes ig n andImplement at io nValidat io nCostWi th ou t fo rm als pecificat io n
    • W ith formalspecifi cat io nSpecification of sub-system interfaces• Large systems are normally comprised of sub-systems with well-definedinterfaces.• Specification of these interfaces allows for their independentdevelopment.• Interfaces are often defined as abstract data types or objects.• The algebraic approach is particularly well suited to thespecification of suchinterfaces.Sub-system interfacesSu b-s ys temASu b-s ys temBInt e rfaceo bj ec t sSpecification components• Introduction – defines the sort (type name) and declares otherspecifications thatare used• Description – informally describes the operations on the type• Signature – defines the syntax of the operations in the interfaceand theirparameters• Axioms – defines the operation semantics by defining axiomswhich characterizebehaviourTypes of operations• Constructor operations: operations which create / modify entitiesof the type• Inspection operations: operations, which evaluate entities of thetype being
    • specified• Rule of thumb for defining axioms: define an axiom, which setsout what isalways true for each inspection operation over each constructorModel-based specification• Algebraic specification can be cumber-some when objectoperations are notindependent of object state (i.e., previous operations).• (System State) Model-based specification exposes the systemstate and definesoperations in terms of changes to that state.• Z is a mature notation for model-based specification. It combinesformal andinformal descriptions and incorporates graphical highlighting.• The basic building blocks of Z-based specifications are schemas.• Schemas identify state variables and define constraints andoperations in terms ofthose variables.The structure of a Z schemaSchSchNatural numbers (0, 1, 2, …)C o n t a i n e r Defines schema statecontents:contents Š capacitycapacity:ema name ema signature Schema predicate“invariants”, pre- & post- conditionsAn insulin pumpinsulindeliveryglucose leveltext messages dose delivered Display1Modelling the insulin pumpNeedleassembly
    • SensorDisplay2AlarmPump ClockPower supplyInsulin reservoirController• The schema models the insulin pump as a number of statevariables_reading? from sensor _dose, cumulative dose _r0, r1, r2 last 3 readings _capacity pump reservoir _alarm! signals exceptional conditions _pump! output for pump device _display1!, display2! text messages & dose • Names followed by a? are inputs, names followed by a! are outputs. Schema invariant • Each Z schema has an invariant part, which defines conditions that are always true (schema predicates) • For the insulin pump schema, it is always true that: _The dose must be less than or equal to the capacity of the insulin reservoir. _No single dose may be more than 5 units of insulin and the total dose delivered in a time period must not exceed 50 units of insulin. This is a safety constraint. _display1! shows the status of the insulin reservoir. Insulin pump schema Insulin_pump reading? : dose, cumulative_dose: r0, r1, r2: // used to record the last 3 readings taken
    • capacity:alarm!: {off, on}pump!:display1! display2!: STRINGevery 10 minutesThe dosage computation• The insulin pump computes the amount of insulin required bycomparing thecurrent reading with two previous readings.• If these suggest that blood glucose is rising then insulin isdelivered.• Information about the total dose delivered is maintained to allowthe safety checkinvariant to be applied.• Note that this invariant always applies – there is no need to repeatit in the dosagecomputation.DOSAGE schemaoperations change state GEdo(i(m( por _ts state & pr edicates- r 1 ∧ x′ - value of x after operation∧ ( r2 =∧DO SAΔInsulin_Pump(se = 0 ∧r1 r0) r1)) ∨(( r1 > r0) (r2 Š r1)) ∨(( r1 < r0) ∧ ((r1-r2) > (r0-r1))))∨dose = 4 ∧(
    • (( r1 Š r0) ∧ (r2 =r1)) ∨(( r1 < r0) ∧ ((r1-r2) Š (r0-r1))))∨dose =(r2 ) * 4((( r1 Š r0) ∧ (r2 > r1)) ∨(( r1 > r0) ∧ ((r2 - r1) _ (r1 - r0)))))c apacit y = cap acity - dos ecumulat ive_dose = cumulative_dose + doser0 = r1 ∧ r1 = r2Output schemas• The output schemas model the system displays and the alarm thatindicates somepotentially dangerous condition.• The output displays show the dose computed and a warningmessage.• The alarm is activated if blood sugar is very low – this indicatesthat the usershould eat something to increase his blood sugar level.Δ conversionNote conflict with “insulin low” msg.^ ANDALARMΔInsulin_PumpSchema consistencyDISPLAYInsulin_Pumpdisplay2! = Nat_to_string (dose) ∧(reading? < 3 ⇒ display1! = "Sugar low" ∨reading? > 30 ⇒ display1! = "Sugar high" ∨reading? _ 3 and reading? Š 30 ⇒ display1! = "OK")( reading? < 3 ∨ reading? > 30 ) ⇒ alarm! = on ∨( reading? _ 3 ∧ reading? Š 30 ) ⇒ alarm! = off
    • • It is important that schemas be consistent. Inconsistency suggestsa problem withsystem requirements.• The INSULIN_PUMP schema and the DISPLAY areinconsistent:_display1! shows a warning message about the insulin reservoir (INSULIN_PUMP) _display1! Shows the state of the blood sugar (DISPLAY) • This must be resolved before implementation of the system. Specification via Pre- and Post-Conditions • Predicates that (when considered together) reflect a program’s intended functional behavior are defined over its state variables. • Pre-condition: expresses constraints on program variables before program execution. An implementer may assume these will hold BEFORE program execution. • Post-condition: expresses conditions / relationships among program variables after execution. These capture any obligatory conditions AFTER program execution. • Language: (first order) predicate calculus _Predicates (X>4) _Connectives (&, V, →, ó, NOT) _Universal and existential quantifiers (for every, there exists…) _Rules of inference (if A & (A → B) then B) Example 1 • Sort a non-empty array LIST [1..N] into increasing order. Pre-cond: N ≥ 1 Post-cond: For_Every i, 1 ≤ i ≤ N-1, LIST [i] ≤ LIST [i+1] & PERM (LIST, LIST’) Example 2
    • • Search a non-empty, ordered array LIST [1..N] for the valuestored in KEY. Ifpresent, set found to true and J to an index of LIST whichcorresponds to KEY.Otherwise, set FOUND to false.Pre-cond: N ≥ 1 & [(“LIST is in increasing order”) V (“LIST is indecreasing order”)](Exercise: express the “ordered” predicate above FORMALLY.)Post-cond: [(FOUND & There Exists i, 1 ≤ i ≤ N | J=i & LIST[J]=Key) V (NOTFOUND & For_Every i, 1 ≤ i ≤ N, LIST [i] ≠KEY)] & UNCH(LIST, KEY)Key points• Formal system specification complements informal specificationtechniques.• Formal specifications are precise and unambiguous. They removeareas of doubtin a specification.• Formal specification forces an analysis of the systemrequirements at an earlystage. Correcting errors at this stage is cheaper than modifying adelivered system.• Formal specification techniques are most applicable in thedevelopment of criticalsystems.• Algebraic techniques are particularly suited to specifyinginterfaces of objects andabstract data types.• In model-based specification, operations are defined in terms ofchanges to systemstate.ActivitiesActivity 1:- Suggest why the architectural design of a systemshould precede thedevelopment of a formal specification.
    • Activity 2:-You have been given the task of selling formalspecification techniques to asoftware development organization. Outline how you would goabout explaining theadvantages of formal specifications to skeptical, practicingsoftware engineers.Activity 3:- Explain why it is particularly important to define sub-system interfaces in aprecise way and why algebraic specification is particularlyappropriate for sub-systeminterface specification.Activity 4:- In the example of a controlled airspace sector, thesafety condition is thataircraft may not be within 300 m of height in the same sector.Modify the specificationshown in figure 9.8 to allow aircraft to occupy the same height inthe sector so long asthey are separated by at least 8km of horizontal difference. Youmay ignore aircraft inadjacent sectors. Hint. You have to modify the constructoroperations so that they includethe aircraft position as well as its height. You also have to definean operation that, giventwo positions, returns the separation between them.Activity 5:- Bank teller machines rely on using information on theuser’s card giving thebank identifier, the account number and the user’s personalidentifier. They also deriveaccount information from a central database and update thatdatabase on completion of atransaction. Using your knowledge of ATM operation write Zschemas defining the stateof the system, card validation (where the user’s identifier ischecked) and cashwithdrawal.
    • Activity 6:- You are a systems engineer and you are asked tosuggest the best way todevelop the safety software for a heart pacemaker. You suggestformally specifying thesystem but your suggestion is rejected by your manager. You thinkhis reasons are weakand based on prejudice. Is it ethical to develop the system usingmethods that you thinkare inadequate?Lecture-9: Architectural Design• Establishing the overall structure of a software systemObjectives• To introduce architectural design and to discuss its importance• To explain why multiple models are required to document inarchitecture• To describe types of architectural models that may be used• To discuss use of domain-specific architectural reference modelsTopics covered• Architectural design• System structuring• Control models• Modular decomposition• Domain-specific architecturesWhat is architectural design?• The process of identifying the sub-systems making up a systemand a frameworkfor sub-system control and communication.• A boot-strapping process undertaken in parallel with the abstractspecification ofsub-systems.• The output of this process is the software architecture.The software design processArchitectur aldesignAbstract
    • specificationInterfacedesignComponentdesignDatastructur edesignAlgorithmdesignSystemarchitectur eSoftwarespecificationInterfacespecifica tionComponentspecificationDatastructur especificationAlgorithmspecifica tionRequirementsspecificationDesign acvtiitiesDesign porductsAdvantages of explicit architecture design and documentation(Bass)• Stakeholder communication – the architecture may be used as afocus ofdiscussion by system stakeholders.• System analysis – the feasibility of meeting critical non-functional requirements
    • (e.g., performance, reliability, maintainability) can be studied earlyon.• Large-scale reuse – the architecture may be reusable across arange of systemswith similar requirements.Architectural design process• System structuring – the system is decomposed into major sub-systems andcommunication (e.g., data sharing) mechanisms are identified.• Control modelling – a model of the control relationshipsbetween the subsystemsis established.• Modular decomposition – the identified sub-systems aredecomposed intolower-level modules (components, objects, etc.)Terminology issues• Modular decomposition is sometimes called high-level (system)design.• A sub-system is usually a system in its own right, and issometimes called aProduct.• A module is a lower-level element that would not normally beconsidered aseparate system; modules are sometimes called Components orObjects.• Traditional (and Somerville’s) terminologySystem (System)Product (Sub-System)Component (Module)Module (Unit) (Algorithm)Architectural models• Different types of models may be used to represent anarchitectural design.• Each presents a different perspective on the architecture.Architectural model types
    • • Static structural models show the major system components.• Dynamic process models show the process structure of thesystem at run-time.• Interface models define the sub-system services offered throughpublicinterfaces.• Relationship models show relationships such as a dataflowamong sub-systems.Architectural styles• The architecture of a system may conform to a single genericmodel or style,although most do not.• An awareness of these styles and how they can affect systemattributes cansimplify the problem of choosing an appropriate architecture.System attributes and architectural styles / structures• Performance – localize operations by using fewer, large-graincomponents tominimize sub-system communication.• Security – use a layered architecture with critical assets in innerlayers.• Safety – isolate safety-critical components in one or just a fewsub-systems.• Availability – include redundant components in the architecture.• Maintainability – use fine-grain, self-contained components.System structuring• Concerned with decomposing the system into interacting sub-systems.• The architectural design is normally expressed as a blockdiagram presenting anoverview of the system structure.• More specific models showing how sub-systems share data aredistributed, andinterface with each other may also be developed. (Examplesfollow.)
    • Packing robot control systemV isionsys temObjectidentificationsystemArmcontro llerGripp ercontrollerPackagingselectionsys temPackingsystemCo nveyo rcon trollerThe repository model• Sub-systems must exchange info. This may be done in two ways:_Shared data is held in a central database or repository and may be accessed by all sub-systems. _Each sub-system maintains its own database and passes data explicitly to other sub-systems. • When large amounts of data are used, the repository model of sharing is commonly used. CASE toolset architecture Project repository Design translator Program editor Design
    • editorCodegeneratorDesignanalyserReportgeneratorRepository model advantages• Simple and efficient way to share large amounts of data locally.• Sub-systems, which use data, need not be concerned with howthat data isproduced, and vice-versa.• Management activities such as backup, access control, andrecovery arecentralized.• Sharing model is published as the repository schema. Integrationof compatibletools is relatively easy.Repository model disadvantages• Sub-systems must agree on a single repository data model. Thisis inevitably acompromise.• Data model evolution is difficult and expensive.• No provision for sub-system-specific data managementrequirements related tobackup, access control, and recovery.• May be difficult to distribute efficiently over a number ofmachines due toproblems with data redundancy and inconsistency.The client-server model• Distributed system model, which shows how data and processingare distributedacross a range of processors.• Major components are:
    • _A set of stand-alone servers, which provide specific services such as printing, file management, etc. _A set of clients, which call on these services _A network, which allows clients to access these services Film and picture library Catalogue Video Picture Hypertext Client 1 Client 2 Client 3 Client 4 Wide-bandwidth network Client-server model advantages • Supports distributed computing. • Underlying network makes distribution of data straightforward. • No shared data model so servers may organize data to optimise their performance. • Distinction between servers and clients may allow use of cheaper hardware. • Relatively easy to expand or upgrade system. Client-server model disadvantages • Relatively complex architecture – problem determination can be difficult. • No shared data model so data integration may be problematic. • Redundant data management in each server. • No central register of names and services, so it may be hard to find out what servers and services are available. The abstract machine model • Organizes a system into a series of layers. • Each layer defines an abstract machine and provides a set of services used to implement the next level of abstract machine. • When a layer interface changes, only the adjacent layer is affected. • However, it is often difficult to structure systems in this way. (Why?) Abstract machine based version management system
    • Control modelsOperat in gsys temDatabase s ys temOb ject m anagemen tVersion man ag emen t• Concerned with the control flow between sub-systems. Distinctfrom the systemstructure model.• Two general approaches:_Centralized control – one sub-system has overall responsibility for control and starts and stops other sub-systems. _Event-based control – each sub-system can respond to externally generated events from other sub-systems, or from the system’s environment. Centralized control models 1.Call-return model – top-down subroutine model where control starts at the top of a subroutine hierarchy and moves downwards. Applicable to sequential systems only. 2. Manager model – applicable to concurrent systems. One system component controls the stopping, starting and coordination of other system processes. Also applicable to sequential systems where it is usually implemented as a case statement within a management routine. Call-return model call Routine 1 Routine 2 Routine 3 Main program return Manager model: real-time system control
    • S y st emcon tr o ll erUs eri nt erfaceFa ul th an dlerC om pu tat io np ro ces sesAct uatorp ro ces sesSen so rp ro ces sesPrincipal Event-based control models1.Broadcast model – an event is broadcast to all sub-systems; anysub-system, which canhandle the event, may do so.2.Interrupt-driven model – used in real-time systems whereinterrupts are detected by aninterrupt handler and passed to some other component forprocessing.(Other event-based models include compound documents andproduction systems.)Broadcast model• Effective in integrating sub-systems executing on differentcomputers in anetwork.• Control policy is NOT embedded in the message handler; sub-systems register aninterest in specific events and the event handler ensures that theseevents are sentto them.• Registration of interests’ supports selective broadcasting.• Evolution is relatively easy since a new sub-system can beintegrated byregistering its events with the event handler.
    • • However, sub-systems don’t know if or when an event will behandled by someother sub-system.Interrupt-driven systems• Used in real-time systems where fast response to an event isessential.• A handler is defined for each type of interrupt.• Each type is associated with a memory location and a hardwareswitch causestransfer to its handler – fast!• Allows fast response but is complex to program and difficult toverify. (Why?)Interrupt-driven controlHandler1Handler2Handler3Handler4Process1Process2Process3Process4InterruptsInterruptvectorModular decomposition (a.k.a. high-level design)• Sub-systems are decomposed into lower-level elements.• Two models are considered:
    • _An object model where the system is decom-posed into interacting objects. (object-oriented design) _A data-flow model where the system is decomposed into functional modules, which transform inputs into outputs. (function-oriented design) Object models • Structure the system into a set of loosely coupled objects with well-defined interfaces. • Object-oriented decomposition is concerned with identifying object classes, their attributes and operations. • When implemented, objects are created from these classes and some control model is used to coordinate object operations. Invoice processing system issue () sendReminder () acceptPayment () sendReceipt () invoice# date amount customer Invoice invoice# date amount customer# Receipt invoice# date amount
    • customer#Paymentcustomer#nameaddresscredit periodCustomerData-flow models• Functional transformations process inputs to produce outputs.• Sometimes referred to as a pipe and filter model (afterterminology used inUNIX).• Variants of this approach have a long history in software design.• When transformations are sequential, this is a batch sequentialmodel• which is extensively used in data processing systems.• Not really suitable for interactive systems (input data streamsversus events)Invoice processing systemin Continuopaus sinput streamsRead issuedvoicesIdentifyymentIssuereceiptsFindpaymentsdueReceiptsIssuepaymentreminderReminders
    • Invoices PaymentsDomain-specific architectures• Architectural models which are specific to some applicationdomain• Two types of domain-specific models:1.Generic models encapsulate the traditional, time-testedcharacteristics of realsystems.2.Reference models are more abstract and describe a larger classof systems. Theyprovide a means of comparing different systems in a domain.• Generic models are usually bottom-up models; Referencemodels aretop-down models.Generic models• The compiler model is a well-known example.• Based on the thousands written, it is now generally agreed thatthestandard components of a compiler are:_Lexical analyser _Symbol table _Syntax analyser _Syntax tree _Semantic analyser _Code generator Compiler model Sequential function model (batch processing oriented) Lex ical analy sis Syn tactic analy sis Semant ic analy sis Code generat ion
    • Symbo ltableLanguage processing systemSyntaxanalyserLexicalanalyserSemanticanalyserAbstractsyntax treeGrammardefinitionSymboltableOutputdefinitionPrettyprinterEditorOptimizerCodegeneratorRepositoryRepository-based modelReference architectures• Reference models are derived from a study of the applicationdomain rather thanfrom existing systems.• May be used as a basis for system implementation, or to comparedifferentsystems. It acts as a standard against which systems can beevaluated.• The OSI (Open System Interconnection) model is a layeredmodel for
    • communication systems (in particular, data processing / point-of-saleapplications).OSI reference modelApplicationPresentationSessionTransportNetworkData linkPhysical7654321Communications mediumNetworkData linkPhysicalApplicationPresentationSessionTransportNetworkData linkPhysicalKey points• The software architect is responsible for deriving a structuralsystem model,a control model, and a sub-system decomposition model.• Large systems rarely conform to a single architectural model.
    • • System decomposition models include the repository model,client-servermodel, and abstract machine model.• Control models include centralized control and event-drivenmodels.• Modular decomposition models include data-flow and objectmodels.• Domain specific architectural models are abstractions over anapplication domain.• They may be constructed by abstracting from existing systems orthey may beidealized reference models.ActivitiesActivity 1:- Explain why it may be necessary to design the systemarchitecture before thespecifications are written.Activity 2:- Construct a table showing the advantages anddisadvantages of the differentstructural models discussed in this chapter.Activity 3:- Giving reasons for your answer, suggest anappropriate structural model forthe following systems:• An automated ticket issuing system used by passengers at arailway station.• A computer controlled video conferencing system, which allowsvideo, audio, andcomputer data to be visible to several participants at the same time.• A robot floor cleaner, which is intended to clean relatively, clearspaces such ascorridors. The cleaner must be able to sense walls and otherobstructions.Activity 4:- Design an architecture for the above systems based onyour choice ofmodel. Make reasonable assumptions about the systemrequirements.
    • Activity 5:- Explain why a call-return model of control is notusually suitable for realtime systems which control some process.Activity 6:- Giving reasons for your answer, suggest anappropriate control model for thefollowing systems:• A batch processing system, which takes information about hours,worked andpays rates and prints salary slips and bank credit transferinformation.• A set of software tools, which are, produced buy differentvendors but which mistwork together.• A television controller, which responds to, signals form a remotecontrol unit.Activity 7:- Discuss their advantages and disadvantages as far asdisreputability isconcerned of the data flow model and the object model. Assumethat both single machineand distributed versions of an application are required.Activity 8:- Should there be a separate profession of ‘softwarearchitect’ whose role is towork independently with a customer to design a softwarearchitecture? This would thenbe implemented by some software company. What might be thedifficulties ofestablishing such a profession?Lecture-10: Distributed Systems Architectures• Architectural design for software that executes onmore than oneprocessorObjectives• To explain the advantages and disadvantages of distributedsystems architectures.
    • • To describe different approaches to the development of client-server systems.• To explain the differences between client-server and distributedobjectarchitectures.• To describe object request brokers and the principles underlyingthe CORBAstandards.Topics covered• Multiprocessing systems• Distributed systems architectures _Client-server architectures  _Distributed object architectures • CORBA (Common Object Request Broker Architecture) Multiprocessor architectures • System composed of multiple processes, which may or may not execute on different processors. • Distribution of process to processor may be pre-ordered or may be under the control of a dispatcher. A multiprocessor traffic control system Traffic lights Light control process Traffic light control processor Traffic flow processor Traffic flow sensors Sensor processor Sensor control
    • processDisplayprocessTypes of multiprocessing systems• Personal systems that are not distributed and that are designed torun on apersonal computer or workstation. (word processors)• Embedded systems that run on a single processor or on anintegrated group ofprocessors. (control systems, real-time systems)• Distributed systems where the system software runs on a looselyintegratedgroup of processors linked by a network. (ATM systems)Distributed systems• Virtually all-large, computer-based systems are now distributedsystems.• Processing is distributed over several computers rather thanconfined to a singlemachine.• Distributed software engineering is now very important.Distributed system characteristics / advantages• Resource sharing (hardware and software)• Openness (resource extendibility)• Concurrency (parallel processing)• Scalability (up to capacity of network)• Fault tolerance (potential)• Transparency (ability to conceal distributed nature)Distributed system disadvantages• Complexity (no. of factors affecting emergent properties)• Security (multiple access points, network eavesdropping)• Manageability (heterogeneity)• Unpredictable responsivenessIssues in distributed system designDesign issue DescriptionResource
    • identificationThe resources in a distributed system are spread across differentcomputers and a naming scheme has to be devised so that users candiscover and refer to the resources that they need. An example ofsuch a naming scheme is the URL (Uniform Resource Locator)thatis used to identify WWW pages. If a meaningful and universallyunderstood identification scheme is not used then many of theseresources will be inaccessible to system users.Communications The universal availability of the Internet and theefficientimplementation of Internet TCP/IP communication protocolsmeansthat, for most distributed systems, these are the most effective wayfor the computers to communicate. However, where there arespecific requirements for performance, reliability etc. alternativeapproaches to communications may be used.Quality of service The quality of service offered by a systemreflects its performance,availability and reliability. It is affected by a number of factorssuchas the allocation of processes to processes in the system, thedistribution of resources across the system, the network and thesystem hardware and the adaptability of the system.SoftwarearchitecturesThe software architecture describes how the applicationfunctionality is distributed over a number of logical componentsandhow these components are distributed across processors. Choosingthe right architecture for an application is essential to achieve thedesired quality of service.Distributed systems architectures• Client-server architectures – distributed services, which arecalled on by clients.
    • Servers that provide services are treated differently from clientsthat use services.• Distributed object architectures –removes distinction betweenclients andservers. Any object in the system may provide and use servicesfrom otherobjects.Middleware• Software that manages and enables communication between thediversecomponents of a distributed system. Middleware is usually off-the-shelf ratherthan specially written.• Distributed system frameworks, e.g. CORBA and DCOM, is animportant class ofmiddle-ware described later.Client-server architectures• The application is modelled as a set of services that are providedby servers and aset of clients that use the services.• Clients must know of servers but servers need not know ofclients. (e.g.,“installing” a network printer)• Clients and servers are logical processes as opposed to physicalmachines.• The mapping of processors to processes is not necessarily 1:1.A client-server systems1s2 s3c1 s4c2 c3 c4c5c6c7 c8c9
    • c10c11c12Client processServer processComputers in a C/S networkNetworkSC2 SC1CC1 CC2 CC3CC4 CC5 CC6ServercomputerClientcomputers1, s2 s3, s4c5, c6, c7c1 c2 c3, c4c8, c9 c10, c11, c12Application layers model• Presentation layer – concerned with presenting the results of acomputation tosystem users and with collecting user inputs.• Application processing layer – concerned with implementingthe logic(functionality) of the application.• Data management layer – concerned with all system databaseoperations.Presentation layerApplication processinglayerData managementlayerApplication layersDistributing layers to processors
    • • Two-tier C/S architecture – the three layers are distributedbetween a serverprocessor and a set of clients.• Three-tier C/S architecture – the layers are distributed amongtwo serverprocesses / processors and a set of clients.• Multi-tier C/S architectures – the layers are distributed amongmultiple serverprocesses / processors (each associated with a separate database,for example) anda set of clients.Two-tier architectures: thin and fat clients• Thin-client model – the application logic and data managementare implementedon the server; the client only handles the user interface.• Fat-client model – the server is only responsible for datamanagement; the clienthandles the application logic and the user interface.Thin and fat clientsThin-clientmodelFat-clientmodel ClientClientServerData managementApplicationprocessingPresentationServerDatamanagementPresentationApplication processingThin-client model
    • • Often used when centralized legacy systems evolve to a C/Sarchitecture; the userinterface is migrated to workstations or terminals and the legacysystem acts as aserver.• Places a heavy processing load on both the server and thenetwork; this iswasteful when clients are powerful workstations.Fat-client model• More processing is delegated to the client as the application logicis executedlocally.• But system management is more complex, especially whenapplication functionchanges and new logic must be installed on each client.A client-server ATM systemAccount serverCustomeraccountdatabaseTeleprocessingmonitorATMATMATMATMThree-tier architectures• Each application architecture layer may execute on a separateprocessor.• Allows for better performance and scalability than a thin-clientapproach and issimpler to manage than a fat-client approach.A 3-tier C/S architectureClientServer
    • DatamanagementPresentationServerApplicationprocessingAn Internet banking systemDatabase serverCustomeraccountdatabaseWeb serverClientClientClientClientAccount serviceprovisionSQLSQL queryHTTP interactionUse of C/S architecturesArchitecture ApplicationsTwo-tier C/Sarchitecture withthin clientsLegacy system applications where separating applicationprocessing and data management is impracticalComputationally-intensive applications such as compilers withlittle or no data managementData-intensive applications (browsing and querying) with littleor no application processing.Two-tier C/Sarchitecture withfat clients
    • Applications where application processing is provided byCOTS (e.g. Microsoft Excel) on the clientApplications where computationally-intensive processing ofdata (e.g. data visualisation) is required.Applications with relatively stable end-user functionality usedin an environment with well-established system managementThree-tier ormulti-tier C/SarchitectureLarge scale applications with hundreds or thousands of clientsApplications where both the data and the application arevolatile.Applications where data from multiple sources are integratedDistributed object architectures• Eliminates the distinction between clients and servers.• System components are objects that provide services to, andreceive servicesfrom, other objects.• Object communication is through middle-ware called an objectrequest broker(effectively a software bus)Distributed object architecturesSoftware buso1 o2 o3 o4o5 o6S (o1) S (o2) S (o3) S (o4)S (o5) S (o6)Advantages of distributed object architectures• Allows system designer to delay decisions on where and howservices should beprovided. (Service-providing objects may execute on any networknode.)• Very open architecture – allows new resources to be added asrequired.• Flexible and scaleable.
    • • System is dynamically reconfigurable – objects can migrateacross the network asrequired. (Thus improving performance.)Uses of distributed object architectures• As a logical model for structuring and organizing a system solelyin terms ofservices provided by a number of distributed objects. (E.g., a dataminingsystem.)• As a flexible means of implementing C/S systems. Both clientsand servers arerealised as distributed objects communicating through a softwarebus.A data mining systemDatabase 1Database 2Database 3Integrator 1Integrator 2VisualiserDisplayReport gen.Disadvantages of distributed object architectures• Complex to design due to model generality and flexibility inservice provision.• C/S systems seem to be a more natural model for most systems.(They reflectmany human service transactions.)CORBA (Common Object Request Broker Architecture)• International standards for an Object Request Broker (ORB) –middleware tomanage communications between distributed objects.• Several implementation of CORBA are available (Unix and MSOS’s).
    • • Defined by the Object Management Group (>500 companies,including Sun, HP,IBM).• DCOM (Distributed Component Object Model) is an alternativestandarddeveloped and implemented by Microsoft.Components of the OMG vision of a distributed application• Application objects designed and implemented for thisapplication.• Domain-specific objects defined by the OMG. (e.g.,finance/insurance,healthcare)• Fundamental CORBA distributed computing services such asdirectories andsecurity management.• Horizontal facilities (such as user interface facilities) used inmany differentapplicationsCORBA application structureObject request brokerDomainfacilitiesHorizontalCORBA facilitiesApplicationobjectsMajor elements of the CORBA standards• An application object model where objects encapsulate state andhave a welldefined,language-neutral interface defined in an IDL (interface definitionlanguage).• An object request broker (ORB) that locates objects providingservices, sendsservice requests, and returns results to requesters.
    • • A set of general object services of use to many distributedapplications.• A set of common components built on top of these services.(Task forces arecurrently defining these.)CORBA objects• Objects that provide services have IDL skeletons that link theirinterface to animplementation.• Calling objects have IDL stubs for every object being called.• Objects do not need to know the location or implementationdetails of otherobjects.Object request broker (ORB)• The ORB handles object communications. It knows of all objectsin the systemand their interfaces.• The calling object binds an IDL stub that defines the interface ofthe called object.• Calling this stub results in calls to the ORB, which then calls therequired objectthrough a published IDL skeleton that links the interface to theserviceimplementation.ORB-based object communicationso1 o2S (o1) S (o2)IDLstubIDLskeletonObject Request BrokerInter-ORB communications• ORBs handle communications between objects executing on thesame machine.
    • • Inter-ORB communications are used for distributed object calls.• CORBA supports ORB-to-ORB communication by providing allORBs access toall IDL interface definitions and by implementing the OMG’sstandard GenericInter-ORB Protocol (GIOP).Inter-ORB communicationso1 o2S (o1) S (o2)IDL IDLObject Request Brokero3 o4S (o3) S (o4)IDL IDLObject Request BrokerExamples of general CORBA services• Naming and trading services – these allow objects to discoverand refer to otherobjects on the network.• Notification services – these allow objects to notify other objectsthat an event hasoccurred.• Transaction services – these support atomic transactions androllback on failure.Key points• Almost all new large systems are distributed systems.• Distributed systems support resource sharing, openness,concurrency, scalability,fault tolerance, and transparency.• Client-server architectures involve services being delivered byservers toprograms operating on clients.• User interface software always runs on the client and datamanagement on theserver.
    • • In a distributed object architecture, there is no distinctionbetween clients andservers.• Distributed object systems require middle-ware to handle objectcommunications.• The CORBA standards are a set of middle-ware standards thatsupport distributedobject architectures.ActivitiesActivity 1:- Explain why distributed systems are inherently morescalable thancentralized systems. What are the likely limits on the scalability ofthe system?Activity 2:- What is the fundamental difference between a fat-client and a thin-clientapproach to client-server systems development? Explain why theuse of Java as animplementation language blurs the distinction between theseapproaches.Activity 3:- It is proposed to develop a system for stockinformation where dealers canaccess information about companies and can evaluate variousinvestment scenarios usinga simulation system. Different dealers use this simulation indifferent ways according totheir experience and the type of stocks that they are dealing with.Suggest a client-serverarchitecture for this system that shows where functionality islocated justify the clientserver system model that you have chosen.Activity 4:- Distributed systems based on a client-server modelhave been developedsince the 1980s but it is only recently that system architecturesbased on disrupted objects
    • have been implemented. Suggest three reasons why this should bethe case.Activity 5:- Explain why the use of distributed objects with anobject request brokersimplifies the implementation of scalable client- server systems.Illustrate your answerwith an example.Activity 6:- How is the CORBA IDL used to supportcommunications between objectsthat have been implemented in different programming languages?Explain why thisapproach may cause performance problems if there are radicaldifferences between thelanguages used for object implementation.Activity 7:- What are the basic facilities that must be provided byan object requestbroker?Lecture-11: Object-Oriented DesignObjectives• To explain how a software design may be represented as a set ofinteractingobjects that encapsulate their own state and operations.• To describe the activities in the object-oriented design process• To introduce various models used to describe an object-orienteddesign• To show how the UML may be used to represent these modelsTopics covered• Objects and object classes• An object-oriented design process• Design evolutionCharacteristics of OOD• Allows designers to think in terms of interacting objects thatmaintain their ownstate and provide operations on that state instead of a set offunctions operating on
    • shared data.• Objects hide information about the representation of state andhence limit accessto it.• Objects may be distributed and may work sequentially or inparallel.A design strategy based on “information hiding”…• A useful definition of information hiding:Potentially changeable design decisions are isolated(i.e., “hidden”) to minimize the impact of change.- David ParnasInteracting objectsstate o3o3:C3state o4o4: C4state o1o1: C1state o6o6: C1state o5o5:C5state o2o2: C3ops1() ops3 () ops4 ()ops3 () ops1 () ops5 ()Advantages of OOD• Easier maintenance. Objects may beunderstood as stand-alone entities.• Objects are appropriate reusable components.• For some systems, there is an obvious mapping from real worldentities to systemobjects.Object-oriented development
    • • OO Analysis: concerned with developing an object model of theapplicationdomain.• OO Design: concerned with developing an object-orientedsystem model toimplement requirements• OO Programming: concerned with realising an OOD using anOOprogramming language such as Java or C++.Objects and object classes• Objects are entities with state and a defined set of operations onthat state._State is represented as a set of object attributes. _Operations provide services to other objects when requested. • Object classes are templates for objects. _An object class definition includes declarations of all attributes and operations associated with an object of that class. _They may inherit attributes and services from other object classes. The Unified Modeling Language • Several different notations for OOD were proposed in the 1980s and 1990s. (Booch, Rumbaugh, Jacobson, Coad & Yourdon, Wirfs, …) • UML is an integration of these notations. • It describes a number of different models that may be produced during OO analysis and design (user view, structural view, behavioural view, implementation view, …) Employee object class (UML) Object communication E m p lo y e e n a m e : s t r in g a d d re s s : s tr in g
    • d a t e O fB ir t h : D a t ee m p lo y e e N o : in te g e rs o c ia lS e c u r ity N o : s tr in gd e p a r tm e n t : D e p tm a n a g e r : E m p lo y e es a l a ry : i n te g e rs ta t u s : { c u r re n t , le ft , re tir e d }t a xC o d e : in te g e r...join()leave()r e t i re ( )c h a n g e D e t a i ls ( )• Conceptually, objects communicate bymessage passing.• Messages include:_The name of the service requested, _A copy of the information required to carry out the service, and _the name of a holder for the result of the service. • In practice, messages are often implemented by procedure calls Message examples // Call a method associated with a buffer // object that returns the next value // in the buffer v = circularBuffer. Get (); // Call the method associated with a // thermostat object that sets the // temperature to be maintained thermostat.setTemp (20); Generalization and inheritance • Objects are members of classes, which define attribute types and operations. • Classes may be arranged in a hierarchy where one class (a super- class) is a generalization of one or more other classes (sub-classes) • A sub-class inherits the attributes and operations from its super class and may add
    • new methods or attributes of its own.A UML generalisation hierarchyEmployeeProgrammerprojectprogLanguageManagerProjectManagerbudgetsControlleddateAppointedprojectsDept.ManagerStrategicManagerdept responsibilitiesAdvantages of inheritance• It is an abstraction mechanism, which may be used to classifyentities.• It is a reuse mechanism at both the design and the programminglevel.• The inheritance graph is a source of organisational knowledgeabout domains andsystems.Problems with inheritance• Object classes are not self-contained (i.e., they cannot beunderstood withoutreference to their super-classes).• Designers have a tendency to reuse the inheritance graph createdduring analysis.(Inheritance graphs of analysis, design and implementation havedifferentfunctions.)Inheritance and OOD
    • • Inheritance is a useful implementation concept, which allowsreuse of attributeand operation definitions.• Some feel that identifying an inheritance hierarchy or network isalso afundamental part of object-oriented design. (Obviously, this canonly beimplemented using an OOPL.)• Others feel this places unnecessary restrictions on theimplementation.• Inheritance introduces complexity and this is undesirable,especially in criticalsystems.UML associations• Objects and object classes participate in various types ofrelationships with otherobjects and object classes.• In the UML, a generalized relationship is indicated by anassociation.• Associations may be annotated with information that describestheir nature.• Associations can be used to indicate that an attribute of an objectis an associatedobject or that a method relies on an associated object.An association modelEmployee DepartmentManageris-member-ofis-managed-bymanagesConcurrent objects• The nature of objects as self-contained entities make them wellsuited for concurrentimplementation.• The message-passing model of object
    • communication can be implemented directly if objects are runningon separateprocessors in a distributed system.Concurrent object implementation: servers and active objects• Servers (Passive objects): implemented as parallel processes withentry pointscorresponding to object operations. If no calls are made to it, theobject suspendsitself and waits for further requests for service.• Active objects: implemented as parallel processes and theinternal object statemay be changed by the object itself and not simply by externalcalls.Example: an active transponder object• A transponder object broadcasts an aircraft’s position.• The object periodically updates the position by triangulation fromsatellites.An object-oriented design process1. Define the context and modes of use of the system.2. Design the system architecture.3. Identify the principal system objects.4. Develop design models (static and dynamic).5. Specify object interfaces.Weather system description• A weather data collection system is required to generate weathermaps on aregular basis using data collected from remote, unattended weatherstations andother data sources such as weather observers, balloons andsatellites. Weatherstations transmit their data to the area computer in response to arequest from thatmachine.• The area computer validates the collected data and integrates itwith the data from
    • different sources. The integrated data is archived and, using datafrom thisarchive and a digitised map database a set of local weather maps iscreated. Mapsmay be printed for distribution on a special-purpose map printer ormay bedisplayed in a number of different formats.• A weather station is a package of software-controlledinstruments, which collectsdata, performs some data processing and transmits this data forfurther processing.The instruments include air and ground thermometers, ananemometer, a windvane, a barometer and a rain gauge. Data is collected every fiveminutes.• When a command is issued to transmit the weather data, theweather stationprocesses and summarises the collected data. The summarised datais transmittedto the mapping computer when a request is received.1.Define system context and modes of use• Goal: develop an understanding of the relationships between thesoftware beingdesigned and its external environment.• System context: a static model that describes other systems inthe environment.• The context of the weather station is illustrated below usingUML packages.Context of weather station• Modes of system use – a dynamic model that describes how thesystem willinteract with its environment.«subsystem»Data collection«subsystem»
    • Data processing«subsystem»Data archiving«subsystem»Data displayWeatherstationSatelliteCommsBalloonObserverDatacheckingDataintegrationMap store Data storeDatastorageMapUserinterfaceMapdisplayMapprinter• Modes of weather station use are illustrated below using a UMLuse-case model.Use-cases for the weather stationExternal entity(weather datacollection sys) C PossibleinteractionsUse-case descriptionS ta rtu pS h u td o wn
    • Re p o rta lib ra teTe s tS y s tem We a th e r s ta tionU s e -c a s e Re p o rtA c to rs W e a th e r d a ta c o lle c tio n s ys tem , W e a the r s ta tio nD ata T h e w e a th e r s ta tio n s e n d s a s um m a ry o fth e w e a th e r d a ta th a th a s b e e n c o lle c te d from th e in s trum e n ts in th e c olle c tio n p e rio dto th e w e a th e r d a ta c o lle c tio n s ys tem . T h e d a tas e n t a re th em a x im um m in im um a n d a v e ra g e g ro u n d a n d air tem p e ra tu re s ,th e m a x im um , m in im um a n d a ve ra g e a ir p re s s ure s , th em a x im um , m in im um a n d a ve ra g e w in d s p e e ds , th e to ta lra in fa ll a n d th e w in d d ire c tio n a s s am p le d a t 5 min u te in te rv a ls .S tim u lu s T h e w e a th e r d a ta c o lle c tio n s ys tem es ta b lis h e s a m o d e m lin kw ith th e w e a th e r s ta tio n a n d re q u e s ts tra n sm is sio n o f th e d a ta .R e s p o n s e T h e s um m a r is e d d a ta is s e n t to th ew e a th e r d a ta c o lle c tio ns ys temC om m en ts W e a th e r s ta tio n s a re u s u a lly a s k ed to re p o rt o n c e p e r h o u r b u tth is fre q u e n c y m a y d if fe r from o n e s ta tio n to th e oth e r a n d m a yb e m o d if ie d in fu tu re .basis for “information hiding”2.Design system architecture
    • • A layered architecture is appropriate for the weather station:_Interface layer for handling communications _Data collection layer for managing instruments _Instruments layer for collecting data • Rule of Thumb: There should be no more than 7 entities in an architectural model. Weather station architecture UML annotations «subsystem» Da ta collection «subsystem» Instruments «subsystem» Interface Weather station Manages all external communications Collects and summarises weather data Package of instruments for raw data collections UML “nested packages” 3. Identify principal system objects • Identifying objects (or object classes) is the most difficult part OO design. • There is no “magic formula” – it relies on the skill, experience, and domain knowledge of system designers • An iterative process – you are unlikely to get it right the first time. Approaches to object identification
    • • Use a grammatical approach based on a natural languagedescription of thesystem (Abbott’s heuristic).• Associate objects with tangible things in the application domain(e.g. devices).• Use a behavioural approach: identify objects based on whatparticipates in whatbehaviour.• Use scenario-based analysis. The objects, attributes and methodsin each scenarioare identified.• Use an information-hiding based approach. Identify potentiallychange-abledesign decisions and isolate these in separate objects.Weather station object classes• Weather station – interface of the weather station to itsenvironment. It reflectsinteractions identified in the use-case model.• Weather data – encapsulates summarised data from theinstruments.• Ground thermometer, Anemometer, Barometer – applicationdomain“hardware” objects related to the instruments in the systemWeather station object classesident ifierreportWeather ()calibrate (instruments)test ()startup (instrum ents)shutdown (instrum ents)WeatherStationtes t ()calibrate ()Groundthe rmometer
    • temperatureAnemometerwin dSpeedwin dDirec tiontes t ()Ba rom eterpressureheighttest ()calibrate ()WeatherDataairTem peraturesgroundTem peratureswin dSpeedswin dDirectionspressuresrainfallcollect ()summarise ()Other objects and object refinement• Use domain knowledge to identify more objects, operations, andattributes._Weather stations should have a unique identifier. _Weather stations are remotely situated so instrument failures have to be reported automatically. Therefore, attributes and operations for self checking are required. • Active or passive objects? _Instrument objects are passive and collect data on request rather than autonomously. This introduces flexibility (how?) at the expense of controller processing time. _Are any active objects required? 4. Develop design models
    • • Design models show the relationships among objects and objectclasses.• Static models describe the static structure of the system in termsof object andobject class relationships.• Dynamic models describe the dynamic interactions amongobjects.Examples of design models• Sub-system models show logical groupings of objects intocoherent sub-systems.(static)• Sequence models show the sequence of object interactionsassociated withsystem uses. (dynamic)• State machine models show how individual objects change theirstate inresponse to events. (dynamic)• Other models include use-case models, aggregation models,generalisation(inheritance) models, etc.Subsystem models• In the UML, these are shown using packages, an encapsulationconstruct.• This is a logical model – the actual organization of objects in thesystem asimplemented may be different.Weather station subsystemsannotationsWr«subsystem»InterfaceCommsControllereatherStation«subsystem»
    • Data collection«subsystem»InstrumentsAirthermometerWeatherDataRainGauge AnemometeInstrumentStatusSequence models• Objects are arranged horizontally across the top.• Time is represented vertically; models are read top to bottom.• Interactions are represented by labelled arrows – different stylesof arrowsrepresent different types of interaction.• A thin rectangle in an object lifeline represents the time when theobject is thecontrolling object in the system.Data collection sequenceNo reply expectedReturn ofsummarise ()control:CommsControllerrequest (report)acknowledge ()report ()reply (report)acknowledge ()send (report):WeatherStation :WeatherDataWeather station state machine model5. Object interface specificationShutdown Waiting TestingTransmitting
    • CollectingSummarisingCalibratingtransmission donecalibrate ()startup () test ()shutdown ()calibration OKtest completeweather summarycompleteclock collectiondoneOperationreportWeather ()• Designers should avoid revealing data representation informationin theirinterface design. (operations access and update data)• Objects may have several logical interfaces, which areviewpoints on the methodsprovided. (supported directly in Java)• The UML uses class diagrams for interface specification butpseudocode mayalso be used.Design evolution• Hiding information in objects means that changes made to anobject do not affectother objects in an unpredictable way.• Assume pollution-monitoring facilities are to be added to weatherstations.• Pollution readings are transmitted with weather data.Changes required• Add an object class called “Air quality” as part of WeatherStation
    • • Add an operation reportAirQuality to WeatherStation. Modify thecontrolsoftware to collect pollution readings• Add objects representing pollution monitoring instruments.Pollution monitoringNO Datasmo k eD a tab e n z eneD a tac o lle ct ( )sum ma r is e ( )A i r q ua l ityid e n t ifie rre p o rtWe a t h e r ()re p o rtA irQ u a lity ()c a lib ra te (in st rume n ts)t e st ()s ta rt u p (in s trum e n ts )sh u td own ( in s trume n t s)We a th e rS ta tionP o ll utio n m on ito ring ins tr um e n tsNO me te r Sm o keM e te rB e n z e neMe t e rKey points• OOD results in design components with their own privatestate andoperations.• Objects should have constructor and inspection operations.They provideservices to other objects.• Objects may be implemented sequentially or concurrently.• The Unified Modeling Language provides different notationsfor definingdifferent object models.• A range of different models may be produced during an object-oriented design
    • process. These include static and dynamic system models• Object interfaces should be defined precisely.• Object-oriented design simplifies system evolution.ActivitiesActivity 1:- Explain why adopting an approach to design that isbased on loosely coupledobjects that hide information about their representation should leadto a design whichmay be readily modified.Activity 2:- Using examples, explain the difference between anobject and an objectclass.Activity 3:- Under what circumstances might it be appropriate todevelop a design whereobjects execute concurrently?Activity 4:- Using the UML graphical notation for object classes,design the followingobject classes identifying attributes and operations. Use your ownexperience to decideon the attributes and operations that should be associated withthese objects:• A telephone:• A printer for a personal computer;• A personal stereo system;• A bank account;• A library catalogue.Activity 5:- Develop the design of the weather station to show theinteraction betweenthe data collection sub- system and the instruments that collectweather data. Usesequence charts to show this interaction.Activity 6:- Identify possible objects in the following systems anddevelop an objectoriented design for them. You may make any reasonableassumptions about the systems
    • when deriving the design.• A group diary and time management system is intended tosupport the timetablingof meetings and appointments across a group of co-workers. Whenanappointment is to be made which involves a number of people, thesystem finds acommon slot in each of their diaries and arranges the appointmentfor that time. Ifno common slots are available, it interacts with the users torearrange theirpersonal diaries to make room fort the appointment.• A petrol (gas) station is to be set up for fully automatedoperation. Derivers swipetheir credit card through a reader connected to the pump; the cardis verified bycommunication with a credit company computer and a fuel limitestablished. Thedriver may then take the fuel required when fuel delivery iscomplete and thepump hose is returned to its holster, the driver’s credit card accountis debitedwith the cost to the furl taken. The credit card is returned afterdebiting. If the cardis invalid, it is returned buy the pump before fuel is dispensed.Activity 7:- Draw a sequence diagram showing the interactions ofobjects in a groupdiary system when a group of people arrange a meeting.Lecture- 12: Real-time Software Design• Designing embedded software systems whosebehaviour is subjectto timing constraintsObjectives
    • • To explain the concept of a real-time system and why thesesystems are usuallyimplemented as concurrent processes• To describe a design process for real-time systems• To explain the role of a real-time executive• To introduce generic architectures for monitoring and control anddata acquisitionsystemsTopics covered• Systems design• Real-time executives• Monitoring and control systems• Data acquisition systemsReal-time systems• Systems, which monitor and control theirenvironment• Inevitably associated with hardware devices•Sensors: Collect data from the system environment•Actuators: Change (in some way) the systemsenvironment• Time is critical. Real-time systems MUSTrespond within specified timesDefinition• A real-time system is a software system where the correctfunctioning of thesystem depends on the results produced by the system and the timeat which theseresults are produced• A ‘soft’ real-time system is a system whose operation is degradedif results arenot produced according to the specified timing requirements• A ‘hard’ real-time system is a system whose operation isincorrect if results arenot produced according to the timing specificationStimulus/Response Systems
    • • Given a stimulus, the system must produce aresponse within a specified time• Periodic stimuli. Stimuli, which occur atpredictable time intervals•For example, a temperature sensor may be polled 10 timesper second• Aperiodic stimuli. Stimuli, which occur atunpredictable times•For example, a system power failure may trigger aninterrupt, which must be processed by the systemArchitectural considerations• Because of the need to respond to timing demands made bydifferentstimuli/responses, the system architecture must allow for fastswitching betweenstimulus handlers• Timing demands of different stimuli are different so a simplesequential loop isnot usually adequate• Real-time systems are usually designed as cooperating processeswith a real-timeexecutive controlling these processesA real-time system modelReal-timecontrol systemSensor Sensor Sensor Sensor Sensor SensorSystem elements• Sensors control processes•Collect information from sensors. May buffer informationcollected in responseto a sensorstimulus• Data processor•Carries out processing of collected information and computes thesystem
    • response• Actuator control•Generates control signals for the actuatorSensor/actuator processesDataprocessorActuatorcontrolActuatorSensorcontrolSensorStimulus ResponseSystem design• Design both the hardware and the software associated withsystem. Partitionfunctions to either hardware or software• Design decisions should be made on the basis on non-functionalsystemrequirements• Hardware delivers better performance but potentially longerdevelopment and lessscope for changeHardware and software designR-T systems design processEstablish systemrequirementsPartitionrequirementsHardwarerequirementsHardwaredesignSoftwarerequirements
    • Softwaredesign• Identify the stimuli to be processed and the required responses tothese stimuli• For each stimulus and response, identify the timing constraints• Aggregate the stimulus and response processing into concurrentprocesses.• A process may be associated with each class of stimulus andresponse• Design algorithms to process each class of stimulus and response.These mustmeet the given timing requirements• Design a scheduling system, which will ensure that processes arestarted in timeto meet their deadlines• Integrate using a real-time executive or operating systemTiming constraints• May require extensive simulation and experiment to ensure thatthese are met bythe system• May mean that certain design strategies such as object-orienteddesign cannot beused because of the additional overhead involved• May mean that low-level programming language features have tobe used forperformance reasonsState machine modelling• The effect of a stimulus in a real-time system may trigger atransition from onestate to another.• Finite state machines can be used for modelling real-timesystems.• However, FSM models lack structure. Even simple systems canhave a complexmodel.
    • • The UML includes notations for defining state machine modelsMicrowave oven state machineFull powerEnableddo: operateovenFullpowerHalfpowerHalfpowerFullpowerNumberTimerDooropenDoorclosedDoorclosedSystemfaultStartdo: set power= 600Half powerdo: set power= 300Set timedo: get numberexit: set timeDisabledOperation
    • TimerCancelWaitingdo: displaytimeWaitingdo: displaytimedo: displayReadydo: displayWaitingReal-time programming• Hard-real time systems may have to programmed in assemblylanguage to ensurethat deadlines are met• Languages such as C allow efficient programs to be written butdo not haveconstructs to support concurrency or shared resource management• Ada as a language designed to support real-time systems designso includes ageneral-purpose concurrency mechanismJava as a real-time language• Java supports lightweight concurrency (threads and synchronizedmethods) andcan be used for some soft real-time systems• Java 2.0 is not suitable for hard RT programming orprogramming where precisecontrol of timing is required•Not possible to specify thread execution time•Uncontrollable garbage collection•Not possible to discover queue sizes for shared resources•Variable virtual machine implementation•Not possible to do space or timing analysisReal-time executives
    • • Real-time executives are specialised operating systems, whichmanage theprocesses in the RTS• Responsible for process management andresource (processor and memory) allocation• May be based on a standard RTE kernel whichis used unchanged or modified for a particularapplication• Does not include facilities such as file managementExecutive components• Real-time clock•Provides information for process scheduling.• Interrupt handler•Manages aperiodic requests for service.• Scheduler•Chooses the next process to be run.• Resource manager•Allocates memory and processor resources.• Despatcher•Starts process execution.Non-stop system components• Configuration manager•Responsible for the dynamic reconfiguration of the systemsoftware and hardware. Hardware modules may be replaced andsoftwareupgraded withoutstopping the systems• Fault manager•Responsible for detecting software and hardware faults andtaking appropriate actions (e.g. switching to backup disks) toensure that thesystem continues inoperationReal-time executive componentsProcess resource
    • requirementsSchedulerSchedulinginformationResourcemanagerDespatcherReal-timeclockProcessesawaitingresourcesReadylistInterrupthandlerAvailableresourcelistProcessorlistExecutingprocessReadyprocessesReleasedresourcesProcess priority• The processing of some types of stimuli mustsometimes take priority• Interrupt level priority. Highest priority, which isallocated to processes requiring a very fastresponse• Clock level priority. Allocated to periodicprocesses
    • • Within these, further levels of priority may beassignedInterrupt servicing• Control is transferred automatically to apre-determined memory location• This location contains an instruction to jump toan interrupt service routine• Further interrupts are disabled, the interruptserviced and control returned to the interruptedprocess• Interrupt service routines MUST be short,simple and fastPeriodic process servicing• In most real-time systems, there will be severalclasses of periodic process, each with differentperiods (the time between executions),execution times and deadlines (the time bywhich processing must be completed)• The real-time clock ticks periodically and eachtick causes an interrupt which schedules theprocess manager for periodic processes• The process manager selects a process, whichis ready for executionProcess management• Concerned with managing the set of concurrent processes• Periodic processes are executed at pre-specified time intervals• The executive uses the real-time clock to determine when toexecute a process• Process period - time between executions• Process deadline - the time by which processing must becompleteRTE process managementProcess switchingResource managerAllocate memory
    • and processorSchedulerChoose processfor executionDespatcherStart execution on anavailable processor• The scheduler chooses the next process to be executed by theprocessor. Thisdepends on a scheduling strategy, which may take the processpriority intoaccount• The resource manager allocates memory and a processor for theprocess to beexecuted• The despatcher takes the process from ready list, loads it onto aprocessor andstarts executionScheduling strategies• Non pre-emptive scheduling•Once a process has been scheduled for execution, it runs tocompletion or untilit is blocked forsome reason (e.g. waiting for I/O)• Pre-emptive scheduling•The execution of executing processes may be stopped if a higherpriorityprocess requires service• Scheduling algorithms•Round-robin•Rate monotonic•Shortest deadline firstMonitoring and control systems• Important class of real-time systems• Continuously check sensors and take actions
    • depending on sensor values• Monitoring systems examine sensors andreport their results• Control systems take sensor values and controlhardware actuatorsBurglar alarm system• A system is required to monitor sensors on doors and windows todetect thepresence of intruders in a building• When a sensor indicates a break-in, the system switches on lightsaround the areaand calls police automatically• Sensors•Movement detectors, window sensors, door sensors.•50 window sensors, 30 door sensors and 200 movementdetectors•Voltage drop sensor• Actions•When an intruder is detected, police are calledautomatically.•Lights are switched on in rooms with active sensors.•An audible alarm is switched on.•The system switches automatically to backup power when avoltage drop isdetected.The R-T system design process• Identify stimuli and associated responses• Define the timing constraints associated witheach stimulus and response• Allocate system functions to concurrentprocesses• Design algorithms for stimulus processing andresponse generation• Design a scheduling system, which ensures thatprocesses will always be scheduled to meet
    • their deadlinesStimuli to be processed• Power failure•Generated aperiodically by a circuit monitor. Whenreceived, the system must switch to backup power within 50ms• Intruder alarm•Stimulus generated by system sensors. Response is to callthe police, switch on building lights and the audible alarmTiming RequirementsStimulus/Response Timing requirementsPower fail interrupt The switch to backup power must becompletedwithin a deadline of 50 ms.Door alarm Eac h door alarm sh ould be polled twice persecond.Window alarm Eac h window alarm sh ould be polled twice persecond.Movement detector Eac h movement detector should be polledtwiceper second.Audible alarm The audible alarm should be switched on within1/2 second of an alarm being raised by a sensor.Lights sw itch The lights should be switched on within 1/2second of an alarm b eing raised by a sensor.Communica tions The ca ll to the police should be started within 2seconds o f an alarm being raised by a sensor.Voice synthesiser A synthesised message should be availablewithin 4 s econds of an alarm being raised by asensor.Process architectureLighting controlAudible alarm Voice synthesizerAlarm systemprocessPower switch
    • processBuilding monitorprocessCommunicationprocessDoor sensorprocessMovementdetector processWindow sensorprocess560Hz400Hz 60Hz 100HzPower failureinterruptAlarmsystemBuilding monitorAlarmsystemAlarm systemAlarm systemDetector status Sensor status Sensor statusRoom numberAlert messageRoom numberRoom numberBuilding monitor process 1}// See http://www.software-engin.com/ for links to thecomplete Java code for this// exampleclass BuildingMonitor extends Thread {BuildingSensor win, door, move ;Siren siren = new Siren () ;
    • Lights lights = new Lights () ;Synthesizer synthesizer = new Synthesizer () ;DoorSensors doors = new DoorSensors (30) ;WindowSensors windows = new WindowSensors (50) ;MovementSensors movements = new MovementSensors(200) ;PowerMonitor pm = new PowerMonitor () ;BuildingMonitor(){// initialise all the sensors and start the processessiren.start () ; lights.start () ;synthesizer.start () ; windows.start () ;doors.start () ; movements.start () ; pm.start () ;Building monitor process 2public void run (){int room = 0 ;while (true){// poll the movement sensors at least twice per second (400Hz)move = movements.getVal () ;// poll the window sensors at least twice/second (100 Hz)win = windows.getVal () ;// poll the door sensors at least twice per second (60 Hz)door = doors.getVal () ;if (move.sensorVal == 1 | door.sensorVal == 1 |win.sensorVal == 1){// a sensor has indicated an intruderif (move.sensorVal == 1) room = move.room ;if (door.sensorVal == 1) room = door.room ;if (win.sensorVal == 1 ) room = win.room ;lights.on (room) ; siren.on () ; synthesizer.on (room) ;break ;
    • } //Bu}} lights.shutdown () ;siren.shutdown () ;synthesizer.shutdown () ;windows.shutdown () ; doors.shutdown () ;movements.shutdown () ;} // runildingMonitorControl systems• A burglar alarm system is primarily a monitoring system. Itcollects data fromsensors but no real-time actuator control• Control systems are similar but, in response to sensor values, thesystem sendscontrol signals to actuators• An example of a monitoring and control system is a system,which monitorstemperature and switches heaters on and offA temperature control systemSensorprocess500Hz500HzSensorvaluesData acquisition systems• Collect data from sensors for subsequentprocessing and analysis.• Data collection processes and processingprocesses may have different periods anddeadlines.• Data collection may be faster than processinge.g. collecting information about an explosion.• Circular or ring buffers are a mechanism for
    • smoothing speed differences.Reactor data collection• A system collects data from a set of sensorsmonitoring the neutron flux from a nuclearreactor.• Flux data is placed in a ring buffer for laterprocessing.• The ring buffer is itself implemented as aconcurrent process so that the collection andprocessing processes may be synchronized.Reactor flux monitoringSensors (each daProcess DisplaydataSensor databufferSensorprocessSensoridentifier andvalueProcessedflux levelta flow is a sensor value)A ring bufferMutual exclusion• Producer processes collect data and add it tothe buffer. Consumer processes take data from the buffer and makeelementsavailableConsumerprocessProducerprocess• Producer and consumer processes must be
    • mutually excluded from accessing the sameelement.• The buffer must stop producer processesadding information to a full buffer and consumer processes tryingto takeinformation from an empty buffer.Java implementation of a ring buffer 1class CircularBuffer{int bufsize ;SensorRecord [] store ;int numberOfEntries = 0 ;int front = 0, back = 0 ;CircularBuffer (int n) {bufsize = n ;store = new SensorRecord [bufsize] ;} // CircularBuffersynchronized void put (SensorRecord rec ) throwsInterruptedException{if ( numberOfEntries == bufsize)wait () ;store [back] = new SensorRecord (rec.sensorId,rec.sensorVal) ;back = back + 1 ;if (back == bufsize)back = 0 ;numberOfEntries = numberOfEntries + 1 ;notify () ;} // putJava implementation of a ring buffer 2synchronized SensorRecord get () throwsInterruptedException{SensorRecord result = new SensorRecord (-1, -1) ;
    • if (numberOfEntries == 0)wait () ;result = store [front] ;front = front + 1 ;if (front == bufsize)front = 0 ;numberOfEntries = numberOfEntries - 1 ;notify () ;return result ;} // get} // CircularBufferKey points• Real-time system correctness depends not juston what the system does but also on how fast itreacts• A general RT system model involves associating processes withsensors andactuators• Real-time systems architectures are usually designed as a numberof concurrentprocesses• Real-time executives are responsible forprocess and resource management.• Monitoring and control systems poll sensors and send controlsignal to actuators• Data acquisition systems are usually organised according to aproducer consumermodel• Java has facilities for supporting concurrency but is not suitablefor thedevelopment of time-critical systemsActivitiesActivity 1:- Using examples, explain why real time systemsusually have to beimplemented using processes.
    • Activity 2:- Explain why an object oriented approach to softwaredevelopment may notbe suitable for real time systems.Activity 3:- Draw state machine models of the control software forthe followingsystems:• An automatic washing machine, which has different programs fordifferent typesof clothes.• The software for a compact disc player.• A telephone answering machine, which records incomingmessages and displaysthe number of accepted messages on an LED display. The systemshould allowthe telephone owner to dial in, type a sequence of numbers(identified as tones)and have the recorded messages replayed over the phone.• A drinks vending machine, which can dispense coffee with andwithout milk andsugar. The user deposits a coin and makes his or her selection bypressing a buttonon the machine. This causes a cup with powdered coffee to beoutput. The userplaces this cup under a tap, presses another button and hot eater isdispensed.Activity 4:- Discuss the strengths and weaknesses of Java as aprogramming languagefor real time systems.Activity 5:- You are asked to work on a real-time developmentproject for a militaryapplication but have no previous experience of projects in thatdomain. Discuss what you,as a professional software engineer, should do before starting workon the project.
    • Lecture-13: Design with ReuseObjectives• To explain the benefits and some potential problems withsoftware reuse.• To describe different types of reusable elements and processesfor reuse.• To introduce application families as a route to reuse.• To describe design patterns as high-level abstractions thatpromote reuse.Topics covered• Component-based development• Application families• Design patternsReuse-based software engineering• In most engineering disciplines, systems are routinely designedby composingelements that have been used in other systems.• This has not been true in SE, but to reduce risks and acceleratedevelopment, it isnow recognized that we need to adopt design processes based onsystematic reuse.Software reuse practice• Application system reuse – widely practised as softwaresystems areimplemented as application families. COTS reuse is becomingincreasinglycommon.• Component reuse – now seen as the key to effective andwidespread reusethrough Component-Based Software Engineering (CBSE).However, it is stillrelatively immature.• Function reuse – libraries of reusable functions have beencommon for 40 years.Benefits of reuse
    • • Increased reliability – when reused elements have been triedand tested in avariety of working systems.• Reduced process risk – less uncertainty of cost compared to newdevelopment.• More effective use of specialists – re-use elements instead ofexperts.• Standards compliance – when standards are embedded inreusable elements.• Accelerated development – reduced development and validationtime.Requirements for design with reuse• Must be possible to find appropriate reusable elements.• Must be confident that the elements will be reliable and willbehave as specified.• Elements must be documented so that they can be understoodand, whennecessary, modified.Reuse problems• Increased maintenance costs – especially if source code /documentation absent.• Lacks of tool support – CASE toolsets do not supportdevelopment with reuse.• Not-invented-here syndrome• Repositories of reusable elements – techniques for classifying,cataloguing, andretrieving elements are immature.• Finding, understanding, and adapting reusable elements takestime.Component-based development• Component-Based Software Engineering (CBSE) is adevelopment approachbased on systematic reuse.• CBSE emerged in the late 1990’s due to failure of OOdevelopment to lead to
    • extensive reuse.• Components are designed to be general service providers.Critical characteristics of a reusable component• An independent executable entity: source code is typically notavailable so thecomponent is not compiled with other system elements.• All interactions are through a published (2-part) interface –internal state is neverexposed.Component interface• “Provides interface” – defines the services that are provided bythe componentto other system elements.• “Requires interface” – defines the services that must be madeavailable to thecomponent by other system elements in order to operate.Component interfacesPrinting services componentPrinter descriptionControl interfaceP rinterIntRequires interface Component Provides interfaceRequires interface Provides interfacePrintPrintServiceGetQueueRemoveTransferRegisterUnregisterGetPDfileComponent abstraction levels• Functional abstraction – implements a single function (e.g.,square root)• Casual groupings – loosely related entities such as datadeclarations and functions
    • • Data abstractions – a data abstraction or object class• Cluster abstractions – related object classes that work together• System abstraction – an entire, self-contained system (e.g., MSExcel)CBSE processes• Component-based reuse may be opportunistic, or it may drive thedevelopmentprocess.• In reuse-driven development, system requirements are modifiedto reflect theavailable components.• CBSE often involves an evolutionary development process withcomponentsbeing “glued together” using a scripting language. (e.g., Unix shell,Visual Basic,TCL/TK)An opportunistic reuse processDesignsystemaachitectureSpecifycomponentsSearch forreusablecomponentsIncorporatediscoveredcomponentsthe “we might get lucky” approachReuse-driven developmentSearch forreusablecomponentsOutlinesystem
    • requirementsModify requirementsaccording todiscoveredcomponentsCBSE problems• Component incompatibilities: may mean that cost and schedulesavings are lessthan expected.• Finding and understanding components: repositories and toolsupport arelacking.• Managing evolution as requirements change: source code istypically notavailable. (“waiting for the next release”)Application families• An application family or product line is a related set ofapplications that has acommon, domain-specific architecture.• The common core of the application family is reused each time anew applicationis required.• Each specific application is specialized in some way.Application family specialization• Platform specialization – different versions of the applicationare developed fordifferent platforms.• Configuration specialization – different versions of theapplication are created tohandle different peripheral devices.• Functional specialization – different versions of the applicationare created forcustomers with different requirements.Family member developmentElicit
    • stakeholderrequirementsChoose closestfitfamilymember Deliver newfamily memberRe-negotiaterequirementsAdapt existingsystemUse existing family member as prototypeDesign patterns (Chris Alexander, mid-70’s)• A way of reusing “accumulated knowledge and wisdom” about aproblem and itssolution.• A design pattern is a description of some problem and theessence of itssolution.• Should be sufficiently abstract to be reusable in differentcontexts.• Often utilize OO characteristics such as inheritance andpolymorphism.Pattern elements (Gamma, ‘95)• Name: a meaningful pattern identifier• Problem description• Solution description: a template for a design solution that can beinstantiated indifferent operational contexts (often illustrated graphically)• Consequences: the results and trade-offs of applying the pattern(analysis andexperience)The Observer pattern (Details: p. 323)• Name: Observer• Description: Separates the display of object state from the objectitself.
    • • Problem description: Used when multiple displays of state areneeded.• Solution description: See UML description• Consequences: Optimisations to enhance display performanceare impractical.Multiple displaysThe Observer patternSubjectA: 40B: 25C: 15D: 20Observer 1 Observer 205025ABCDABCDSubject ObserverAttach (Observer)Detach (Observer)Notify ()Update ()ConcreteSubjectGetState ()subjectStateConcreteObserverUpdate ()observerStatereturn subjectStatefor all o in observerso -> Update ()
    • observerState =subject -> GetState ()Key points• Design with reuse involves designing software around existingexamples of gooddesign and making use of existing software elements.• Advantages are lower costs, faster software development, andlower risks.• CBSE relies on black-box components with defined requires- andprovidesinterfaces.• Software components for reuse should be independent, reflectstable domainabstractions, and provide access to state through interfaceoperations.• COTS product reuse is concerned with the reuse of large-scale,off-the-shelfsystems.• Application families are related applications that have a common,domain-specificarchitecture.• Design patterns are high-level abstractions that documentsuccessful designsolutions.ActivitiesActivity 1:- What are the major technical and non-technical factorswhich hindersoftware reuse? Form your own experience, do you reuse muchsoftware? If not, whynot?Activity 2:- Explain why the savings in cost form reusing existingsoftware is not simpleproportional to the size of the components that are reused.Activity 3:- Give four circumstances where you might recommendagainst softwarereuse.
    • Activity 4:- Suggest possible requires and provides interfaces forthe followingcomponents:• A component implementing a bank account.• A component implementing a language-independent keyboard.Keyboards indifferent countries have different key organizations and differentcharactersets.Activity 5:- What is the difference between an applicationframework and a COTSproduct as for as reuse is concerned? Why is it sometimes easier toreuse a COTS productthan an application framework?Activity 6:- Why are patterns an effective form of design reuse?What are thedisadvantages to this approach to reuse?Activity 7:- The reuse of software raises a number of copyrightand intellectual propertyissues. If a customer pays a software contractor to develop somesystem, who has theright to reuse the developed code? Does the software contractorhave the right to use thatcode as a basis for a generic component? What paymentmechanisms might be used toreimburse providers of reusable components? Discuss these issuesand other ethicalissues associated with the reuse of software.© Copy Right: Rai University11.676.2 49SOFTWARE ENGINEERINGObjectives• To explain why formal specification helps discover problemsin system requirements.• To describe the use of:
    • Algebraic specification techniques, andModel-based specification techniques (including simple pre andpost conditions).Topics Covered• Formal specification in the software process• Interface specification• Behavioural specificationFormal Methods• Formal specification is part of a more general collection oftechniques known as “formal methods.”• All are based on the mathematical representations andanalysis of requirements and software.• Formal methods include:Formal specificationSpecification analysis and property proofsTransformational developmentProgram verification (program correctness proofs)• Specifications are expressed with precisely defined vocabulary,syntax, and semantics.Acceptance and Use• Formal methods have not become mainstream as was oncepredicted, especially in the US.Other, less costly software engineering techniques (e.g., inspections/ reviews) have been successful at increasing systemquality. (Hence, the need for formal methods has been reduced.)Market changes have made time-to-market rather than qualitythe key issue for many systems. (Formal methods do not reducetime-to-market.)The scope of formal methods is limited. They are not wellsuited to specifying user interfaces. (Many interactive applicationsare “GUI-heavy” today.)Formal methods are hard to scale up to very large systems.(Although this is rarely necessary.)The costs of introducing formal methods are high.Thus, the risks of adopting formal methods on most projects
    • outweigh the benefits.• However, formal specification is an excellent way to findrequirements errors and to express requirementsunambiguously.• Projects, which use formal methods invariably, report fewererrors in the delivered software.• In systems where failure must be avoided, the use of formalmethods is justified and likely to be cost-effective.• Thus, the use of formal methods is increasing in criticalsystem development where safety, reliability, and security areimportant.Formal Specification in The Software ProcessRequ irementsspecificationFormalspecificatio nSy stemmo dellin gAr chitecturald es ig nRequ irementsd efinitionHig h-le veld es ig nFormal Specification TechniquesAlgebraic approach : the system is specified in terms of itsoperations and their relationships via axioms.Model-based approach (including simple pre- and postconditions): the system is specified in terms of a state modeland operations are defined in terms of changes to system state.Formal Specification LanguagesUse of Formal Specification• Formal specification is a rigorous process and requires moreeffort in the early phases of software development.• This reduces requirements errors as ambiguities,
    • incompleteness, and inconsistencies are discovered andresolved.• Hence, rework due to requirements problems is greatlyreduced.UNIT IOVERVIEW AND REQUIREMENTSCHAPTER 8LECTURE 14:FORMAL SPECIFICATIONS50 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGDevelopment Costs With Formal SpecificationSp eci ficat io nDes ig n andImpl ement at io nValidat io nSp eci ficat io nDes ig n andImpl ement at io nValidat io nCo stWi th ou t fo rmals pecifi cat io nW i th fo rmals pecifi cat io nSpecification of Sub-system Interfaces• Large systems are normally comprised of sub-systems withwell-defined interfaces.• Specification of these interfaces allows for their independentdevelopment.• Interfaces are often defined as abstract data types or objects.• The algebraic approach is particularly well suited to thespecification of such interfaces.Sub-system Interfaces
    • Su b- sys temAS u b- sys temBInte rf ac eo bj ec tsSpecification Components• Introduction : defines the sort (type name) and declaresother specifications that are used• Description : informally describes the operations on the type• Signature : defines the syntax of the operations in theinterface and their parameters• Axioms : defines the operation semantics by definingaxioms which characterize behaviourTypes of Operations• Constructor operations: operations which create / modifyentities of the type• Inspection operations: operations, which evaluate entities ofthe type being specified• Rule of thumb for defining axioms: define an axiom, whichsets out what is always true for each inspection operationover each constructorModel-based Specification• Algebraic specification can be cumber-some when objectoperations are not independent of object state (i.e., previousoperations).• (System State) Model-based specification exposes the systemstate and defines operations in terms of changes to thatstate.• Z is a mature notation for model-based specification. Itcombines formal and informal descriptions and incorporatesgraphical highlighting.• The basic building blocks of Z-based specifications areschemas.• Schemas identify state variables and define constraints and
    • operations in terms of those variables.The Structure of A Z Schemacontents Š capacityContainercontents:capacity:Schema name Schema signature Schema predicateNatural numbers (0, 1, 2, …)Defines schema state“invariants”, pre- & postconditionsAn Insulin PumpNeedleassemblySensorDisplay1 Display2AlarmPump ClockPower supplyInsulin reservoirControllerinsulindeliveryglucose leveltext messages dose deliveredModelling The Insulin Pump• The schema models the insulin pump as a number of statevariablesreading? -from sensor dose, cumulative doser0, r1, r2 -last 3 readingscapacity -pump reservoiralarm! -signals exceptional conditionspump! -output for pump devicedisplay1!, display2! -text messages & dose• Names followed by a? are inputs, names followed by a! areoutputs.
    • Schema Invariant• Each Z schema has an invariant part, which definesconditions that are always true (schema predicates)• For the insulin pump schema, it is always true that:The dose must be less than or equal to the capacity of theinsulin reservoir.<© Copy Right: Rai University11.676.2 51SOFTWARE ENGINEERINGNo single dose may be more than 5 units of insulin and thetotal dose delivered in a time period must not exceed 50 unitsof insulin. This is a safety constraint.display1! shows the status of the insulin reservoir.Insulin Pump SchemaInsulin_pumpreading? :dos e, cumulative_dose:r0, r1, r2: // used to record the last 3 readings takencapacity:alarm!: {off, on}pump!:dis play1!, display2!: STRINGdos e Š capacity ∧ dose Š 5 ∧cumulative_dose Š 50capacity•40 ⇒ dis play1! = " "capacity Š 39 ∧ capacity •10 ⇒ dis play1!= "Insulin low"capacity Š 9⇒ alarm!= on ∧ dis play1! = "Ins ulin very low"r2 =reading?dose ? ?capacity ^ dose ? 5 ^ cumulative_dose ? 50capacity ? 40 => display1! = “ “capacity ? 39 ^ capacity ? 10 => display1! = “Insulin low”capacity ? 9 => alarm! = on ^ display1! = “Insulin very low”r2 = reading?every 10 minutes…The Dosage Computation
    • • The insulin pump computes the amount of insulin requiredby comparing the current reading with two previousreadings.• If these suggest that blood glucose is rising then insulin isdelivered.• Information about the total dose delivered is maintained toallow the safety check invariant to be applied.• Note that this invariant always applies – there is no need torepeat it in the dosage computation.DOSAGE SchemaDOSAGE∆Insulin_Pump(dos e = 0 ∧ ((( r1 •r0) ∧ ( r2 = r1)) ∨(( r1 > r0) ∧ (r2 Š r1)) ∨(( r1 < r0) ∧ ((r1-r2) > (r0-r1))))∨dose = 4 ∧((( r1 Š r0) ∧ (r2 =r1)) ∨(( r1 < r0) ∧ ((r1-r2) Š (r0-r1))))∨dos e =(r2 -r1) * 4 ∧((( r1 Š ∧ (r2 > r1)) ∨(( r1 > r0) ∧ ((r2 - r1) •(r1 - r0)))))capacity = cap acity - dosecumulative_dos e = cumulative_dose + doser0 = r1 ∧ r1 = r2operations change state
    • imports state & predicates(( r1 ? r0) ^ ( r2 = r1)) V(( r1 > r0) ^ ( r2 < r1)) V(( r1 < r0) ^ ((r1-r2) > (r0-r1)))(( r1 ? r0) ^ (r2 = r1)) V(( r1 < r0) ^ ((r1 – r2) ? (r0 – r1)))(( r1 ? r0) ^ (r2 > r1)) V(( r1 > r0) ^ ((r2 – r1) ? (r1 – r0)))x?- value of x after operationOutput Schemas• The output schemas model the system displays and thealarm that indicates some potentially dangerous condition.• The output displays show the dose computed and a warningmessage.• The alarm is activated if blood sugar is very low – thisindicates that the user should eat something to increase hisblood sugar level.DIS PLAY∆In su lin_Pumpdis play2! = Nat_to_s tring (dose) ∧(reading? < 3 ⇒ display1! = "S ugar low" ∨rea ding? > 3 0 ⇒ disp la y1! = "S ugar high" ∨rea ding? •3 a nd re ading? Š 3 0 ⇒ display1! = "OK")ALARM∆In sulin_P ump( re ading? < 3 ∨ re ading? > 30 ) ⇒ alarm! = on ∨ ( re ading? • 3 ∧ reading ? Š 30 ) ⇒ alarm! = o ffconversion Note conflict with“insulin low” msg.^ AND? 3 ? 30??Schema Consistency• It is important that schemas be consistent. Inconsistency
    • suggests a problem with system requirements.• The INSULIN_PUMP schema and the DISPLAY areinconsistent:display1! shows a warning message about the insulin reservoir(INSULIN_PUMP)display1! Shows the state of the blood sugar (DISPLAY)• This must be resolved before implementation of the system.Secification Via Pre-and Post-conditions• Predicates that (when considered together) reflect a program’sintended functional behavior are defined over its statevariables.• Pre-condition: expresses constraints on program variablesbefore program execution. An implementer may assumethese will hold BEFORE program execution.• Post-condition: expresses conditions / relationships amongprogram variables after execution. These capture anyobligatory conditions AFTER program execution.• Language: (first order) predicate calculusPredicates (X>4)Connectives (&, V, →, ó, NOT)Universal and existential quantifiers (for every, there exists…)Rules of inference (if A & (A →B) then B)Example 1Sort a non-empty array LIST [1..N] into increasing order.Pre-cond: N >1Post-cond: For_Every i, 1 < i < N-1, LIST [i] < LIST [i+1] &PERM (LIST, LIST’)52 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGExample 2Search a non-empty, ordered array LIST [1..N] for the valuestored in KEY. If present, set found to true and J to an indexof LIST which corresponds to KEY. Otherwise, set FOUND tofalse.
    • Pre-cond: N > 1 & [(“LIST is in increasing order”) V (“LIST isin decreasing order”)](Exercise: express the “ordered” predicate above FORMALLY.)Post-cond: [(FOUND & There Exists i, 1 < i < N | J=i &LIST [J]=Key) V (NOT FOUND & For_Every i, 1 < i < N,LIST [i] ≠ KEY)] & UNCH (LIST, KEY)Key Points• Formal system specification complements informalspecification techniques.• Formal specifications are precise and unambiguous. Theyremove areas of doubt in a specification.• Formal specification forces an analysis of the systemrequirements at an early stage. Correcting errors at this stageis cheaper than modifying a delivered system.• Formal specification techniques are most applicable in thedevelopment of critical systems.• Algebraic techniques are particularly suited to specifyinginterfaces of objects and abstract data types.• In model-based specification, operations are defined in termsof changes to system state.ActivitySuggest why the architectural design of a system should precedethe development of a formal specification.ActivityYou have been given the task of selling formal specificationtechniques to a software development organization. Outlinehow you would go about explaining the advantages of formalspecifications to skeptical, practicing software engineers.ActivityExplain why it is particularly important to define sub-systeminterfaces in a precise way and why algebraic specification isparticularly appropriate for sub-system interface specification.© Copy Right: Rai University11.676.2 53SOFTWARE ENGINEERING
    • ActivityIn the example of a controlled airspace sector, the safetycondition is that aircraft may not be within 300 m of height inthe same sector. Modify the specification shown in figure 9.8 toallow aircraft to occupy the same height in the sector so long asthey are separated by at least 8km of horizontal difference. Youmay ignore aircraft in adjacent sectors. Hint. You have to modifythe constructor operations so that they include the aircraftposition as well as its height. You also have to define anoperation that, given two positions, returns the separationbetween them.ActivityBank teller machines rely on using information on the user’scard giving the bank identifier, the account number and theuser’s personal identifier. They also derive account informationfrom a central database and update that database on completionof a transaction. Using your knowledge of ATM operationwrite Z schemas defining the state of the system, card validation(where the user’s identifier is checked) and cash withdrawal.ActivityYou are a systems engineer and you are asked to suggest thebest way to develop the safety software for a heart pacemaker.You suggest formally specifying the system but your suggestionis rejected by your manager. You think his reasons are weakand based on prejudice. Is it ethical to develop the system usingmethods that you think are inadequate?54 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGEstablishing The Overall Structure of a SoftwareSystemObjectives• To introduce architectural design and to discuss itsimportance• To explain why multiple models are required to document in
    • architecture• To describe types of architectural models that may be used• To discuss use of domain-specific architectural referencemodelsTopics Covered• Architectural design• System structuring• Control models• Modular decomposition• Domain-specific architecturesWhat is Architectural Design?• The process of identifying the sub-systems making up asystem and a framework for sub-system control andcommunication.• A boot-strapping process undertaken in parallel with theabstract specification of sub-systems.• The output of this process is the software architecture.The Software Design ProcessArchitectuarldesignAbstractspecificationInterfacedesignComponentdesignDatastructuerdesignAlgorithmdesignSystemarchitectuerSoftwarespecification
    • Interfacespecifica tionComponentspecificationDatastructuerspecificationAlgorithmspecifica tionRequirementsspecificationDesign acvtiitiesDesign opdr uctsAdvantages of explicit architecture design and documentation (Bass)• Stakeholder communication : the architecture may be used asa focus of discussion by system stakeholders.• System analysis : the feasibility of meeting critical nonfunctionalrequirements (e.g., performance, reliability,maintainability) can be studied early on.• Large-scale reuse : the architecture may be reusable across arange of systems with similar requirements.Architectural Design Process• System structuring : the system is decomposed into majorsub-systems and communication (e.g., data sharing)mechanisms are identified.• Control modelling : a model of the control relationshipsbetween the sub-systems is established.• Modular decomposition : the identified sub-systems aredecomposed into lower-level modules (components, objects,etc.)Terminology Issues• Modular decomposition is sometimes called high-level(system) design.• A sub-system is usually a system in its own right, and issometimes called a Product.
    • • A module is a lower-level element that would not normallybe considered a separate system; modules are sometimescalled Components or Objects.• Traditional (and Somerville’s) terminologySystem (System)Product (Sub-System)Component (Module)Module (Unit) (Algorithm)Architectural Models• Different types of models may be used to represent anarchitectural design.• Each presents a different perspective on the architecture.Architectural Model Types• Static structural models show the major system components.• Dynamic process models show the process structure of thesystem at run-time.• Interface models define the sub-system services offeredthrough public interfaces.• Relationship models show relationships such as a dataflowamong sub-systems.Architectural Styles• The architecture of a system may conform to a single genericmodel or style, although most do not.• An awareness of these styles and how they can affect systemattributes can simplify the problem of choosing anappropriate architecture.System Attributes And Architectural Styles /Structures• Performance : localize operations by using fewer, large-graincomponents to minimize sub-system communication.• Security : use a layered architecture with critical assets in innerlayers.• Safety : isolate safety-critical components in one or just a fewsub-systems.UNIT II
    • DESIGN, VERIFICATION AND VALIDATIONCHAPTER 9LESSON15 AND 16:ARCHITECTURAL DESIGN© Copy Right: Rai University11.676.2 55SOFTWARE ENGINEERINGAvailability : include redundant components in the architecture.• Maintainability : use fine-grain, self-contained components.System Structuring• Concerned with decomposing the system into interactingsub-systems.• The architectural design is normally expressed as a blockdiagram presenting an overview of the system structure.• More specific models showing how sub-systems share dataare distributed, and interface with each other may also bedeveloped. (Examples follow.)Packing Robot Control SystemV isions ys temOb j ectidentifi cat io ns ystemArmcon tro ll erGri pp ercon tro ll erPackag in gs el ections ys temPacki ngs ystemCo nveyo rcon tro ll erThe Repository Model
    • • Sub-systems must exchange info. This may be done in twoways:Shared data is held in a central database or repository and maybe accessed by all sub-systems.Each sub-system maintains its own database and passes dataexplicitly to other sub-systems.• When large amounts of data are used, the repository modelof sharing is commonly used.CASE Toolset ArchitectureProjectrepositoryDesigntranslatorProgrameditorDesigneditorCodegeneratorDesignanalyserReportgeneratorRepository Model Advantages• Simple and efficient way to share large amounts of datalocally.• Sub-systems, which use data, need not be concerned withhow that data is produced, and vice-versa.• Management activities such as backup, access control, andrecovery are centralized.• Sharing model is published as the repository schema.Integration of compatible tools is relatively easy.Repository Model Disadvantages• Sub-systems must agree on a single repository data model.This is inevitably a compromise.
    • • Data model evolution is difficult and expensive.• No provision for sub-system-specific data managementrequirements related to backup, access control, and recovery.• May be difficult to distribute efficiently over a number ofmachines due to problems with data redundancy andinconsistency.The Client-server Model• Distributed system model, which shows how data andprocessing are distributed across a range of processors.• Major components are:A set of stand-alone servers, which provide specific servicessuch as printing, file management, etc.A set of clients, which call on these servicesA network, which allows clients to access these servicesFilm and Picture LibraryCatalogueserverCatalogueVideoserverFilmclipfilesPictureserverDigitizedphotographsHypertextserverHypertextwebClient 1 Client 2 Client 3 Client 4Wide-bandwidthnetworkClient-server Model Advantages• Supports distributed computing.• Underlying network makes distribution of data
    • straightforward.• No shared data model so servers may organize data tooptimise their performance.• Distinction between servers and clients may allow use ofcheaper hardware.• Relatively easy to expand or upgrade system.56 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGClient-server Model Disadvantages• Relatively complex architecture – problem determination canbe difficult.• No shared data model so data integration may beproblematic.• Redundant data management in each server.• No central register of names and services, so it may be hardto find out what servers and services are available.The Abstract Machine Model• Organizes a system into a series of layers.• Each layer defines an abstract machine and provides a set ofservices used to implement the next level of abstractmachine.• When a layer interface changes, only the adjacent layer isaffected.• However, it is often difficult to structure systems in this way.(Why?)Abstract Machine Based Version ManagementSystemOperatingsys temDat abase systemObject managementVersi on managementControl Models
    • • Concerned with the control flow between sub-systems.Distinct from the system structure model.• Two general approaches:Centralized control : one sub-system has overall responsibilityfor control and starts and stops other sub-systems.Event-based control : each sub-system can respond to externallygenerated events from other sub-systems, or from the system’senvironment.Centralized Control Models1. Call-return model : top-down subroutine model wherecontrol starts at the top of a subroutine hierarchy and movesdownwards. Applicable to sequential systems only.2. Manager model : applicable to concurrent systems. Onesystem component controls the stopping, starting andcoordination of other system processes. Also applicable tosequential systems where it is usually implemented as a casestatement within a management routine.Call-return ModelRoutine1.1 Routine1.2 Routine3.1 Routine3.2Routine1 Routine2 Routine3MainprogramManager Model - Real-time System ControlS y st emco n tr o ll erUs e ri nt er fac eFaul th an dl e rC om pu ta t io np ro ces sesAc t uat o rp ro ces sesS en so rp ro ces se s
    • Principal Event-based Control Models1. Broadcast model : an event is broadcast to all sub-systems;any sub-system, which can handle the event, may do so.2. Interrupt-driven model : used in real-time systems whereinterrupts are detected by an interrupt handler and passed tosome other component for processing.(Other event-based models include compound documents andproduction systems.)Broadcast Model• Effective in integrating sub-systems executing on differentcomputers in a network.• Control policy is NOT embedded in the message handler;sub-systems register an interest in specific events and theevent handler ensures that these events are sent to them.• Registration of interests’ supports selective broadcasting.• Evolution is relatively easy since a new sub-system can beintegrated by registering its events with the event handler.• However, sub-systems don’t know if or when an event willbe handled by some other sub-system.Interrupt-driven Systems• Used in real-time systems where fast response to an event isessential.• A handler is defined for each type of interrupt.• Each type is associated with a memory location and ahardware switch causes transfer to its handler – fast!© Copy Right: Rai University11.676.2 57SOFTWARE ENGINEERING• Allows fast response but is complex to program and difficultto verify. (Why?)Interrupt-driven ControlHandler1Handler2
    • Handler3Handler4Process1Process2Process3Process4InterruptsInterruptvectorModular Decomposition (A.K.A. High-level Design)• Sub-systems are decomposed into lower-level elements.• Two models are considered:An object model where the system is decom-posed intointeracting objects. (object-oriented design)A data-flow model where the system is decomposed intofunctional modules, which transform inputs into outputs.(function-oriented design)Object Models• Structure the system into a set of loosely coupled objectswith well-defined interfaces.• Object-oriented decomposition is concerned with identifyingobject classes, their attributes and operations.• When implemented, objects are created from these classesand some control model is used to coordinate objectoperations.Invoice Processing Systemissue ()sendReminder ()acceptPayment ()
    • sendReceipt ()invoice#dateamountcustomerInvoiceinvoice#dateamountcustomer#Receiptinvoice#dateamountcustomer#Paymentcustomer#nameaddresscredit periodCustomerData-flow Models• Functional transformations process inputs to produceoutputs.• Sometimes referred to as a pipe and filter model (afterterminology used in UNIX).• Variants of this approach have a long history in softwaredesign.• When transformations are sequential, this is a batchsequential model• Which is extensively used in data processing systems.• Not really suitable for interactive systems (input data streamsversus events)Invoice Processing SystemReadissued
    • invoicesIdentifypaymentsIssuereceiptsFindpaymentsdueReceiptsIssuepaymentreminderRemindersInvoices PaymentsDomain-specific Architectures• Architectural models which are specific to some applicationdomain• Two types of domain-specific models:1.Generic models encapsulate the traditional, time-testedcharacteristics of real systems.2.Reference models are more abstract and describe a larger classof systems. They provide a means of comparing differentsystems in a domain.• Generic models are usually bottom-up models; Referencemodels are top-down models.Generic Models• The compiler model is a well-known example.• Based on the thousands written, it is now generally agreedthat the standard components of a compiler are:Lexical analyserSymbol tableSyntax analyserSyntax treeSemantic analyserCode generator
    • Compiler ModelLex icalanal ysi sSyn tact icanalysi sSemant icanalysisCodeg enerat ionSymboltabl eSequential function model (batch processing oriented)58 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGLanguage Processing SystemSyntaxanalyserLexicalanalyserSemanticanalyserAbstractsyntax treeGrammardefini tionSymboltableOutputdefini tionPrett yprinterEdit orOptimizerCode
    • generatorRepositoryRepository-based modelReference Architectures• Reference models are derived from a study of the applicationdomain rather than from existing systems.• May be used as a basis for system implementation, or tocompare different systems. It acts as a standard againstwhich systems can be evaluated.• The OSI (Open System Interconnection) model is a layeredmodel for communication systems (in particular, dataprocessing / point-of-sale applications).OSI Reference ModelApplicationPresentationSessionTransportNetworkData linkPhysical7654321Communications mediumNetworkData linkPhysicalApplicationPresentationSessionTransport
    • NetworkData linkPhysicalKey Points• The software architect is responsible for deriving a structuralsystem model, a control model, and a sub-systemdecomposition model.• Large systems rarely conform to a single architectural model.• System decomposition models include the repository model,client-server model, and abstract machine model.• Control models include centralized control and event-drivenmodels.• Modular decomposition models include data-flow andobject models.• Domain specific architectural models are abstractions over anapplication domain.• They may be constructed by abstracting from existingsystems or they may be idealized reference models.ActivityExplain why it may be necessary to design the system architecturebefore the specifications are written.ActivityConstruct a table showing the advantages and disadvantages ofthe different structural models discussed in this chapter.© Copy Right: Rai University11.676.2 59SOFTWARE ENGINEERINGActivityGiving reasons for your answer, suggest an appropriatestructural model for the following systems:• An automated ticket issuing system used by passengers at arailway station.• A computer controlled video conferencing system, whichallows video, audio, and computer data to be visible toseveral participants at the same time.
    • • A robot floor cleaner, which is intended to clean relatively,clear spaces such as corridors. The cleaner must be able tosense walls and other obstructions.ActivityDesign an architecture for the above systems based on yourchoice of model. Make reasonable assumptions about thesystem requirements.ActivityExplain why a call-return model of control is not usuallysuitable for real time systems which control some process.ActivityGiving reasons for your answer, suggest an appropriate controlmodel for the following systems:• A batch processing system, which takes information abouthours, worked and pays rates and prints salary slips and bankcredit transfer information.• A set of software tools, which are, produced buy differentvendors but which mist work together.• A television controller, which responds to, signals form aremote control unit.60 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGActivityDiscuss their advantages and disadvantages as far as disreputabilityis concerned of the data flow model and the object model.Assume that both single machine and distributed versions ofan application are required.ActivityShould there be a separate profession of ‘software architect’whose role is to work independently with a customer to designa software architecture? This would then be implemented bysome software company. What might be the difficulties ofestablishing such a profession?Notes:
    • © Copy Right: Rai University11.676.2 61SOFTWARE ENGINEERINGArchitectural Design for Software That Executes onMore Than One ProcessorObjectives• To explain the advantages and disadvantages of distributedsystems architectures.• To describe different approaches to the development ofclient-server systems.• To explain the differences between client-server anddistributed object architectures.• To describe object request brokers and the principlesunderlying the CORBA standards.Topics Covered• Multiprocessing systems• Distributed systems architecturesClient-server architecturesDistributed object architectures• CORBA (Common Object Request Broker Architecture)Multiprocessor Architectures• System composed of multiple processes, which may or maynot execute on different processors.• Distribution of process to processor may be pre-ordered ormay be under the control of a dispatcher.A Multiprocessor Traffic Control SystemTraf fic lightsLi ghtcontrolprocessTraff ic light controlprocessorTraffic flowprocessorTraf fic flowsensors Operatorconsol es
    • and camerasSensorprocessorSe nsorcontrolprocessDisplayprocessTypes of Multiprocessing Systems• Personal systems that are not distributed and that aredesigned to run on a personal computer or workstation.(word processors)• Embedded systems that run on a single processor or on anintegrated group of processors. (control systems, real-timesystems)• Distributed systems where the system software runs on aloosely integrated group of processors linked by a network.(ATM systems)Distributed Systems• Virtually all-large, computer-based systems are nowdistributed systems.• Processing is distributed over several computers rather thanconfined to a single machine.• Distributed software engineering is now very important.Distributed System Characteristics / Advantages• Resource sharing (hardware and software)• Openness (resource extendibility)• Concurrency (parallel processing)• Scalability (up to capacity of network)• Fault tolerance (potential)• Transparency (ability to conceal distributed nature)Distributed System Disadvantages• Complexity (no. of factors affecting emergent properties)• Security (multiple access points, network eavesdropping)
    • • Manageability (heterogeneity)• Unpredictable responsivenessIssues in Distributed System DesignDesign issue DescriptionResourceidentificationThe resources in a distributed systemare spread across differentcomputers and a namingscheme has to be devised so that users candiscover and refer to the resources that they need. An example ofsuch a naming scheme is the URL (Uniform Resource Locator)thatis usedto identify WWWpages. If a meaningful and universallyunderstood identificationscheme is not used thenmany of theseresources will be inaccessible to system users.Communications The universal availability of the Internet and theeffi cientimplementation of InternetTCP/IP communication protocolsmeansthat, for most distributed systems, these are the most effective wayfor the computers to communicate. However, where there arespecific requirements for performance, reliability etc. alternativeapproaches tocommunications may be used.Quality of service The quality of service offered by asystemreflects its performance,availability andreliability. It is affected by a number of factors suchas the allocation of processes to processes in the system, thedistribution of resources across the system, the network andthesystem hardware and the adaptability of the system.SoftwarearchitecturesThe software architecture describes how the applicationfunctionality is distributed over a number of logical componentsandhow thesecomponents are distributed across processors. Choosingthe right architecture for an application is essential to achieve thedesired quality of service.
    • Distributed Systems Architectures• Client-server architectures : Ristributed services, which arecalled on by clients. Servers that provide services are treateddifferently from clients that use services.• Distributed object architectures : Removes distinctionbetween clients and servers. Any object in the system mayprovide and use services from other objects.UNIT IIDESIGN, VERIFICATION AND VALIDATIONCHAPTER 10LESSON17 AND 18:DISTRIBUTED SYSTEMSARCHITECTURES62 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGMiddleware• Software that manages and enables communication betweenthe diverse components of a distributed system. Middlewareis usually off-the-shelf rather than specially written.• Distributed system frameworks, e.g. CORBA and DCOM, isan important class of middle-ware described later.Client-server Architectures• The application is modelled as a set of services that areprovided by servers and a set of clients that use the services.• Clients must know of servers but servers need not know ofclients. (e.g., “installing” a network printer)• Clients and servers are logical processes as opposed tophysical machines.• The mapping of processors to processes is not necessarily1:1.A Client-server Systems1s2 s 3c 1 s4
    • c2 c3 c4c5c6c7 c 8c9c 10c11c12Client pr ocessSe rver processComputers in a C/S NetworkNetworkSC2 SC1CC1 CC2 CC3CC4 CC5 CC6Se rvercomputerCl ientcomputers1, s2 s3, s4c5, c6, c7c1 c2 c3, c4c8, c9 c10, c11, c12Application Layers Model• Presentation layer : concerned with presenting the results of acomputation to system users and with collecting user inputs.• Application processing layer : concerned with implementingthe logic (functionality) of the application.• Data management layer : concerned with all system databaseoperations.Application LayersP r e s e n ta t io n la y e rA p p l i ca t i o n pr o c e s s in gl ay e rD a t a m a n a ge m e n t
    • l ay e rDistributing Layers to Processors• Two-tier C/S architecture : the three layers are distributedbetween a server processor and a set of clients.• Three-tier C/S architecture : the layers are distributed amongtwo server processes / processors and a set of clients.• Multi-tier C/S architectures : the layers are distributed amongmultiple server processes / processors (each associated with aseparate database, for example) and a set of clients.Two-tier Architectures: Thin and Fat Clients• Thin-client model : the application logic and datamanagement are implemented on the server; the client onlyhandles the user interface.• Fat-client model : the server is only responsible for datamanagement; the client handles the application logic and theuser interface.Thin and Fat ClientsThin-clientmodelFat-clientmodel ClientClientServerData managementApplicationprocessingPresentationServerDatamanagementPresentationApplication processingThin-client Model• Often used when centralized legacy systems evolve to a C/Sarchitecture; the user interface is migrated to workstations or
    • terminals and the legacy system acts as a server.• Places a heavy processing load on both the server and thenetwork; this is wasteful when clients are powerfulworkstations.Fat-client Model• More processing is delegated to the client as the applicationlogic is executed locally.• But system management is more complex, especially whenapplication function changes and new logic must be installedon each client.A Client-server ATM SystemAccount serverCu stomeraccou ntd atabaseTeleprocessingmo nito rATMATMATMATM© Copy Right: Rai University11.676.2 63SOFTWARE ENGINEERINGThree-tier Architectures• Each application architecture layer may execute on a separateprocessor.• Allows for better performance and scalability than a thinclientapproach and is simpler to manage than a fat-clientapproach.A 3-tier C/S ArchitectureClientServerData
    • managementPresentationServerApplicationprocessin gAn Internet Banking SystemDatab ase serverCustomeraccountdatabaseWeb serverClientClientClientClientAccount serviceprovisionSQLSQLqueryHTTP interactionUse of C/S ArchitecturesArc hitecture ApplicationsTwo-tier C/Sarchitecture withthin clientsLegacy system applications where separating applicationproces sing and data management is impracticalComputationally-intensive applications such as compilers withlittle or no datamanagementData-intensive applications (browsing and querying) with littleor no application processing.Two-tier C/Sarchitecture withfat clientsApplications where application processing is provided by
    • COTS(e.g. Microsoft Excel) on the clientApplications where computationally-intensive processing ofdata (e.g. data visualisation) is required.Applications with relatively stable end-user functionality usedin an environment with well-established systemmanagementThree-tier ormulti-tier C/SarchitectureLarge scale applications with hundreds or thousands of clientsApplications where both the data and the application arevolatile.Applications where data fr ommultiple sources are integratedDistributed Object Architectures• Eliminates the distinction between clients and servers.• System components are objects that provide services to, andreceive services from, other objects.• Object communication is through middle-ware called anobject request broker (effectively a software bus)Distributed Object ArchitecturesSo f tw ar e bu so1 o 2 o 3 o 4o5 o 6S (o 1) S ( o2) S ( o3) S ( o 4)S (o 5) S ( o 6)Advantages of Distributed Object Architectures• Allows system designer to delay decisions on where and howservices should be provided. (Service-providing objects mayexecute on any network node.)• Very open architecture : allows new resources to be added asrequired.• Flexible and scaleable.• System is dynamically reconfigurable : objects can migrateacross the network as required. (Thus improvingperformance.)Uses of Distributed Object Architectures
    • • As a logical model for structuring and organizing a systemsolely in terms of services provided by a number ofdistributed objects. (E.g., a data mining system.)• As a flexible means of implementing C/S systems. Bothclients and servers are realised as distributed objectscommunicating through a software bus.A Data Mining SystemDatabase 1Database 2Database 3Integrator 1Integrator 2VisualiserDisplayReport gen.Disadvantages of Distributed Object Architectures• Complex to design due to model generality and flexibility inservice provision.• C/S systems seem to be a more natural model for mostsystems. (They reflect many human service transactions.)CORBA (Common Object Request BrokerArchitecture)• International standards for an Object Request Broker (ORB):middleware to manage communications between distributedobjects.• Several implementation of CORBA are available (Unix andMS OS’s).• Defined by the Object Management Group (>500companies, including Sun, HP, IBM).• DCOM (Distributed Component Object Model) is analternative standard developed and implemented byMicrosoft.Components of The OMG Vision of a DistributedApplication• Application objects designed and implemented for this
    • application.64 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERING• Domain-specific objects defined by the OMG. (e.g., finance/insurance, healthcare)• Fundamental CORBA distributed computing services suchas directories and security management.• Horizontal facilities (such as user interface facilities) used inmany different applicationsCOBRA Application StructureCORBAservicesObject requestbrokerDomainfacilitiesHorizontalCORBAfacilitiesApplicationobjectsMajor Elements of the CORBA Standards• An application object model where objects encapsulate stateand have a well-defined, language-neutral interface defined inan IDL (interface definition language).• An object request broker (ORB) that locates objectsproviding services, sends service requests, and returns resultsto requesters.• A set of general object services of use to many distributedapplications.• A set of common components built on top of theseservices. (Task forces are currently defining these.)CORBA Objects• Objects that provide services have IDL skeletons that linktheir interface to an implementation.• Calling objects have IDL stubs for every object being called.• Objects do not need to know the location or
    • implementation details of other objects.Object Request Broker (ORB)• The ORB handles object communications. It knows of allobjects in the system and their interfaces.• The calling object binds an IDL stub that defines theinterface of the called object.• Calling this stub results in calls to the ORB, which then callsthe required object through a published IDL skeleton thatlinks the interface to the service implementation.ORB-based Object Communicationso1 o2S (o1) S (o2)IDLstubIDLskeletonObject RequestBrokerInter-ORB Communications• ORBs handle communications between objects executing onthe same machine.• Inter-ORB communications are used for distributed objectcalls.• CORBA supports ORB-to-ORB communication byproviding all ORBs access to all IDL interface definitions andby implementing the OMG’s standard Generic Inter-ORBProtocol (GIOP).Inter-ORB Communicationso1 o2S (o1) S (o2)IDL IDLObject Request Brokero3 o4S (o3) S (o4)IDL IDLObject Reques tBroker
    • NetworkExamples of General CORBA Services• Naming and trading services : these allow objects to discoverand refer to other objects on the network.• Notification services : these allow objects to notify otherobjects that an event has occurred.• Transaction services : these support atomic transactions androllback on failure.Key Points• Almost all new large systems are distributed systems.• Distributed systems support resource sharing, openness,concurrency, scalability, fault tolerance, and transparency.• Client-server architectures involve services being delivered byservers to programs operating on clients.• User interface software always runs on the client and datamanagement on the server.• In a distributed object architecture, there is no distinctionbetween clients and servers.© Copy Right: Rai University11.676.2 65SOFTWARE ENGINEERING• Distributed object systems require middle-ware to handleobject communications.• The CORBA standards are a set of middle-ware standardsthat support distributed object architectures.ActivityExplain why distributed systems are inherently more scalablethan centralized systems. What are the likely limits on thescalability of the system?ActivityWhat is the fundamental difference between a fat-client and athin-client approach to client-server systems development?Explain why the use of Java as an implementation languageblurs the distinction between these approaches.Activity
    • It is proposed to develop a system for stock information wheredealers can access information about companies and can evaluatevarious investment scenarios using a simulation system.Different dealers use this simulation in different ways accordingto their experience and the type of stocks that they are dealingwith. Suggest a client-server architecture for this system thatshows where functionality is located justify the client serversystem model that you have chosen.ActivityDistributed systems based on a client-server model have beendeveloped since the 1980s but it is only recently that systemarchitectures based on disrupted objects have been implemented.Suggest three reasons why this should be the case.66 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGActivityExplain why the use of distributed objects with an objectrequest broker simplifies the implementation of scalable clientserversystems. Illustrate your answer with an example.ActivityHow is the CORBA IDL used to support communicationsbetween objects that have been implemented in differentprogramming languages? Explain why this approach may causeperformance problems if there are radical differences betweenthe languages used for object implementation.ActivityWhat are the basic facilities that must be provided by an objectrequest broker?© Copy Right: Rai University11.676.2 67SOFTWARE ENGINEERINGObjectives• To explain how a software design may be represented as a setof interacting objects that encapsulate their own state and
    • operations.• To describe the activities in the object-oriented design process• To introduce various models used to describe an objectorienteddesign• To show how the UML may be used to represent thesemodelsTopics Covered• Objects and object classes• An object-oriented design process• Design evolutionCharacteristics of OOD• Allows designers to think in terms of interacting objects thatmaintain their own state and provide operations on thatstate instead of a set of functions operating on shared data.• Objects hide information about the representation of stateand hence limit access to it.• Objects may be distributed and may work sequentially or inparallel.A design strategy based on “information hiding”…• A useful definition of information hiding:Potentially changeable design decisions are isolated(i.e., “hidden”) to minimize the impact of change.- David ParnasInteracting Objectsstate o3o3:C3state o4o4: C4state o1o1: C1state o6o6: C1state o5o5:C5state o2
    • o2: C3ops1() ops3 () ops4 ()ops3 () ops1 () ops5 ()Advantages of OOD• Easier maintenance. Objects may beunderstood as stand-alone entities.• Objects are appropriate reusable components.• For some systems, there is an obvious mapping from realworld entities to system objects.Object-oriented Development• OO Analysis: concerned with developing an object model ofthe application domain.• OO Design: concerned with developing an object-orientedsystem model to implement requirements• OO Programming: concerned with realising an OOD usingan OO programming language such as Java or C++.Objects and Object Classes• Objects are entities with state and a defined set of operationson that state.State is represented as a set of object attributes.Operations provide services to other objects when requested.• Object classes are templates for objects.An object class definition includes declarations of all attributesand operations associated with an object of that class.They may inherit attributes and services from other objectclasses.The Unified Modeling Language• Several different notations for OOD were proposed in the1980s and 1990s. (Booch, Rumbaugh, Jacobson, Coad &Yourdon, Wirfs, …)• UML is an integration of these notations.• It describes a number of different models that may beproduced during OO analysis and design (user view,structural view, behavioural view, implementation view, …)Employee Object Class (UML)
    • Employeename : st ringaddre s s: s tringdateOfBirth: Dateemplo yeeN o: integersocialSecurityNo: s tringdepar tment : Deptma na ger: Employeesalary : integers tatus: {current , left , re tired}taxC o de: integer...join ()leave ()ret ire ()chang eDetails ()UNIT IIDESIGN, VERIFICATION AND VALIDATIONCHAPTER 11LESSON 19 AND 20:OBJECT-ORIENTED DESIGN68 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGObject Communication• Conceptually, objects communicate by message passing.• Messages include:The name of the service requested,A copy of the information required to carry out the service, andthe name of a holder for the result of the service.• In practice, messages are often implemented by procedurecallsMessage Examples// Call a method associated with a buffer// object that returns the next value
    • // in the buffer v = circularBuffer. Get ( );// Call the method associated with a// thermostat object that sets the// temperature to be maintained thermostat.setTemp (20);Generalization and Inheritance• Objects are members of classes, which define attribute typesand operations.• Classes may be arranged in a hierarchy where one class (asuper-class) is a generalization of one or more other classes(sub-classes)• A sub-class inherits the attributes and operations from itssuper class and may add new methods or attributes of itsown.A UML Generalisation HierarchyEmployeeProgrammerprojectprogLanguageManagerProjectManagerbudgetsControlleddateAppointedprojectsDept.ManagerStrategicManagerdept responsibilitiesAdvantages of Inheritance• It is an abstraction mechanism, which may be used to classifyentities.• It is a reuse mechanism at both the design and theprogramming level.• The inheritance graph is a source of organisational
    • knowledge about domains and systems.Problems With Inheritance• Object classes are not self-contained (i.e., they cannot beunderstood without reference to their super-classes).• Designers have a tendency to reuse the inheritance graphcreated during analysis. (Inheritance graphs of analysis,design and implementation have different functions.)Inheritance and OOD• Inheritance is a useful implementation concept, which allowsreuse of attribute and operation definitions.• Some feel that identifying an inheritance hierarchy or networkis also a fundamental part of object-oriented design.(Obviously, this can only be implemented using an OOPL.)• Others feel this places unnecessary restrictions on theimplementation.• Inheritance introduces complexity and this is undesirable,especially in critical systems.UML Associations• Objects and object classes participate in various types ofrelationships with other objects and object classes.• In the UML, a generalized relationship is indicated by anassociation.• Associations may be annotated with information thatdescribes their nature.• Associations can be used to indicate that an attribute of anobject is an associated object or that a method relies on anassociated object.An Association ModelEmployee DepartmentManageris-member-ofis-managed-bymanagesConcurrent Objects• The nature of objects as self-contained entities make them
    • well suited for con-current implementation.• The message-passing model of objectcommunication can be implemented directly if objects arerunning on separate processors in a distributed system.Concurrent object implementation: servers andactive objects• Servers (Passive objects): implemented as parallel processeswith entry points corresponding to object operations. If no© Copy Right: Rai University11.676.2 69SOFTWARE ENGINEERINGcalls are made to it, the object suspends itself and waits forfurther requests for service.• Active objects: implemented as parallel processes and theinternal object state may be changed by the object itself andnot simply by external calls.Example: An Active Transponder Object• A transponder object broadcasts an aircraft’s position.• The object periodically updates the position by triangulationfrom satellites.An Object-oriented Design Process• Define the context and modes of use of the system.• Design the system architecture.• Identify the principal system objects.• Develop design models (static and dynamic).• Specify object interfaces.Weather System Description• A weather data collection system is required to generateweather maps on a regular basis using data collected fromremote, unattended weather stations and other data sourcessuch as weather observers, balloons and satellites. Weatherstations transmit their data to the area computer in responseto a request from that machine.• The area computer validates the collected data and integratesit with the data from different sources. The integrated data is
    • archived and, using data from this archive and a digitisedmap database a set of local weather maps is created. Mapsmay be printed for distribution on a special-purpose mapprinter or may be displayed in a number of differentformats.• A weather station is a package of software-controlledinstruments, which collects data, performs some dataprocessing and transmits this data for further processing.The instruments include air and ground thermometers, ananemometer, a wind vane, a barometer and a rain gauge.Data is collected every five minutes.• When a command is issued to transmit the weather data, theweather station processes and summarises the collected data.The summarised data is transmitted to the mappingcomputer when a request is received.1.Define system context and modes of use• Goal: develop an understanding of the relationshipsbetween the software being designed and its externalenvironment.• System context: a static model that describes other systemsin the environment.• The context of the weather station is illustrated below usingUML packages.Context of Weather Station«subsystem»Data collection«subsystem»Data processing«subsystem»Data archiving«subsystem»Data displayWeatherstationSatellite
    • CommsBalloonObserverDatacheckingDataintegrationMap store Data storeDatastorageMapUserinterfaceMapdisplayMapprinter• Modes of system use : a dynamic model that describes howthe system will interact with its environment.• Modes of weather station use are illustrated below using aUML use-case model.Use-cases for the Weather StationUse-case DescriptionSystem Weather stationUse -case ReportActors Weather data collection system, Weather stationData The weather station sends a summary of the weatherdata that has been collected from the instruments in thecollection period to the weather data collection system.The data sent are the maximum minimum and averageground and air temperatures, the maximum, minimumand average air pressures, the maximum, minimum andaverage wind speeds, the total rainfall and the winddirection as sampled at 5 minute intervals.Stimulus The weather data collection system establishes a
    • modem link with the weather station and requeststransmission of the data.Response The summarised data is sent to the weather datacollection systemComments Weather stations are usually asked to reportonce perhour but this frequency may differ from one station tothe other and may be modified in future.2. Design System Architecture• A layered architecture is appropriate for the weather station:Interface layer : for handling communicationsData collection layer : for managing instrumentsInstruments layer : for collecting data• Rule of Thumb: There should be no more than 7 entities inan architectural model.70 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGWeather Station Architecture«subsystem»Da ta collection«subsystem»Instruments«subsystem»InterfaceWeather stationManages allexternalcommunicationsCollects andsummarisesweather dataPackage ofinstruments for rawdata collections
    • UML “nested packages” UML annotations3. Identify Principal System Objects• Identifying objects (or object classes) is the most difficultpart OO design.• There is no “magic formula” – it relies on the skill,experience, and domain knowledge of system designers• An iterative process – you are unlikely to get it right the firsttime.Approaches to Object Identification• Use a grammatical approach based on a natural languagedescription of the system (Abbott’s heuristic).• Associate objects with tangible things in the applicationdomain (e.g. devices).• Use a behavioural approach: identify objects based on whatparticipates in what behaviour.• Use scenario-based analysis. The objects, attributes andmethods in each scenario are identified.• Use an information-hiding based approach. Identifypotentially change-able design decisions and isolate these inseparate objects.Weather Station Object Classes• Weather station : interface of the weather station to itsenvironment. It reflects interactions identified in the use-casemodel.• Weather data : encapsulates summarised data from theinstruments.• Ground thermometer, Anemometer, Barometer : applicationdomain “hardware” objects related to the instruments in thesystemWeather Station Object Classesident ifierreportWe ather ()c alibrate (inst ruments)test ()s tartup (in s truments )
    • s hutdown (ins truments )Weath erStationtes t ( )c alibrate ()G roundthe rm ometertempe ratureAnemometerwin d Speedwin d Direc tiontes t ()Ba rom eterpres s ureheigh ttest ( )c alibr ate ()WeatherDataairTemperaturesgroundTemperature swin dSpeedswin dDirec tionspres suresrainfallc ollect ()summaris e ()Other Objects And Object Refinement• Use domain knowledge to identify more objects, operations,and attributes.Weather stations should have a unique identifier.Weather stations are remotely situated so instrument failureshave to be reported automatically. Therefore, attributes andoperations for self checking are required.• Active or passive objects?Instrument objects are passive and collect data on request ratherthan autonomously. This introduces flexibility (how?) at the
    • expense of controller processing time.Are any active objects required?4. Develop Design Models• Design models show the relationships among objects andobject classes.• Static models describe the static structure of the system interms of object and object class relationships.• Dynamic models describe the dynamic interactions amongobjects.Examples of Design Models• Sub-system models show logical groupings of objects intocoherent sub-systems. (static)• Sequence models show the sequence of object interactionsassociated with system uses. (dynamic)• State machine models show how individual objects changetheir state in response to events. (dynamic)• Other models include use-case models, aggregation models,generalisation (inheritance) models, etc.Subsystem Models• In the UML, these are shown using packages, anencapsulation construct.• This is a logical model – the actual organization of objects inthe system as implemented may be different.Weather Station Subsystems«subsyst em»I nterfaceCommsControllerWeatherStation«subsyst em»Data collection«subsystem»I nst rumentsAirthermometerWeatherData
    • GroundthermometerAnemometerWindVaneRainGaugeInstrumentStatusBarometer-Annotations© Copy Right: Rai University11.676.2 71SOFTWARE ENGINEERINGSequence Models• Objects are arranged horizontally across the top.• Time is represented vertically; models are read top tobottom.• Interactions are represented by labelled arrows - differentstyles of arrows represent different types of interaction.• A thin rectangle in an object lifeline represents the time whenthe object is the controlling object in the system.Data collection sequenceWeather Station State Machine ModelSh utdown Waiting Test ingT ransmit tingCollectingSummaris ingCalibrat ingtran smi ss ion donecalibrate ()s tartu p () tes t ()shu tdown ()calibrat ion OKtest complet eweather summarycomp lete
    • clock collect io ndoneOperationrepo rtWeather ()5. Object Interface Specification• Designers should avoid revealing data representationinformation in their interface design. (operations access andupdate data)• Objects may have several logical interfaces, which areviewpoints on the methods provided. (supported directly inJava)• The UML uses class diagrams for interface specification butpseudocode may also be used.Design Evolution• Hiding information in objects means that changes made toan object do not affect other objects in an unpredictable way.• Assume pollution-monitoring facilities are to be added toweather stations.• Pollution readings are transmitted with weather data.Changes Required• Add an object class called “Air quality” as part of WeatherStation• Add an operation reportAirQuality to WeatherStation.Modify the control software to collect pollution readings• Add objects representing pollution monitoring instruments.Pollution MonitoringNO Da t as mo k eD atab en z e n eD atac olle ct ()su m m ar is e ( )Ai r q ua l it yid en t ifierr ep or tWea th e r ( )r ep or t A irQ u ality ()
    • c alib r ate ( in st r um e nt s)t est ( )s tar tu p (in s t ru m en ts )sh ut d own (in s tru me n ts)We at h erS t at io nP o ll u tio n m on it o r in g in s tr um e n tsN O me te r S m oke M e terB en z en eM e te rKey Points• OOD results in design components with their own privatestate and operations.• Objects should have constructor and inspection operations.They provide services to other objects.• Objects may be implemented sequentially or concurrently.• The Unified Modeling Language provides different notationsfor defining different object models.• A range of different models may be produced during anobject-oriented design process. These include static anddynamic system models• Object interfaces should be defined precisely.• Object-oriented design simplifies system evolution.ActivityExplain why adopting an approach to design that is based onloosely coupled objects that hide information about theirrepresentation should lead to a design which may be readilymodified.72 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGActivityUsing examples, explain the difference between an object and anobject class.ActivityUnder what circumstances might it be appropriate to develop adesign where objects execute concurrently?
    • ActivityUsing the UML graphical notation for object classes, design thefollowing object classes identifying attributes and operations.Use your own experience to decide on the attributes andoperations that should be associated with these objects:• A telephone:• A printer for a personal computer;• A personal stereo system;• A bank account;• A library catalogue.ActivityDevelop the design of the weather station to show theinteraction between the data collection sub- system and theinstruments that collect weather data. Use sequence charts toshow this interaction.© Copy Right: Rai University11.676.2 73SOFTWARE ENGINEERINGActivityIdentify possible objects in the following systems and developan object oriented design for them. You may make anyreasonable assumptions about the systems when deriving thedesign.• A group diary and time management system is intended tosupport the timetabling of meetings and appointmentsacross a group of co-workers. When an appointment is to bemade which involves a number of people, the system finds acommon slot in each of their diaries and arranges theappointment for that time. If no common slots areavailable, it interacts with the users to rearrange their personaldiaries to make room fort the appointment.• A petrol (gas) station is to be set up for fully automatedoperation. Derivers swipe their credit card through a readerconnected to the pump; the card is verified bycommunication with a credit company computer and a fuel
    • limit established. The driver may then take the fuel requiredwhen fuel delivery is complete and the pump hose isreturned to its holster, the driver’s credit card account isdebited with the cost to the furl taken. The credit card isreturned after debiting. If the card is invalid, it is returnedbuy the pump before fuel is dispensed.ActivityDraw a sequence diagram showing the interactions of objects ina group diary system when a group of people arrange a meeting.74 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGDesigning Embedded Software Systems WhoseBehaviour is Subject to Timing ConstraintsObjectives• To explain the concept of a real-time system and why thesesystems are usually implemented as concurrent processes• To describe a design process for real-time systems• To explain the role of a real-time executive• To introduce generic architectures for monitoring and controland data acquisition systemsTopics Covered• Systems design• Real-time executives• Monitoring and control systems• Data acquisition systemsReal-time Systems• Systems, which monitor and control their environment• Inevitably associated with hardware devicesSensors: Collect data from the system environmentActuators: Change (in some way) the system’s environment• Time is critical. Real-time systems MUST respond withinspecified timesDefinition• A real-time system is a software system where the correct
    • functioning of the system depends on the results producedby the system and the time at which these results areproduced• A ‘soft’ real-time system is a system whose operation isdegraded if results are not produced according to thespecified timing requirements• A ‘hard’ real-time system is a system whose operation isincorrect if results are not produced according to the timingspecificationStimulus/Response Systems• Given a stimulus, the system must produce a responsewithin a specified time• Periodic stimuli. Stimuli, which occur at predictable timeintervalsFor example, a temperature sensor may be polled 10 times persecond• A periodic stimuli. Stimuli, which occur at unpredictabletimesFor example, a system power failure may trigger an interrupt,which must be processed by the systemArchitectural Considerations• Because of the need to respond to timing demands made bydifferent stimuli/responses, the system architecture mustallow for fast switching between stimulus handlers• Timing demands of different stimuli are different so asimple sequential loop is not usually adequate• Real-time systems are usually designed as cooperatingprocesses with a real-time executive controlling theseprocessesA Real-time System ModelReal-timecontrol sys temActuator Act uat or Actuator ActuatorSensor Sensor Sensor Sensor Sensor SensorSystem Elements
    • • Sensors control processesCollect information from sensors. May buffer informationcollected in response to a sensor stimulus• Data processorCarries out processing of collected information and computesthe system response• Actuator controlGenerates control signals for the actuatorSensor/Actuator ProcessesDatap roces so rActuat orcontrolActuat orSenso rcon trolS en sorSt imulus ResponseSystem Design• Design both the hardware and the software associated withsystem. Partition functions to either hardware or software• Design decisions should be made on the basis on nonfunctionalsystem requirementsUNIT IIDESIGN, VERIFICATION AND VALIDATIONCHAPTER 12LESSON 21 AND 22:REAL-TIME SOFTWARE DESIGN© Copy Right: Rai University11.676.2 75SOFTWARE ENGINEERING• Hardware delivers better performance but potentially longerdevelopment and less scope for changeHardware and Software DesignEst ab lis hs ys tem
    • requirementsParti ti onrequirementsHardwarerequ irementsHardwared es ignSo ftwarerequ ir em ent sSo ftwaredes ig nR-t Systems Design Process• Identify the stimuli to be processed and the requiredresponses to these stimuli• For each stimulus and response, identify the timingconstraints• Aggregate the stimulus and response processing intoconcurrent processes.• A process may be associated with each class of stimulus andresponse• Design algorithms to process each class of stimulus andresponse. These must meet the given timing requirements• Design a scheduling system, which will ensure that processesare started in time to meet their deadlines• Integrate using a real-time executive or operating systemTiming Constraints• May require extensive simulation and experiment to ensurethat these are met by the system• May mean that certain design strategies such as objectorienteddesign cannot be used because of the additionaloverhead involved• May mean that low-level programming language featureshave to be used for performance reasonsState Machine Modelling
    • • The effect of a stimulus in a real-time system may trigger atransition from one state to another.• Finite state machines can be used for modelling real-timesystems.• However, FSM models lack structure. Even simple systemscan have a complex model.• The UML includes notations for defining state machinemodelsMicrowave Oven State MachineFull powerEnableddo: operateovenFullp owerHalfpowerHalfpowerFullp owerNumberTimerDooropenDoorclo sedDoorclo sedSystemfaultStartdo: set power= 600Half p ower
    • do: set power=3 00Set timed o: get numberexit: set timeDisabledOperationTimerCancelWaitingdo: displaytimeWaitingd o: di splaytimedo: displayReady do: displayWaitin gReal-time Programming• Hard-real time systems may have to programmed inassembly language to ensure that deadlines are met• Languages such as C allow efficient programs to be writtenbut do not have constructs to support concurrency or sharedresource management• Ada as a language designed to support real-time systemsdesign so includes a general-purpose concurrency mechanismJava As A Real-time Language• Java supports lightweight concurrency (threads andsynchronized methods) and can be used for some soft realtimesystems• Java 2.0 is not suitable for hard RT programming orprogramming where precise control of timing is requiredNot possible to specify thread execution timeUncontrollable garbage collection
    • Not possible to discover queue sizes for shared resourcesVariable virtual machine implementationNot possible to do space or timing analysisReal-time Executives• Real-time executives are specialised operating systems, whichmanage the processes in the RTS• Responsible for process management and resource(processor and memory) allocation• May be based on a standard RTE kernel which is usedunchanged or modified for a particular application• Does not include facilities such as file managementExecutive Components• Real-time clockProvides information for process scheduling.• Interrupt handlerManages aperiodic requests for service.• SchedulerChooses the next process to be run.• Resource managerAllocates memory and processor resources.76 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERING• DespatcherStarts process execution.Non-stop System Components• Configuration managerResponsible for the dynamic reconfiguration of the systemsoftware and hardware. Hardware modules may be replaced andsoftware upgraded without stopping the systems• Fault managerResponsible for detecting software and hardware faults andtaking appropriate actions (e.g. switching to backup disks) toensure that the system continues in operationReal-time Executive Components
    • Pro ce ss resourcerequ irement sSchedul erSchedul ingi nformat ionRe so ur c em anag erDe spatch erRe al-t im ec lo ckProce ssesawa it in gre sourc esRe adyl is tInte rrupth an dl e rAvail ablere so urc el istProces sorl istEx ecutin gp roces sR eadypro ce sse sRe le as edre sourc esProcess Priority• The processing of some types of stimuli must sometimestake priority• Interrupt level priority. Highest priority, which is allocated toprocesses requiring a very fast response• Clock level priority. Allocated to periodic processes• Within these, further levels of priority may be assigned
    • Interrupt Servicing• Control is transferred automatically to a pre-determinedmemory location• This location contains an instruction to jump to an interruptservice routine• Further interrupts are disabled, the interrupt serviced andcontrol returned to the interrupted process• Interrupt service routines MUST be short, simple and fastPeriodic Process Servicing• In most real-time systems, there will be several classes ofperiodic process, each with different periods (the timebetween executions), execution times and deadlines (the timeby which processing must be completed)• The real-time clock ticks periodically and each tick causes aninterrupt which schedules the process manager for periodicprocesses• The process manager selects a process, which is ready forexecutionProcess Management• Concerned with managing the set of concurrent processes• Periodic processes are executed at pre-specified time intervals• The executive uses the real-time clock to determine when toexecute a process• Process period - time between executions• Process deadline - the time by which processing must becompleteRTE Process ManagementReso urce mana gerAllocate memoryand p ro ces so rSchedulerCh oo se p roces sfo r executio nDespatcher
    • Start executio n on anav ailab le pro ces so rProcess Switching• The scheduler chooses the next process to be executed by theprocessor. This depends on a scheduling strategy, which maytake the process priority into account• The resource manager allocates memory and a processor forthe process to be executed• The despatcher takes the process from ready list, loads itonto a processor and starts executionScheduling Strategies• Non pre-emptive schedulingOnce a process has been scheduled for execution, it runs tocompletion or until it is blocked for some reason (e.g. waitingfor I/O)• Pre-emptive schedulingThe execution of executing processes may be stopped if ahigher priority process requires service• Scheduling algorithmsRound-robinRate monotonicShortest deadline firstMonitoring and Control Systems• Important class of real-time systems• Continuously check sensors and take actions depending onsensor values• Monitoring systems examine sensors and report their results• Control systems take sensor values and controlhardware actuatorsBurglar Alarm System• A system is required to monitor sensors on doors andwindows to detect the presence of intruders in a building• When a sensor indicates a break-in, the system switches onlights around the area and calls police automatically• Sensors
    • Movement detectors, window sensors, door sensors.50 window sensors, 30 door sensors and 200 movementdetectorsVoltage drop sensor© Copy Right: Rai University11.676.2 77SOFTWARE ENGINEERING• ActionsWhen an intruder is detected, police are called automatically.Lights are switched on in rooms with active sensors.An audible alarm is switched on.The system switches automatically to backup power when avoltage drop is detected.The R-T System Design Process• Identify stimuli and associated responses• Define the timing constraints associated with each stimulusand response• Allocate system functions to concurrent processes• Design algorithms for stimulus processing and responsegeneration• Design a scheduling system, which ensures that processeswill always be scheduled to meet their deadlinesStimuli to be Processed• Power failureGenerated aperiodically by a circuit monitor. When received, thesystem must switch to backup power within 50ms• Intruder alarmStimulus generated by system sensors. Response is to call thepolice, switch on building lights and the audible alarmTiming RequirementsStimulus /Respons e Timing re quirementsPower fai l interrupt Th e switch to back up p ower must be co mpletedwithin a dead line of 5 0 ms .Doo r ala rm Eac h do or ala rm sh ou ld be polled twice per
    • second .Win dow alarm Eac h window alarm sh ould be polled twice p ersecond .Movem ent detec tor Eac h mo vement de tect or s hould be polledtwiceper s eco nd.Aud ible alarm Th e a ud ible alarm should b e sw itche d on within1/2 s eco nd of an a larm be ing r aised by a s ensor .Lights sw itch Th e l igh ts sho uld b e switched on w ithin 1 /2second o f an alarm b ei ng raised by a sensor .Comm un icatio ns Th e ca ll to the police shou ld be s tar tedwithin 2seconds o f an alarm being raised by a sensor .Voi ce synth esiser A synthesised message shou ld be av ai lab lewithin 4 s econds of an a larm be ing r aised by asens or.Process ArchitectureLighti ng contro lproce ssAudible alarmp rocessVoice synthesiz erprocessAlarm systemproce ssPower swit chproces sBuilding monitorproce ssCommuni cat ionprocessDoor se nsorproce ssMovementdet ector proce ss
    • Wi ndow se nsorproce ss560Hz400Hz 60Hz 1 00HzPower fa ilureinter ruptAlarmsys temBuilding monitorAl armsystemAla rm s ystemAla rm s ystemDet ector stat us S ensor st at us Sen sor statusRoom numberAl ert messageRoom numberRoom numbe rBuilding Monitor Process 1}// See http://www.software-engin.com/ for links to thecomplete Java code for this// exampleclass BuildingMonitor extends Thread {Buil dingSensor win, door, move ;Siren siren = new Siren () ;Lights lights = newLights () ;Synthesizer synthesizer = new Synthesizer () ;DoorSensors doors = new DoorSensors (30) ;WindowSensors windows = new WindowSensors (50) ;MovementSensors movements = new MovementSensors(200) ;PowerMonitor pm = new PowerMonitor () ;Buil dingMonitor(){
    • // initialise al l the sensors and start the processessiren.start () ; lights.start () ;synthesizer.start () ; windows.start () ;doors.start () ; movements.start () ; pm.start () ;Building Monitor Process 2public void run (){int room = 0 ;while (t rue){// poll the movement sensors at least twice per second (400Hz)move =movements.getVal () ;// poll the window sensors at least twice/second (100 Hz)win = windows.getVal () ;// poll the door sensors at least twice per second (60 Hz)door = doors.getVal () ;if (move.sensorVal == 1 | door.sensorVal == 1 |win.sensorVal == 1){// a sensor has indicated an intruderif (move.sensorVal == 1) room =move.room ;if (door.sensorVal == 1) room =door.room ;if (win.sensorVal == 1 ) room =win.room ;lights.on (room) ; siren.on () ; synthesizer.on (room) ;break ;}}lights.shutdown () ; siren.shutdown () ; synthesizer.shutdown() ;windows.shutdown () ; doors.shutdown () ;movements.shutdown () ;} // run} //BuildingMonitorControl Systems
    • • A burglar alarm system is primarily a monitoring system. Itcollects data from sensors but no real-time actuator control• Control systems are similar but, in response to sensorvalues, the system sends control signals to actuators• An example of a monitoring and control system is a system,which monitors temperature and switches heaters on and off78 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGA Temperature Control SystemThermostatprocessSensorprocessFurnacecontrolprocessHeater controlprocess500Hz500Hz500Hz Thermostat processSensorvaluesSwitch commandRoomnumberData Acquisition Systems• Collect data from sensors for subsequent processing andanalysis.• Data collection processes and processing processes may havedifferent periods and deadlines.• Data collection may be faster than processing e.g. collectinginformation about an explosion.• Circular or ring buffers are a mechanism for smoothingspeed differences.Reactor Data Collection
    • • A system collects data from a set of sensors monitoring theneutron flux from a nuclear reactor.• Flux data is placed in a ring buffer for later processing.• The ring buffer is itself implemented as a concurrent processso that the collection and processing processes may besynchronized.Reactor Flux MonitoringDisplayPro ces sd ataSen sor datab ufferSen so rp ro ces sSen so ridentifier an dvalu ePro ces sedflux levelSen so rs (each data flow is a sensor v alu e)A Ring BufferConsumerprocessProducerprocessMutual Exclusion• Producer processes collect data and add it to the buffer.Consumer processes take data from the buffer and makeelements available• Producer and consumer processes must be mutuallyexcluded from accessing the same element.• The buffer must stop producer processes addinginformation to a full buffer and consumer processes tryingto take information from an empty buffer.Java Implementation of a Ring Buffer 1
    • class CircularBuffer{int bufsize ;SensorRecord [] store ;int numberOfEntries = 0 ;int front = 0, back = 0 ;CircularBuffer (int n) {bufsize = n ;store = new SensorRecord [bufsize] ;} // CircularBuffersynchronized void put (SensorRecord rec ) throwsInterruptedException{if ( numberOfEntries == bufsize)wait () ;store [back] = new SensorRecord (rec.sensorId,rec.sensorVal) ;back = back + 1 ;if (back == bufsize)back = 0 ;numberOfEntries = numberOfEntries + 1 ;notify () ;} // putJava Implementation of a Ring Buffer 2synchronized SensorRecord get () throwsInterruptedException{SensorRecord result = new SensorRecord (-1, -1) ;if (numberOfEntries == 0)wait () ;result = store [front] ;front = front + 1 ;if (front == bufsize)front = 0 ;numberOfEntries = numberOfEntries - 1 ;
    • notify () ;return result ;} // get} // CircularBufferKey Points• Real-time system correctness depends not juston what the system does but also on how fast itreacts• A general RT system model involves associating processeswith sensors and actuators• Real-time systems architectures are usually designed as anumber of concurrent processes• Real-time executives are responsible forprocess and resource management.• Monitoring and control systems poll sensors and sendcontrol signal to actuators• Data acquisition systems are usually organised according to aproducer consumer model© Copy Right: Rai University11.676.2 79SOFTWARE ENGINEERING• Java has facilities for supporting concurrency but is notsuitable for the development of time-critical systemsActivityUsing examples, explain why real time systems usually have tobe implemented using processes.ActivityExplain why an object oriented approach to software developmentmay not be suitable for real time systems.ActivityDraw state machine models of the control software for thefollowing systems:• An automatic washing machine, which has differentprograms for different types of clothes.• The software for a compact disc player.
    • • A telephone answering machine, which records incomingmessages and displays the number of accepted messages onan LED display. The system should allow the telephoneowner to dial in, type a sequence of numbers (identified astones) and have the recorded messages replayed over thephone.• A drinks vending machine, which can dispense coffee withand without milk and sugar. The user deposits a coin andmakes his or her selection by pressing a button on themachine. This causes a cup with powdered coffee to beoutput. The user places this cup under a tap, presses anotherbutton and hot eater is dispensed.ActivityDiscuss the strengths and weaknesses of Java as a programminglanguage for real time systems.80 11.676.2© Copy Right: Rai UniversitySOFTWARE ENGINEERINGActivityYou are asked to work on a real-time development project for amilitary application but have no previous experience of projectsin that domain. Discuss what you, as a professional softwareengineer, should do before starting work on the project.Notes:Lecture-23: Software Re-engineering• Reorganising and modifying existing software systemsto make themmore maintainableObjectives• To explain why software re-engineering is a cost-effective optionfor systemevolution• To describe the activities involved in the software re-engineeringprocess
    • • To distinguish between software and data re-engineering and toexplain theproblems of data re-engineeringTopics covered• Source code translation• Reverse engineering• Program structure improvement• Program modularisation• Data re-engineeringSystem re-engineering• Re-structuring or re-writing part or all of alegacy system without changing itsfunctionality• Applicable where some but not all sub-systemsof a larger system require frequentmaintenance• Re-engineering involves adding effort to makethem easier to maintain. The system may be re-structured and re-documentedWhen to re-engineer• When system changes are mostly confined topart of the system then re-engineer that part• When hardware or software support becomesobsolete• When tools to support re-structuring areavailableRe-engineering advantages• Reduced risk•There is a high risk in new software development. There may bedevelopment problems,staffing problems and specification problems• Reduced cost•The cost of re-engineering is often significantly less than the costsof developing newsoftware
    • Business process re-engineering• Concerned with re-designing business processes to make themmore responsiveand more efficient• Often reliant on the introduction of new computer systems tosupport the revisedprocesses• May force software re-engineering as the legacy systems aredesigned to supportexisting processesForward engineering and re-engineeringUnderstanding andtransformationExistingsoftware systemRe-engineeredsystemDesign andimplementationSystemspecificationNewsystemSoftware re-engineeringForward engineeringThe re-engineering processReverseengineeringProgramdocumentationDatareengineeringOriginal dataProgramstructure
    • improvementProgrammodularisationStructuredprogramReengineereddataModularisedOriginal programprogramSource codetranslationRe-engineering cost factors• The quality of the software to be re-engineered• The tool support available for re-engineering• The extent of the data conversion, which is required• The availability of expert staff for re-engineeringRe-engineering approachesA Automated restructuringwith manual changesutomated sourcecode conversionRestructuring plusarchitectural changesAutomated programrestructuringProgram and datarestructuringIncreased costSource code translation• Involves converting the code from one language (or languageversion) to anothere.g. FORTRAN to C• May be necessary because of:•Hardware platform update
    • •Staff skill shortages•Organisational policy changes• Only realistic if an automatic translator is availableThe program translation processAutomaticallytranslate codeDesign translatorinstructionsIdentify sourcecode differencesManuallytranslate codeSystem to bere-engineeredSystem to bere-engineeredRe-engineeredsystemReverse engineering• Analysing software with a view to understanding its design andspecification• May be part of a re-engineering process but may also be used tore-specify asystem for re-implementation• Builds a program data base and generates information from this• Program understanding tools (browsers, cross-referencegenerators, etc.) may beused in this processThe reverse engineering processData stucturediagramsProgram stucturediagramsTraceabilitymatrices
    • DocumentgenerationSysteminformationstoreAutomatedanalysisManualannotationSystem to bere-engineered• Reverse engineering often precedes re-engineering but issometimes worthwhilein its own right•The design and specification of a system may be reverseengineered so that they can bean input to the requirements specification process for the system’sreplacement•The design and specification may be reverse engineered tosupport program maintenanceProgram structure improvement• Maintenance tends to corrupt the structure of a program. Itbecomes harder andharder to understand• The program may be automatically restructured to removeunconditional branches• Conditions may be simplified to make them more readableCondition simplification-- Complex conditionif not (A > B and (C < D or not (E > F)))...-- Simplified conditionif (A <= B and (C>= D or E > F)...Automatic program restructuringGraphrepresentation
    • ProgramgeneratorRestructuredprogramAnalyser andgraph builderProgram to berestructuredRestructuring problems• Problems with re-structuring are:•Loss of comments•Loss of documentation•Heavy computational demands• Restructuring doesn’t help with poor modularisation whererelated componentsare dispersed throughout the code• The understandability of data-driven programs may not beimproved by restructuringProgram modularisation• The process of re-organising a program so that related programparts are collectedtogether in a single module• Usually a manual process that is carried out by programinspection and reorganisationModule types• Data abstractions•Abstract data types where data structures and associatedoperations are grouped• Hardware modules•All functions required to interface with a hardware unit• Functional modules•Modules containing functions that carry out closely related tasks• Process support modules•Modules where the functions support a business process orprocess fragment
    • Recovering data abstractions• Many legacy systems use shared tables and global data to savememory space• Causes problems because changes have a wide impact in thesystem• Shared global data may be converted to objects or ADTs•Analyse common data areas to identify logical abstractions•Create an ADT or object for these abstractions•Use a browser to find all data references and replace withreference to the dataabstractionData abstraction recovery• Analyse common data areas to identify logical abstractions• Create an abstract data type or object class for each of theseabstractions• Provide functions to access and update each field of the dataabstraction• Use a program browser to find calls to these data abstractions andreplace thesewith the new defined functionsData re-engineering• Involves analysing and reorganising the data structures (andsometimes the datavalues) in a program• May be part of the process of migrating from a file-based systemto a DBMSbasedsystem or changing from one DBMS to another• Objective is to create a managed data environmentApproaches to data re-engineeringApproach DescriptionData cleanup The data records and values are analysed to improvetheir quality.Duplicates are removed, redundant information is deleted and aconsistentformat applied to all records. This should not normally require any
    • associated program changes.Data extension In this case, the data and associated programs arere-engineered to removelimits on the data processing. This may require changes toprograms toincrease field lengths, modify upper limits on the tables, etc. Thedata itselfmay then have to be rewritten and cleaned up to reflect theprogramchanges.Data migration In this case, data is moved into the control of amodern databasemanagement system. The data may be stored in separate files ormay bemanaged by an older type of DBMS.Data problems• End-users want data on their desktop machines rather than in afile system. Theyneed to be able to download this data from a DBMS• Systems may have to process much more data than was originallyintended bytheir designers• Redundant data may be stored in different formats in differentplaces in thesystemData value inconsistenciesData inconsistency DescriptionInconsistent defaultvaluesDifferent programs assign different default values to the samelogical dataitems. This causes problems for programs other than those thatcreated thedata. The problem is compounded when missing values areassigned a
    • default value that is valid. The missing data cannot then bediscovered.Inconsistent units The same information is represented in differentunits in differentprograms. For example, in the US or the UK, weight data may berepresented in pounds in older programs but in kilograms in morerecentsystems. A major problem of this type has arisen in Europe withtheintroduction of a single European currency. Legacy systems havebeenwritten to deal with national currency units and data has to beconverted toeuros.Inconsistent validationrulesDifferent programs apply different data validation rules. Datawritten byone program may be rejected by another. This is a particularproblem forarchival data which may not have been updated in line withchanges todata validation rules.InconsistentrepresentationsemanticsPrograms assume some meaning in the way items are represented.Forexample, some programs may assume that upper-case text meansanaddress. Programs may use different conventions and maytherefore rejectdata which is semantically valid.Inconsistent handlingof negative values
    • Some programs reject negative values for entities which mustalways bepositive. Others, however, may accept these as negative values orfail torecognise them as negative and convert them to a positive value.Data migration• Data naming problems•Names may be hard to understand. The same data may havedifferent names in differentprogramsDatabasemanagementsystemLogical andphysicaldata modelsdescribesFile 1 File 2 File 3 File 4 File 5 File 6Program 2 Program 3Program 4 Program 5 Program 6 Program 7Program 1Program 3 Program 4 Program 5 Program 6Program 2 Program 7Program 1Becomes• Field length problems•The same item may be assigned different lengths in differentprograms• Record organisation problems•Records representing the same entity may be organised differentlyin different programs• Hard-coded literals• No data dictionaryData conversion
    • • Data re-engineering may involve changing the data structureorganisation withoutchanging the data values• Data value conversion is very expensive. Special-purposeprograms have to bewritten to carry out the conversionThe data re-engineering processKey points• The objective of re-engineering is to improve the systemstructure to make iteasier to understand and maintainEntity namemodificationLiteralreplacementData definitionre-orderingDatare-formattingDefault valueconversionValidation rulemodificationDataanalysisDataconversionDataanalysisModifieddataProgram to be re-engineeredChange summary tablesStage 1 Stage 2 Stage 3
    • • The re-engineering process involves source code translation,reverse engineering,program structure improvement, program modularisation and datare-engineering• Source code translation is the automatic conversion of program inone language toanother• Reverse engineering is the process of deriving the system designand specificationfrom its source code• Program structure improvement replaces unstructured controlconstructs withwhile loops and simple conditionals• Program modularisation involves reorganisation to group relateditems• Data re-engineering may be necessary because of inconsistentdata managementActivitiesActivity 1:- Under what circumstances do you think that softwareshould scrapped andrewritten rather than re-engineered?Activity 2:- Write a set of guidelines that may be used to help findmodules in anunstructured program.Activity 3:- What problems might arise when converting data formone type of databasemanagement system to another (e.g. hierarchical to relational orrelational to object –oriented?Activity 4:- Explain why it is impossible to recover a systemspecification beautomatically analyzing system source code.Activity 5:- Using examples, describe the problems with datadegradation which mayhave to be tackled during the process of data cleanup.
    • Activity 6:- The year 2000 problem where dates were representedas two digits posed amajor program maintenance problem for many organizations.What were the implicationsof this problem for data re-engineering?Activity 7:- A company routinely places contractual conditions onfreelance working onre-engineering their applications which prevents them from takingon contracts withsimilar companies. The reason for this is that re-engineeringinevitably reveals businessinformation. Is this a reasonable position for a company to takegiven that they have noobligations to contractors after their contract has finished?Lecture-24: Configuration management• Managing the products of system changeObjectives• To explain the importance of software configuration management(CM)• To describe key CM activities namely CM planning, changemanagement, versionmanagement and system building• To discuss the use of CASE tools to support configurationmanagement processesTopics covered• Configuration management planning• Change management• Version and release management• System building• CASE tools for configuration managementConfiguration management• New versions of software systems are created as they change•For different machines/OS•Offering different functionality•Tailored for particular user requirements
    • • Configuration management is concerned with managing evolvingsoftwaresystems•System change is a team activity•CM aims to control the costs and effort involved in makingchanges to a system• Involves the development and application of procedures andstandards to managean evolving software product• May be seen as part of a more general quality managementprocess• When released to CM, software systems are sometimes calledbaselines, as theyare a starting point for further developmentSystem familiesWorkstationversionUnixversionDECversionInitialsystemMainframeversionVMSversionPCversionSunversionCM standards• CM should always be based on a set of standards, which areapplied within anorganisation
    • • Standards should define how items are identified; how changesare controlled andhow new versions are managed• Standards may be based on external CM standards (e.g. IEEEstandard for CM)• Existing standards are based on a waterfall process model - newstandards areneeded for evolutionary developmentConcurrent development and testing• A time for delivery of system components is agreed• A new version of a system is built from these components bycompiling andlinking them• This new version is delivered for testing using pre-defined tests• Faults that are discovered during testing are documented andreturned to thesystem developersDaily system building• It is easier to find problems that stem from componentinteractions early in theprocess• This encourages thorough unit testing - developers are underpressure not to‘break the build’• A stringent change management process is required to keep trackof problems thathave been discovered and repairedConfiguration management planning• All products of the software process may haveto be managed•Specifications•Designs•Programs•Test data•User manuals
    • • Thousands of separate documents aregenerated for a large software systemCM planning• Starts during the early phases of the project• Must define the documents or documentclasses, which are to be managed (Formaldocuments)• Documents which might be required for futuresystem maintenance should be identified and specified as manageddocumentsThe CM plan• Defines the types of documents to be managed and a documentnaming scheme• Defines who takes responsibility for the CM procedures andcreation of baselines• Defines policies for change control and version management• Defines the CM records which must be maintained• Describes the tools, which should be used to assist the CMprocess and anylimitations on their use• Defines the process of tool use• Defines the CM database used to record configurationinformation• May include information such as the CM of external software,process auditing,etc.Configuration item identification• Large projects typically produce thousands of documents, whichmust be uniquelyidentified• Some of these documents must be maintained for the lifetime ofthe software• Document naming scheme should be definedso that related documents have related names.• A hierarchical scheme with multi-level names is
    • probably the most flexible approachConfiguration hierarchyPCL-TOOLSEDITSTRUCTURESBINDFORMCOMPILE MAKE-GENHELPThe configuration database• All CM information should be maintained in aconfiguration database• This should allow queries about configurations to beanswered•Who has a particular system version?•What platform is required for a particular version?•What versions are affected by a change to component X?•How many reported faults in version T?• The CM database should preferably be linked to the softwarebeing managedCM database implementation• May be part of an integrated environment to support softwaredevelopment. TheCM database and the managed documents are all maintained on thesame system• CASE tools may be integrated with this so that there is a closerelationshipbetween the CASE tools and the CM tools• More commonly, the CM database is maintained separately asthis is cheaper andmore flexibleChange management• Software systems are subject to continualchange requests•From users
    • •From developers•From market forces• Change management is concerned with keepingmanaging of these changes and ensuring thatthey are implemented in the most cost-effectivewayThe change management processRequest change by completing a change request formAnalyze change requestif change is valid thenAssess how change might be implementedAssess change costSubmit request to change control boardif change is accepted thenrepeatmake changes to softwaresubmit changed software for quality approvaluntil software quality is adequatecreate new system versionelsereject change requestelsereject change requestChange request form• Definition of change request form is part of theCM planning process• Records change required, suggestor of change,reason why change was suggested andurgency of change (from requestor of thechange)• Records change evaluation, impact analysis,change cost and recommendations (Systemmaintenance staff)Change Request FormProject: Proteus/PCL-Tools Number: 23/94
    • Change requester: I. Sommerville Date: 1/12/98Requested change: When a component is selected from thestructure,display the name of the file where it is stored.Change analyser: G. Dean Analysis date: 10/12/98Components affected: Display-Icon.Select, Display-Icon.DisplayAssociated components: FileTableChange assessment: Relatively simple to implement as a filename tableis available. Requires the design and implementation of a displayfield. Nochanges to associated components are required.Change priority: LowChange implementation:Estimated effort: 0.5 daysDate to CCB: 15/12/98 CCB decision date: 1/2/99CCB decision: Accept change. Change to be implemented inRelease 2.1.Change implementor: Date of change:Date submitted to QA: QA decision:Date submitted to CM:CommentsChange tracking tools• A major problem in change management istracking change status• Change tracking tools keep track the status ofeach change request and automatically ensurethat change requests are sent to the rightpeople at the right time.• Integrated with E-mail systems allowingelectronic change request distributionChange control board• Changes should be reviewed by an external group who decidewhether or not they
    • are cost-effective from a strategic and organizational viewpointrather than atechnical viewpoint• Should be independent of project responsiblefor system. The group is sometimes called a change control board• May include representatives from client andcontractor staffDerivation history• Record of changes applied to a document orcode component• Should record, in outline, the change made, the rationale for thechange, whomade the change and when it was implemented• May be included as a comment in code. If a standard prologuestyle is used for thederivation history, tools can process this automaticallyComponent header information// PROTEUS p roject (ESP RIT 6087)//// PCL-TOOLS/EDIT/FORMS/DISP LAY/AST-INTERFACE//// Obje ct: PC L-Tool-Des c// Autho r: G. Dea n// Cre a tion d at e : 10th Novemb er 199 8//// © Lancas te r Unive rs ity 199 8//// Modification his tory// Ver s ion Modifier Date Change Rea son// 1.0 J . J ones 1/12/1998 Add h eade r Submitted to CM// 1.1 G. De an 9/4/1999 New field Change re q. R07/99Version and release management• Invent identification scheme for systemversions• Plan when new system version is to be
    • produced• Ensure that version management procedures and tools areproperly applied• Plan and distribute new system releasesVersions/variants/releases• Version An instance of a system, which isfunctionally distinct in some way from othersystem instances• Variant An instance of a system, which isfunctionally identical but non-functionallydistinct from other instances of a system• Release An instance of a system, which isdistributed to users outside of the developmentteamVersion identification• Procedures for version identification should define anunambiguous way ofidentifying component versions• Three basic techniques for component identification•Version numbering•Attribute-based identification•Change-oriented identificationVersion numbering• Simple naming scheme uses a linear derivatione.g. V1, V1.1, V1.2, V2.1, V2.2 etc.• Actual derivation structure is a tree or anetwork rather than a sequence• Names are not meaningful.• Hierarchical naming scheme may be betterVersion derivation structureV1.0 V1.1 V1.2 V2.0 V2.1 V2.2V1.1b V1.1.1V1.1aAttribute-based identification• Attributes can be associated with a version with
    • the combination of attributes identifying thatversion• Examples of attributes are Date, Creator,Programming Language, Customer, and Status etc.• More flexible than an explicit naming schemefor version retrieval; Can cause problems withuniqueness• Needs an associated name for easy referenceAttribute-based queries• An important advantage of attribute-based identification is that itcan supportqueries so that you can find ‘the most recent version in Java’ etc.Example•AC3D (language =Java, platform = NT4, date = Jan 1999)Change-oriented identification• Integrates versions and the changes made to create these versions• Used for systems rather than components• Each proposed change has a change set that describes changesmade to implementthat change• Change sets are applied in sequence so that, in principle, aversion of the systemthat incorporates an arbitrary set of changes may be createdRelease management• Releases must incorporate changes forced onthe system by errors discovered by users andby hardware changes• They must also incorporate new systemfunctionality• Release planning is concerned with when toissue a system version as a releaseSystem releases• Not just a set of executable programs• May also include
    • •Configuration files defining how the release is configured for aparticular installation•Data files needed for system operation•An installation program or shell script to install the system ontarget hardware•Electronic and paper documentation•Packaging and associated publicity• Systems are now normally released on CD-ROM or asdownloadable installationfiles from the webRelease problems• Customer may not want a new release of thesystem•They may be happy with their current system as the new versionmay provide unwantedfunctionality• Release management must not assume that all previous releaseshave beenaccepted. All files required for a release should be re-created whena new releaseis installedRelease decision making• Preparing and distributing a system release is an expensiveprocess• Factors such as the technical quality of the system, competition,marketingrequirements and customer change requests should all influencethe decision ofwhen to issue a new system releaseSystem release strategyFactor DescriptionTechnical quality ofthe systemIf serious system faults are reported which affect the way in whichmany customers use the system, it may be necessary to issue a
    • fault repair release. However, minor system faults may be repairedby issuing patches (often distributed over the Internet) that can beapplied to the current release of the system.Lehman’s fifth law(see Chapter 27)This suggests that the increment of functionality which is includedin each release is approximately constant. Therefore, if there hasbeen a system release with significant new functionality, then itmay have to be followed by a repair release.Competition A new system release may be necessary because acompetingproduct is available.MarketingrequirementsThe marketing department of an organisation may have made acommitment for releases to be available at a particular date.Customer changeproposalsFor customised systems, customers may have made and paid for aspecific set of system change proposals and they expect a systemrelease as soon as these have been i mplemented.Release creation• Release creation involves collecting all files and documentationrequired to createa system release• Configuration descriptions have to be written for differenthardware andinstallation scripts have to be written• The specific release must be documented to record exactly whatfiles were used tocreate it. This allows it to be re-created if necessarySystem building• The process of compiling and linking software components intoan executablesystem
    • • Different systems are built from differentcombinations of components• Invariably supported by automated tools that are driven by ‘buildscripts’System building problems• Do the build instructions include all requiredcomponents?•When there are many hundreds of components making upa system, it is easy to miss one out. This should normallybe detected by the linker• Is the appropriate component versionspecified?•A more significant problem. A system built with the wrongversion may work initially but fail after delivery• Are all data files available?•The build should not rely on standard data files. Standardsvary from place to place• Are data file references within componentscorrect?•Embedding absolute names in code almost always causesproblems as naming conventions differ from place to place• Is the system being built for the right platform?•Sometimes must build for a specific OS version or hardwareconfiguration• Is the right version of the compiler and othersoftware tools specified?•Different compiler versions may actually generate different codeand the compiledcomponent will exhibit different behaviourSystem buildingBuildscriptSource codecomponentversions
    • Object codecomponentsExecutablesystemSystembuilderCompilersVersionmanagementsystemLinkerSystem representation• Systems are normally represented for building by specifying thefile name to beprocessed by building tools. Dependencies between these aredescribed to thebuilding tools• Mistakes can be made as users lose track of which objects arestored in whichfiles• A system modelling language addresses this problem by using alogical ratherthan a physical system representationCASE tools for configuration management• CM processes are standardised and involve applying pre-definedprocedures• Large amounts of data must be managed• CASE tool support for CM is therefore essential• Mature CASE tools to support configuration management areavailable rangingfrom stand-alone tools to integrated CM workbenchesChange management tools• Change management is a procedural process so it can bemodelled and integratedwith a version management system
    • • Change management tools•Form editor to support processing the change request forms•Workflow system to define who does what and to automateinformation transfer•Change database that manages change proposals and is linked to aVM systemVersion management tools• Version and release identification•Systems assign identifiers automatically when a new version issubmitted to the system• Storage management.•System stores the differences between versions rather than all theversion code• Change history recording•Record reasons for version creation• Independent development•Only one version at a time may be checked out for change.Parallel working on differentversionsDelta-based versioningVersion1.0Version1.1Version1.2Version1.3D1 D2 D3Creation dateSystem building• Building a large system is computationally expensive and maytake several hours• Hundreds of files may be involved• System building tools may provide
    • •A dependency specification language and interpreter•Tool selection and instantiation support•Distributed compilation•Derived object managementComponent dependenciescompscan.o syn.o sem.o cgen.oKey points• Configuration management is the management of system changeto softwareproducts• A formal document-naming scheme should beestablished and documents should be managed in a database• The configuration database should record information aboutchanges and changerequests• A consistent scheme of version identification should beestablished using versionnumbers, attributes or change sets• System releases include executable code, data, configuration filesanddocumentation• System building involves assembling components into a system• CASE tools are available to support all CM activities• CASE tools may be stand-alone tools or may be integratedsystems whichintegrate support for version management, system building andchangemanagementActivitiesActivity 1:- Explain why you should not use the title of adocument to identify thedocument in a configuration management system. Suggest astandard for a document
    • identification scheme that may be used for all projects in anorganization.Activity 2:- Using the entity-relational or object-oriented approachdesign a model of aconfiguration database which records information about systemcomponents, versions,releases and changes. Some requirements for the data model are asfollows:• It should be possible to retrieve all versions or a single identifiedversion of acomponent.• It should be possible to retrieve the latest version of a component.• It should be possible to find out which change requests have beenimplemented bya particular version of a system.• It should be possible to discover which versions of componentsare included in aspecified version of a system.• It should be possible to retrieve a particular release of a systemaccording to eitherthe release date or the customers to whom the release wasdelivered.Activity 3:- Using a data-flow diagram. Describe a changemanagement procedure,which might be used in a large organization concerned withdeveloping software foeexternal clients. Changes may be suggested form either external orinternal sources.Activity 4:- Describe the difficulties which can be encountered insystem building.Suggest particular problems that might arise when a system is builton a host computerfor some target machine.Activity 5:- A common problem with system building occurswhen physical file names
    • are incorporated in system code and the file structure implied inthese names differs formthat of the target machine. Write a set of programmer’s guidelines,which help avoid thisand other system building problems, which you can think of.Activity 6:- Describe five factors which must be taken intoaccount by engineers duringthe process of building a release of a large software system.Activity 7:- Describe two ways in which system building tools canoptimize the processof building a version of a system form its components.