Skip to content
JNTUK · B.Tech study libraryFree access · No sign-up
JNTUK · R23 · CSE · Semester 3-1

Object Oriented Analysis and Design exam preparation.

Practice questions for every unit in the style of the R23 end exam, a model answer for each, and a one-page revision summary. Built on the official syllabus units.

  • Practice questions in the exam's style
  • Drafted with AI and checked by a second AI pass. Doubtful points were verified against public sources. Report a mistake
Units
5
Questions
60
2-mark
30
10-mark
30
Checked on

Exam guide

Paper pattern

Semester-end theory paper, 70 marks, from the JNTUK B.Tech R23 Regulations, end-examination pattern for theory subjects.

  1. Question 1 · 20 marksTen compulsory short-answer questions of 2 marks each (two from every unit).
  2. Questions 2 to 6 · 50 marksFive either/or questions of 10 marks each, one per unit. You answer one of the two in each.
  • The semester-end examination carries 70 marks; internal assessment carries 30.
  • Mid-semester examinations are separate: a 20-minute objective paper (10 marks) and a 90-minute subjective paper with three either/or questions of 10 marks (condensed to 15 marks).
  • The regulations text does not state the length of the end examination. Use the duration printed on your hall ticket or question paper.

Read the R23 regulations (PDF) ↗

How to split your time

This plan assumes a 3-hour paper. If yours is different, keep the same proportions. Marks per minute stay roughly even across Question 1 and the 10-mark answers.

  1. 10 minRead the paper and choose one option in each either/or question
  2. 30 minQuestion 1: ten short answers (about 3 minutes each)
  3. 130 minQuestions 2 to 6: one 10-mark answer per unit (about 26 minutes each)
  4. 10 minFinal check of numbering, calculations and diagrams

Study tips for Object Oriented Analysis and Design

  • Draw each UML diagram by hand with the correct notation: class, object, use case, sequence, activity, state machine, component and deployment diagrams, using the paper symbols each answer describes.
  • Learn the relationship symbols together and practise telling them apart: association, aggregation, composition, generalization, dependency and realization, with the direction of each arrow and where the multiplicity goes.
  • For every case study, model one small part completely: name the classes and actors, draw one structural and one behavioural diagram, and check that the two use the same names.
  • Write two or three lines on each idea from Booch's chapter on complexity, such as hierarchy, decomposition and abstraction, so that you can explain why software is inherently complex.
  • When a question asks you to compare, such as aggregation with composition, include with extend, or sequence with communication diagrams, answer with a short table and one example each.
Unit 1

Introduction: Complex Systems

Syllabus: The structure of complex systems; The inherent complexity of software; The attributes of a complex system; Organized and disorganized complexity; Bringing order to chaos; Designing complex systems; Case study: system architecture for satellite-based navigation

One-page revision summary

  • Computers, plants, animals, matter and social institutions are all hierarchies of interrelated subsystems, and each level of the hierarchy has its own level of abstraction.
  • Software is inherently complex because of the complexity of the problem domain, the difficulty of managing the development process, the flexibility possible through software and the problems of characterizing the behaviour of discrete systems.
  • Maintenance fixes errors, evolution responds to changing requirements, and preservation keeps old, decaying software running by extraordinary effort.
  • The five attributes of a complex system are hierarchic structure, relative primitives, separation of concerns, common patterns and stable intermediate forms.
  • Disorganized complexity shows many parts interacting in intricate ways with little visible commonality; organized complexity follows hierarchies and common patterns.
  • The canonical form of a complex system has two orthogonal hierarchies, the class structure ("is a") and the object structure ("part of"), which together form its architecture.
  • Human short-term memory holds about seven, plus or minus two, chunks of information, so designers rely on decomposition, abstraction and hierarchy.
  • Algorithmic decomposition splits a system into the steps of a process; object-oriented decomposition splits it into collaborating objects drawn from the problem domain.
  • The two decompositions are orthogonal, so a designer starts with one, preferably objects, and expresses the other within the structure it gives.
  • Engineering is both a science and an art: a designer applies theory but must also invent, balancing requirements that conflict.
  • A good design satisfies the functional specification, fits the limits of the target medium, meets performance and resource needs, respects constraints on the form of the product, and respects limits on the design process such as time, cost and tools.
  • The purpose of design is a clean and relatively simple internal structure, or architecture, and a design is the end product of the design process.
  • Building models lets designers try ideas and find mistakes cheaply, before they are built into the real system.
  • Object-oriented development uses several complementary models, covering the logical and physical views of a system and its static and dynamic behaviour.
  • A software design method has three elements: notation to express models, a process to build them in order, and tools to check them.
  • The satellite navigation case study divides the system into Satellite, Ground, Launch and User segments that meet only at defined interfaces.
  • The navigation architecture is validated by walking each use case through the segments, and nonfunctional requirements such as accuracy and availability are allocated to segments.

Learn these by heart

  • Five attributes of a complex system: hierarchic structure, relative primitives, separation of concerns, common patterns, stable intermediate forms.
  • Four elements of inherent software complexity: problem domain, development process, flexibility of software, behaviour of discrete systems.
  • Canonical form = class structure ("is a" hierarchy) + object structure ("part of" hierarchy); together they are the architecture.
  • Human short-term memory span: seven, plus or minus two, chunks of information.
  • Order from chaos comes from decomposition, abstraction and hierarchy.
  • Algorithmic decomposition = steps of a process; object-oriented decomposition = collaborating objects from the problem domain.
  • A design method = notation + process + tools.

2-mark questions

1 What is a complex system? Give two examples. 2 marks
Model answer

A complex system is one made of many interrelated parts organised in levels: the whole is divided into subsystems, each subsystem into smaller ones, until the most basic components are reached. Examples: a personal computer (system unit, CPU and memory, down to logic gates) and a plant (roots, stems and leaves, down to individual cells).

2 What is industrial-strength software? How does it differ from a small personal program? 2 marks
Model answer

Industrial-strength software is built by teams for organisations. It shows a rich set of behaviours, has a long life during which many users depend on it, and keeps changing. A small personal program is written, used and thrown away by one person. Industrial-strength software is so complex that no single developer can understand every detail of its design.

3 What is meant by stable intermediate forms in a complex system? 2 marks
Model answer

Large working systems usually grow step by step out of smaller systems that already work. Each working step is a stable intermediate form, and its parts later serve as primitives for building larger systems. Attempts to build a large system in one leap usually fail, so software should be grown in small, working increments.

4 What is the canonical form of a complex system? 2 marks
Model answer

It is the common form that almost all complex systems share: two orthogonal hierarchies. The class structure is the "is a" hierarchy (a Chip is a Component), and the object structure is the "part of" hierarchy (cpuChip is part of mainBoard). Every object is an instance of some class, and the two structures together form the system's architecture.

5 What is abstraction, and why is it needed when dealing with complexity? 2 marks
Model answer

Abstraction means ignoring the inessential details of something and working with a simplified model that keeps only the features that matter for the purpose at hand. It is needed because a person's short-term memory can hold only about seven, plus or minus two, chunks of information at once; abstraction lets each chunk carry far more meaning.

6 Name and explain the three elements of a software design method. 2 marks
Model answer

A software design method has three elements:

  • Notation: the language and symbols used to express each model, for example UML diagrams.
  • Process: the ordered activities that guide how the system's models are built.
  • Tools: software aids that remove the drudgery of drawing and maintaining models and check them, so that errors and inconsistencies are exposed.

10-mark questions

1 Explain the structure of complex systems with suitable examples. Draw the decomposition hierarchy of a personal computer. 10 marks
Model answer

Complex systems are found everywhere, in nature and in things people build, and they share a common structure. A few examples show what software designers can learn from them.

1. Structure of a personal computer. A personal computer has a few major parts: a system unit, a monitor and a keyboard. Each part can be decomposed again. The system unit holds the CPU, main memory and a disk; the CPU contains an ALU, a control unit and registers; and each of these is built from logic gates. Each level can be studied without reasoning about the levels below it: a programmer thinks about the CPU's instructions, not about its gates.

Decomposition hierarchy of a personal computerA tree with Personal computer at the top, split into System unit, Monitor and Keyboard. The System unit splits into CPU, Main memory and Disk, and the CPU into ALU, Control unit and Registers, all three built from Logic gates.PersonalcomputerSystem unitMonitorKeyboardCPUMain memoryDiskALUControl unitRegistersLogic gates
Decomposition hierarchy of a personal computer

In the figure, each line joins a part to the whole that contains it, with the whole drawn above.

2. Structure of plants and animals. A plant is made of roots, stems and leaves; these are made of tissues, and tissues are made of cells. Animals show the same layering through organs, tissues and cells. The same building block, the cell, sits at the bottom of very different structures.

3. Structure of matter. Matter is made of atoms; atoms are made of electrons, protons and neutrons; and protons and neutrons are made of still smaller particles called quarks. Each level is studied with its own laws.

4. Structure of social institutions. A large company is divided into divisions, divisions into branches, and branches into individual people. Groups form, merge and dissolve, yet the layered structure remains.

These examples teach common lessons:

  • A complex system is a hierarchy of interrelated parts, and each level is a different level of abstraction.
  • The behaviour of the whole comes from how the parts at each level cooperate, so the whole is more than the sum of its parts.
  • Where one part ends and another begins depends partly on the observer, so the same system can be divided in different ways for different purposes.
  • Parts meet at clear interfaces, so one level can be understood without the details of another.

In conclusion, complex systems are not shapeless masses; they are hierarchies of subsystems. Software can be built in the same way, by arranging its parts in levels that can each be understood on their own.

2 Why is software inherently complex? Explain the four elements that cause this complexity. 10 marks
Model answer

A small program written by one person is simple, but industrial-strength software is complex in a way that cannot be removed, only managed. Four elements make this complexity inherent.

The four elements of the inherent complexity of softwareFour boxes, Problem domain, Development process, Flexibility of software and Discrete behaviour, each point to Inherent complexity. Inherent complexity is hidden behind an Illusion of simplicity.Problem domainDevelopmentprocessFlexibilityof softwareDiscretebehaviourInherentcomplexityIllusion ofsimplicityhidden behind
The four elements of the inherent complexity of software

1. The complexity of the problem domain. The problems software solves are themselves complex. A railway reservation system must handle seat quotas, waiting lists, cancellations, payments and peak-hour loads, along with nonfunctional needs such as performance, reliability and security. Users and developers also struggle to understand each other: users find it hard to state their needs precisely, and developers lack domain knowledge. Requirements change during development, often because seeing early versions helps users say what they really want. A large system is a costly investment, so it is not thrown away: it is maintained (errors are fixed), evolved (it is changed for new requirements) and sometimes preserved (kept running by extraordinary effort after it has decayed).

2. The difficulty of managing the development process. A central aim of the team is to make the system look simple to its users: its vast internal complexity is hidden behind a simple outside view, an illusion of simplicity. Large systems need hundreds of thousands of lines of code, written by large and sometimes distributed teams. With n developers there are n(n-1)/2 possible communication paths, so 5 developers have 10 paths but 50 developers have 1,225. Keeping one unified design across so many people is hard.

3. The flexibility possible through software. Software can express almost any abstraction, so developers are tempted to build every primitive building block themselves instead of using standard parts. The building industry has codes and standards for the quality of bricks, steel and cement; software has few such standards, so much of it is still hand-crafted.

4. The problems of characterizing the behaviour of discrete systems. A program's state is the set of current values of all its variables, together with the position and call stack of each thread. This state space is enormous: only 64 yes/no flags give 2^64 ≈ 1.84 × 10^19 combinations, which would take about 585 years to test at one billion tests per second. A continuous system behaves smoothly, so a small change in input gives a small change in output; in a discrete system, one unexpected event can move the state almost anywhere. Exhaustive testing is therefore impossible.

When this complexity is not controlled, projects finish late, cost more than planned and fail to meet their requirements.

In conclusion, software complexity comes from the problem, the team, the medium and the discrete nature of programs. Decomposition, abstraction and hierarchy are the tools used to master it.

3 Explain the five attributes of a complex system with suitable examples. 10 marks
Model answer

Complex systems in very different fields share five attributes. Knowing them tells us how software should be structured.

1. Hierarchic structure. A complex system is usually organised as a hierarchy: the whole is divided into subsystems, each subsystem into smaller ones, until the most basic components are reached. A computer contains a CPU and a disk; the CPU contains an ALU and registers; these are built from logic gates. A system's architecture depends both on its parts and on the hierarchic relationships among them.

Hierarchy, primitives and link strength in a computerA part hierarchy: Computer contains CPU and Disk, the CPU contains ALU and Registers, and both are built from Logic gates, the primitive level. A strong link joins ALU and Registers inside the CPU, and a weak link joins the CPU and the Disk.Inside the CPUComputerCPUDiskALURegistersLogic gates(primitive)strong linkweak link
Hierarchy, primitives and link strength in a computer

In the figure, plain lines show the part hierarchy, with each whole above its parts, and the labelled lines show how strongly parts are linked.

2. Relative primitives. There is no fixed bottom level: what we treat as an elementary component depends on who is looking and why. To an application programmer a library function is primitive; to a chip designer the logic gate is primitive.

3. Separation of concerns. Parts inside one component interact much more strongly and often than separate components interact with each other. So the fast, frequent activity inside a component, its internal working, is kept apart from the slower, rarer activity between components, their interaction. Inside the CPU, the ALU and the registers exchange data on every clock cycle, while the CPU reads the disk far less often. Each component can therefore be studied in relative isolation.

4. Common patterns. A hierarchy usually reuses a small number of kinds of subsystem, combined and arranged in many ways. Cells build the tissues of both plants and animals; in software, a small set of structures such as loops, procedures and classes appears again and again.

5. Stable intermediate forms. Complex systems evolve over time. Large working systems usually grow step by step out of smaller systems that already work, and each working step is a stable intermediate form. Parts that were once complex become the primitives of larger systems. An attempt to build a large system in one leap usually fails, and the cure is to restart from a small system that works and grow it.

In conclusion, the five attributes show that complexity has structure: hierarchy, a chosen primitive level, strong links inside parts and weak links between them, repeated patterns, and growth through stable forms. Good software design copies this structure.

4 Distinguish between organized and disorganized complexity. Explain the canonical form of a complex system and the limits of human capacity for dealing with complexity. 10 marks
Model answer

Complexity is far easier to master when it is organized. This answer contrasts the two kinds of complexity and shows the form that organized complex systems share.

1. Disorganized complexity. When we first study a large software system, we see many parts interacting in many intricate ways, with little visible commonality among the parts or among their interactions. Such complexity is disorganized: there is no structure to hold on to, so the system cannot be understood as a whole.

2. Organized complexity. When the parts and their links follow a recognizable structure, with hierarchies, common patterns and stable intermediate forms, the complexity is organized. The system may still be large, but it can be studied level by level. Much of design is the work of turning disorganized complexity into organized complexity.

3. The canonical form. Finding common abstractions and mechanisms makes a complex system much easier to understand. When the five attributes are combined with the ideas of class and object, almost every complex system turns out to have the same canonical form, made of two orthogonal hierarchies:

  • The class structure is the "is a" hierarchy: Board is a Component, and Chip is a Component.
  • The object structure is the "part of" hierarchy: cpuChip and ramChip are part of mainBoard.

The two hierarchies are linked because every object is an instance of some class: mainBoard is an instance of Board, and cpuChip and ramChip are instances of Chip. Together, the class structure and the object structure form the system's architecture.

Canonical form: class structure and object structureThe class structure shows Board and Chip each pointing to Component with an "is a" arrow, and the object structure shows cpuChip and ramChip pointing to mainBoard with "part of" arrows. "Instance of" arrows link mainBoard to Board, and cpuChip and ramChip to Chip.Class structure (is a)Object structure (part of)ComponentChipBoardmainBoardcpuChipramChipis ais apart ofpart ofinstance ofinstance ofinstance of
Canonical form: class structure and object structure

On paper, each "is a" arrow is a generalization, drawn as a solid line with a hollow triangle at the parent class, Component. Each "part of" link is drawn with a diamond at the whole, mainBoard (filled for composition). The "instance of" link is usually shown by writing the class into the object's name, as mainBoard : Board.

4. Limits of human capacity. Even when we know this form, building it is hard, because the human mind is limited. Short-term memory holds only about seven, plus or minus two, chunks of information at a time, and absorbing each new chunk takes time. The designer of a large system must keep far more than seven concerns in mind at once, so unaided thinking breaks down. The remedy is to work with fewer, richer chunks, through decomposition, abstraction and hierarchy.

In conclusion, disorganized complexity overwhelms us, while organized complexity follows the canonical form of class and object hierarchies, which keeps each view within the limits of human understanding.

5 Explain how decomposition, abstraction and hierarchy bring order to chaos. Compare algorithmic and object-oriented decomposition with an example. 10 marks
Model answer

The inherent complexity of software cannot be removed, but three techniques let us master it: decomposition, abstraction and hierarchy. A small payroll program is the example.

1. Decomposition. The oldest way to handle complexity is divide and conquer: break the system into smaller parts, each refined independently, so that only a few parts need to be understood at a time.

a) Algorithmic decomposition. Top-down structured design breaks the program into modules, each carrying out one major step of the overall process. Run payroll is split into Read timesheets, Compute pay and Print payslips, and Compute pay into Compute gross pay and Compute deductions.

b) Object-oriented decomposition. Here the parts are the key abstractions found in the problem domain. Each object is an independent agent with its own state and behaviour, and the objects work together by sending messages: Payroll sends computePay to each Employee (message 1), the Employee sends getHours to its Timesheet (message 2), and Payroll then sends print to a Payslip (message 3).

Algorithmic and object-oriented decomposition of a payroll programTop: an algorithmic tree in which Run payroll splits into Read timesheets, Compute pay and Print payslips, and Compute pay splits into Compute gross pay and Compute deductions. Bottom: objects in which Payroll sends 1: computePay to Employee, Employee sends 2: getHours to Timesheet, and Payroll sends 3: print to Payslip.Algorithmic decompositionObject-orientedRun payrollRead timesheetsCompute payPrint payslipsComputegross payComputedeductionsPayrollEmployeePayslipTimesheet1: computePay2: getHours3: print
Algorithmic and object-oriented decomposition of a payroll program

On paper, the lower part is a communication diagram: object boxes joined by links, with a numbered message arrow beside each link.

The two views are orthogonal, so a system cannot be decomposed both ways at once. We pick one as the starting point and express the other inside the structure it gives; experience favours starting with objects.

         Algorithmic    Object-oriented
Unit     procedure      object
Basis    process steps  domain objects
Data     passed around  hidden in objects
Change   spreads widely mostly local
Reuse    procedures     classes

Object-oriented decomposition has clear advantages:

  • It gives smaller systems, because common mechanisms are reused.
  • It is more resilient to change, because it is built on stable intermediate forms.
  • It lowers risk, because the system grows step by step from smaller systems that already work.
  • It helps the designer separate concerns in a very large state space.

2. Abstraction. Since we can hold only about seven, plus or minus two, chunks of information at once, we ignore inessential details and work with a simplified, idealized model. Payroll needs to know only that an Employee can computePay, not how tax rules are applied inside it.

3. Hierarchy. Arranging abstractions in hierarchies packs more meaning into each chunk. The class structure is an "is a" hierarchy, in which subclasses share the structure and behaviour of a superclass: salaried and hourly employees, for example, are both kinds of employee. The object structure is a "part of" hierarchy that shows how objects collaborate through mechanisms: each Timesheet is part of an Employee's record.

In conclusion, decomposition divides the problem, abstraction hides detail and hierarchy relates the pieces; together they turn chaos into an understandable design.

6 Explain how the system architecture of a satellite-based navigation system is developed, from its requirements to its segments, their validation and decomposition. 10 marks
Model answer

A satellite-based navigation system (SNS) is a large, long-lived system of hardware and software: a constellation of satellites broadcasts timing and orbit data, and a receiver anywhere on Earth uses these signals to work out its position, velocity and time. Its architecture is developed as a series of models, each refining the one before.

1. State the requirements (inception). Functional: give users position, velocity and time anywhere, at any time, and let operators control the constellation. Nonfunctional: accuracy, availability, continuity of service and reliability over many years.

2. Define the boundary. The whole SNS is first treated as a black box, and the actors outside it are named, for example the User, who needs a position, and the Operator, who commands the system.

3. Find the use cases. Mission-level use cases describe what the system does over its whole life, such as initializing, running and ending operations. Each is refined into system use cases, for example broadcasting navigation signals, monitoring satellite health and launching new satellites.

4. Propose the architecture (elaboration). The SNS is divided into four segments:

  • Satellite segment: the satellites that broadcast navigation signals and send health data to the ground.
  • Ground segment: takes the Operator's commands, monitors the satellites and, as in GPS, uploads orbit and clock corrections.
  • Launch segment: places new and replacement satellites in orbit.
  • User segment: receivers that compute position, velocity and time from the signals of at least four satellites.
Segments of the satellite-based navigation systemInside the satellite navigation system, the Launch segment places satellites in orbit, the Ground segment uploads corrections to the Satellite segment and receives health data, and the Satellite segment sends navigation signals to the User segment. Outside, the Operator sends commands to the Ground segment, and the User segment gives the User position, velocity and time.Satellite navigation systemOperator (actor)Ground segmentLaunch segmentSatellitesegmentUser segmentUser (actor)commandsuploadscorrectionshealth dataplacesin orbitnavigationsignalsposition,velocity, time
Segments of the satellite-based navigation system

5. Validate the architecture. Each use case is walked through the segments, for example with an activity diagram that has one swimlane per segment. A step that no segment can perform shows a gap in the architecture.

6. Allocate nonfunctional requirements and specify interfaces. Each quality goal is assigned to the segments that must meet it; accuracy, for instance, depends on both the Ground and Satellite segments. Every link between segments, such as the ground-to-satellite uplink and the satellite-to-user signal, gets a precise interface.

7. Decompose and deploy. Each segment is split into subsystems, which are deployed on physical nodes; GPS, for example, splits its ground segment into a control centre, monitor stations and uplink antennas.

The case study applies the principles of designing complex systems. Every step builds a model (context, use cases, segments, deployment), expressed in a notation such as UML, produced by an ordered process and kept consistent with tools. Because segments meet only at defined interfaces, each is a stable intermediate form: later changes, such as adding new functions or changing the target hardware, stay local.

In conclusion, the SNS architecture is built by hierarchic decomposition into segments and subsystems, validated against use cases, and evolved without redesigning the whole.

Unit 2

Introduction to UML and Basic Structural Modeling

Syllabus: The importance of modeling; Principles of modeling; Object-oriented modeling; The conceptual model of the UML; Architecture; The software development life cycle; Classes; Relationships; Common mechanisms; Diagrams; Case study: control system for traffic management

One-page revision summary

  • A model is a simplification of reality, built because a complex system cannot be understood as a whole.
  • Models help us visualize, specify, construct and document a system.
  • Choose models carefully, express them at the precision each reader needs, keep them connected to reality, and use several nearly independent models.
  • The object-oriented view builds a system from objects and classes taken from the problem vocabulary; the algorithmic view builds it from procedures.
  • The UML is a language for visualizing, specifying, constructing and documenting the artifacts of a software-intensive system.
  • The conceptual model of the UML has three parts: building blocks (things, relationships, diagrams), rules and common mechanisms.
  • UML rules cover names, scope, visibility, integrity and execution; a model that obeys them is well formed.
  • The architecture is described by five views: use case, design, process, implementation and deployment.
  • A process suited to the UML is use case driven, architecture-centric, and iterative and incremental.
  • The Unified Process has four phases, inception, elaboration, construction and transition, each ending at a milestone.
  • A class is drawn as a rectangle with name, attribute and operation compartments; an abstract class has its name in italics.
  • Dependency is a dashed arrow, generalization a solid line with a hollow triangle at the parent, and realization a dashed line with a hollow triangle at the interface.
  • Multiplicity such as 1, 0..1, * or 1..* is written at an association end and says how many objects take part at that end.
  • The common mechanisms are specifications, adornments, common divisions and extensibility mechanisms.
  • A note is a rectangle with a folded corner that holds a comment or a constraint.
  • Structural diagrams show the static parts of a system and behavioral diagrams show its dynamic parts.
  • In the traffic management case study, the class diagram names the vocabulary, such as Train, Route, TrackSection and Signal, before any behavior is modelled.

Learn these by heart

  • Four aims of modeling: visualize, specify, construct, document.
  • Four principles: the choice of model matters; models have levels of precision; the best models are connected to reality; no single model is sufficient.
  • Building blocks: things (structural, behavioral, grouping, annotational), relationships (dependency, association, generalization, realization) and diagrams.
  • The 4+1 views: design, process, implementation and deployment, tied together by the use case view.
  • Phases: inception, elaboration, construction, transition.
  • Visibility: + public, - private, # protected, ~ package.
  • Aggregation has a hollow diamond at the whole; composition has a filled diamond at the whole.
  • Extensibility mechanisms: stereotypes in guillemets «...», tagged values, and constraints in braces {...}.

2-mark questions

1 What is a model? State the four aims of modeling a software system. 2 marks
Model answer

A model is a simplification of reality that keeps only the details that matter for a purpose. We model a system to understand it better. Models help us visualize a system as it is or as we want it to be, specify its structure or behavior, get a template that guides its construction, and document the decisions we have made.

2 How does the object-oriented view of software modeling differ from the algorithmic view? 2 marks
Model answer

In the algorithmic view the main building block is the procedure or function, and the system is broken into steps; such systems become hard to maintain as requirements change. In the object-oriented view the main building block is the object or class, taken from the vocabulary of the problem, and every object has identity, state and behavior.

3 Name the four kinds of things in the UML, with an example of each. 2 marks
Model answer
  • Structural things, the static parts of a model, such as a class or a component.
  • Behavioral things, the dynamic parts, such as an interaction or a state machine.
  • Grouping things, which organize a model, such as a package.
  • Annotational things, which explain a model, such as a note (a rectangle with a folded corner).
4 What do the visibility markers +, -, # and ~ mean on the features of a UML class? 2 marks
Model answer

Visibility states who may use an attribute or operation. + public: any class that can see the class; - private: only the class itself; # protected: the class and its descendants; ~ package: only classes in the same package. For example, - balance : Real is a private attribute and + deposit(amount : Real) is a public operation.

5 Differentiate aggregation and composition with an example of each. 2 marks
Model answer

Both are whole-part associations. In aggregation the parts can exist without the whole and may be shared, as a Team and its Players; a hollow diamond marks the whole. In composition each part belongs to one whole at a time, which creates and destroys it, as an Order and its OrderLines; a filled diamond marks the whole.

6 What are the extensibility mechanisms of the UML? 2 marks
Model answer

They extend the UML in a controlled way:

  • Stereotype: a new kind of building block derived from an existing one, written in guillemets, e.g. «exception».
  • Tagged value: a property of a stereotype that adds new information, e.g. {version = 2.1}.
  • Constraint: a rule that adds to or changes semantics, written in braces, e.g. {ordered}.

10-mark questions

1 Why is modeling important in software development? Explain the four principles of modeling, and show how the object-oriented view of modeling differs from the algorithmic view. 10 marks
Model answer

A model is a simplification of reality: it keeps the details that matter for one purpose and leaves out the rest. We build models so that we can understand the system we are developing, because a complex system cannot be grasped as a whole. A model lets us study one aspect at a time.

Importance of modeling. Models serve four aims:

  • They help us visualize a system as it is or as we want it to be.
  • They let us specify the structure or behavior of the system.
  • They give a template that guides us in constructing it.
  • They document the decisions we have made.

A small program can be written without models, but a large system built by a team, with changing requirements, needs them so that everyone shares one picture of the design and risk stays under control.

Principles of modeling.

1. The choice of what models to create strongly affects how a problem is attacked and how the solution is shaped. A database designer sees tables and keys, an algorithmic designer sees functions and an object-oriented designer sees collaborating classes; each view leads to a different system.

2. Every model may be expressed at different levels of precision. A user may need only class names and use cases, while a programmer needs every attribute and operation.

3. The best models are connected to reality. A model simplifies, but it must not hide important details. In object-oriented development the analysis and design models use the same classes, so the link to the real problem stays visible.

4. No single model is sufficient. Every nontrivial system is best approached through a small set of nearly independent models, such as the use case, design, process, implementation and deployment views.

Object-oriented and algorithmic views.

  • Algorithmic view: the main building block is the procedure or function, and the system is decomposed into steps. When requirements change, functions spread across the design must change, so such systems become hard to maintain.
  • Object-oriented view: the main building block is the object or class. An object is a thing from the vocabulary of the problem or its solution, such as a Customer, an Order or a Product in a shopping system. Every object has identity, state and behavior, and a class describes a set of similar objects. Changes tend to stay inside the classes they affect.

In conclusion, modeling with the UML follows these principles: it offers several diagrams, each drawn at the detail its reader needs, built from classes that mirror the real problem.

2 Describe the software development life cycle best suited to the UML. Explain its four phases and the role of iterations. 10 marks
Model answer

The UML is a modeling language, not a process, so it can be used with any development method. It gives the most benefit with a process that is use case driven, architecture-centric, and iterative and incremental. The Unified Process is a life cycle of this kind.

Properties of the process:

  • Use case driven: use cases are the main artifact for stating the required behavior, checking the architecture, testing the system and communicating with stakeholders.
  • Architecture-centric: the architecture is the main artifact for conceiving, building, managing and evolving the system.
  • Iterative: the project produces a stream of executable releases.
  • Incremental: each release adds to the one before, so the architecture is integrated continuously.

Iterations are also risk-driven: each one attacks the largest risks that remain.

Phases. The life cycle is divided in time into four phases. Each ends at a milestone, where the team checks that the goals of the phase have been met before going on.

The four phases of the Unified Process life cycleFour phases run from top to bottom, Inception, Elaboration, Construction and Transition, joined by arrows labelled milestone. A note beside each phase gives its main result: vision, scope and business case; requirements and architecture; the product built in iterations; the release goes to users.InceptionElaborationConstructionTransitionVision, scope,business caseRequirements,architectureProduct builtin iterationsRelease goesto usersmilestonemilestonemilestone
The four phases of the Unified Process life cycle

1. Inception: the first idea is developed until it is sound enough to justify elaboration. The team writes the vision, the business case and the scope, lists the main risks and outlines the key use cases.

2. Elaboration: the product vision and its architecture are defined. Requirements are stated, given priorities and baselined, and an executable architecture is built that settles the riskiest technical questions.

3. Construction: the product is built in iterations, growing from the architecture baseline into software ready for its users. Requirements and evaluation criteria are re-examined against business needs as the work proceeds.

4. Transition: the release goes to users. Beta testing, training, defect fixing and small feature changes continue until the product is accepted.

Iterations. An iteration is a distinct set of work, with a plan and evaluation criteria, that ends in an executable release. Every phase holds one or more iterations. Each iteration passes through the same disciplines (business modeling, requirements, analysis and design, implementation, testing and deployment) in different proportions: early iterations stress requirements and design, while later ones stress implementation and testing. Supporting disciplines such as project management and configuration management run throughout. The UML models grow alongside: use cases first, then the classes of the architecture, then more detailed diagrams in later iterations.

In conclusion, the life cycle is a series of iterations grouped into four phases, so the system grows in small, tested releases rather than in one risky step.

3 Explain the conceptual model of the UML with a neat diagram. 10 marks
Model answer

To use the UML well, we need a conceptual model of the language. It has three major elements: the basic building blocks, the rules that say how the blocks may be put together, and the common mechanisms that apply throughout the language.

The conceptual model of the UMLThe conceptual model of UML splits into rules, building blocks and common mechanisms. Building blocks split into things, relationships and diagrams, and things split into structural, behavioral, grouping and annotational things.Conceptualmodel of UMLRulesBuilding blocksCommonmechanismsThingsRelationshipsDiagramsStructuralthingsBehavioralthingsGrouping thingsAnnotationalthings
The conceptual model of the UML

1. Building blocks. There are three kinds: things, relationships and diagrams.

Things are the abstractions in a model. There are four kinds:

  • Structural things, the static parts: class, interface, collaboration, use case, active class, component, artifact and node.
  • Behavioral things, the dynamic parts: an interaction (messages exchanged among objects), a state machine (the states an object passes through in response to events) and an activity (the sequence of steps a computation follows).
  • Grouping things, which organize a model: the package is the main one.
  • Annotational things, which explain a model: the note, a rectangle with a folded corner that holds a comment or a constraint.

Relationships tie things together. There are four:

  • dependency: a change to one thing may affect the thing that uses it (dashed arrow);
  • association: a structural link between objects, with aggregation as a whole-part special case (solid line);
  • generalization: a child is a kind of its parent (solid line, hollow triangle at the parent);
  • realization: one classifier carries out a contract specified by another, as a class realizes an interface (dashed line, hollow triangle).

Diagrams are graphical presentations of a set of elements, drawn as a connected graph of things and relationships, such as class, object, use case, sequence, activity, state machine, component and deployment diagrams.

2. Rules. The UML has semantic rules for:

  • names: what things, relationships and diagrams may be called;
  • scope: the context that gives a name its meaning;
  • visibility: how names can be seen and used by others;
  • integrity: how things relate properly and consistently;
  • execution: what it means to run or simulate a dynamic model.

A model that obeys them is well formed. While work is in progress, models may be elided, incomplete or inconsistent.

3. Common mechanisms. Four apply throughout:

  • specifications: the textual statement behind every symbol;
  • adornments: details added to a basic symbol, such as visibility or multiplicity;
  • common divisions: class and object, interface and implementation, type and role;
  • extensibility mechanisms: stereotypes, tagged values and constraints.

In conclusion, the building blocks give the vocabulary, the rules give the grammar, and the common mechanisms give a consistent style across all UML diagrams.

4 Explain the 4+1 view model of software architecture, and name the UML diagrams that model each view. 10 marks
Model answer

Architecture is the set of significant decisions about how a software system is organized: the structural elements and their interfaces, their behavior as collaborations among them, how they are composed into larger subsystems, and the style that guides this. It also weighs usage, functionality, performance, resilience, reuse, ease of understanding, economic and technology constraints, and aesthetics.

End users, analysts, developers, system integrators, testers and project managers each look at the system differently, so the architecture is described by five interlocking views. Each view is a projection of the whole model that focuses on one aspect.

The 4+1 views of a software architectureThe use case view sits in the centre, linked to the design view, implementation view, process view and deployment view. A note beside each view names its static diagrams: class and object diagrams, component diagrams, diagrams of active classes, deployment diagrams and use case diagrams.Class andobject diagramsComponentdiagramsDesign viewImplementationviewUse case viewProcess viewUse casediagramsDeployment viewDiagrams ofactive classesDeploymentdiagrams
The 4+1 views of a software architecture

1. Use case view: the use cases that describe the behavior of the system as seen by its end users, analysts and testers. It shapes the other four views. Static aspects: use case diagrams; dynamic aspects: interaction, state machine and activity diagrams.

2. Design view: the classes, interfaces and collaborations that form the vocabulary of the problem and its solution. It mainly supports the functional requirements. Static: class and object diagrams; dynamic: interaction, state machine and activity diagrams.

3. Process view: the threads and processes that give the system its concurrency and synchronization, modelled with active classes. It addresses performance, scalability and throughput, and uses the same kinds of diagrams as the design view, drawn as diagrams of its active classes.

4. Implementation view: the components and artifacts used to assemble and release the physical system. It addresses configuration management of releases built from fairly independent parts. Static: component diagrams; dynamic: interaction, state machine and activity diagrams.

5. Deployment view: the nodes that form the hardware topology on which the system runs. It addresses the distribution, delivery and installation of the physical parts. Static: deployment diagrams; dynamic: interaction, state machine and activity diagrams.

The UML diagrams therefore fall into two groups:

  • Structural (static): class, object, component, composite structure, package and deployment diagrams.
  • Behavioral (dynamic): use case, sequence, communication, timing, interaction overview, activity and state machine diagrams.

These are the thirteen diagram kinds of UML 2.0; UML 2.2 added a fourteenth, the profile diagram.

In conclusion, the use case view ties the other four together: each use case is realized in the design, process, implementation and deployment views, so the five views give one consistent picture of the system.

5 What is a class? Explain the UML notation for a class and for the relationships among classes, with a class diagram of a university. 10 marks
Model answer

A class is a description of a set of objects that share the same attributes, operations, relationships and semantics. It is drawn as a rectangle with three compartments:

1. Name: a simple name such as Course, or a qualified name with its package, such as Academics::Course. An abstract class has its name in italics.

2. Attributes: named properties, written as visibility name : type = default.

3. Operations: services that any object of the class can be asked to perform, written as visibility name(parameters) : return type.

Visibility is + public, - private, # protected and ~ package. An extra compartment may list responsibilities, the obligations of the class.

Course
--------------------------
- code : String
- title : String
- credits : Integer = 3
--------------------------
+ enrol(s : Student)
+ slotIn(t : Timetable)
# hasSeat() : Boolean

Relationships. The figure shows each kind in a small university model.

Class diagram of a university showing the UML relationshipsUniversity is joined to Department by composition, Department to Professor by aggregation, and Professor and Student point to Person by generalization. Professor teaches Course, Student enrolls in Course, Course points to «interface» Schedulable by realization and to Timetable by dependency.UniversityPersonDepartmentProfessorStudentCourse«interface»SchedulableTimetablecompositionaggregationgeneralizationgeneralizationteachesenrolls inrealizationdependency
Class diagram of a university showing the UML relationships
  • Dependency: a using relationship; a change in the supplier may affect the client. Course uses Timetable as the parameter of slotIn, so a dashed arrow runs from Course to Timetable.
  • Generalization: the child is a kind of the parent and inherits its features. Student and Professor are kinds of Person, each drawn with a solid line and a hollow triangle at Person.
  • Association: a structural link between objects, drawn as a solid line with an optional name and a multiplicity at each end. A Student enrolls in 1..* courses and a Course has * students; a Professor teaches * courses and each Course has 1 professor.
  • Aggregation: a whole-part association whose parts can exist apart from the whole, drawn with a hollow diamond at the whole. A Department has 1..* professors.
  • Composition: a strong aggregation in which each part belongs to only one whole at a time, and the whole creates and destroys it, drawn with a filled diamond at the whole. A University is composed of 1..* departments.
  • Realization: a class carries out the contract of an interface, drawn as a dashed line with a hollow triangle at the interface. Course realizes «interface» Schedulable, which declares slotIn.
Kind            Line    End mark
dependency      dashed  open arrowhead
generalization  solid   hollow triangle
association     solid   none or arrow
aggregation     solid   hollow diamond
composition     solid   filled diamond
realization     dashed  hollow triangle

In conclusion, the class box records what each abstraction knows and does, and the relationship notations connect the classes into one model.

6 Case study: for a control system that manages railway traffic, identify the main classes and draw a class diagram showing their relationships and the common mechanisms used. 10 marks
Model answer

A traffic management control system keeps trains moving safely over a rail network. In this small model, a central TrafficController plans a route for each train, tracks where every train is and commands the signals and switches beside the track.

1. Identify the classes from the vocabulary of the problem:

  • TrafficController: the control software; it plans routes, monitors trains and commands track devices.
  • Train: a train running on the network, hauled by one or more Locomotive objects.
  • Route: the ordered list of track sections a train is to follow.
  • TrackSection: a stretch of track with an id and a length.
  • TrackDevice: an abstract class for the equipment the controller commands.
  • Signal and Switch: kinds of TrackDevice; a Signal shows red, yellow or green, and a Switch is set to normal or reverse.

2. Give the key class its features. isClear checks that no section of a route is occupied before planRoute returns it.

TrafficController
------------------------------
- zone : String
------------------------------
+ planRoute(t : Train) : Route
+ command(d : TrackDevice)
- isClear(r : Route) : Boolean

3. Draw the relationships:

Class diagram of a railway traffic management control systemTrafficController monitors Train, plans Route and commands TrackDevice. Train follows Route, occupies TrackSection and aggregates Locomotive; Route aggregates TrackSection {ordered}; TrackSection is composed of TrackDevice {abstract}, and Signal and Switch point to it by generalization. A note on TrackSection says only one train per section.TrafficControllerTrainRouteLocomotiveTrackSectionOnly one trainper sectionTrackDevice{abstract}SignalSwitchmonitorsplanscommandsfollowsaggregationaggregation{ordered}occupiescompositiongeneralizationgeneralization
Class diagram of a railway traffic management control system
  • Associations (solid lines): the TrafficController monitors * trains, plans * routes and commands * track devices; each Train follows 1 Route; a Train occupies 1..* track sections, and a section is occupied by 0..1 train.
  • Aggregation (hollow diamond at the whole): a Train has 1..* locomotives, which can be moved to another train; a Route has 1..* track sections, and many routes share the same section.
  • Composition (filled diamond at TrackSection): a section has 0..* devices, and each TrackDevice belongs to exactly one section and is removed with it.
  • Generalization (hollow triangle at TrackDevice): Signal and Switch inherit from TrackDevice.

4. Apply the common mechanisms:

  • Specification: each class symbol stands for a full textual specification, such as the TrafficController box above.
  • Adornments: a multiplicity at every association end, and the property {abstract} (or an italic name) on TrackDevice, so it has no direct instances.
  • Constraint: {ordered} at the TrackSection end of the Route aggregation keeps the sections in travel order.
  • Note: a note attached to TrackSection records the safety rule, only one train per section.

In conclusion, the class diagram fixes the vocabulary of the traffic system; the same class names are reused later in its interaction and state machine diagrams.

Unit 3

Class and Object Diagrams and Advanced Structural Modeling

Syllabus: Class diagrams: terms, concepts and modeling techniques; Object diagrams: terms, concepts and modeling techniques; Advanced classes; Advanced relationships; Interfaces, types and roles; Packages; Case study: cryptanalysis (an AI application)

One-page revision summary

  • A class diagram shows classes, interfaces and collaborations with their dependency, generalization, association and realization relationships, and models the static design view.
  • Class diagrams are used to model the vocabulary of a system, simple collaborations and a logical database schema.
  • Forward engineering turns a class diagram into code and reverse engineering builds one from code; some model detail, such as constraints, has no direct place in code.
  • An object diagram is a snapshot: it shows objects, their attribute values and the links among them at one moment.
  • A link is an instance of an association, so every link in an object diagram must match an association in the class diagram.
  • Reverse engineering an object diagram from a running program, for example at a debugger breakpoint, is more useful than forward engineering one.
  • Classifiers include classes, interfaces, datatypes, signals, components, nodes, use cases and subsystems.
  • Static features are underlined, abstract classes and operations are written in italics, and a class marked {leaf} cannot be specialized.
  • A template class lists its formal parameters in a dashed box and must be bound, for example with «bind» <T -> Job>, before it has instances.
  • A set of subclasses can be marked {complete} or {incomplete} and {disjoint} or {overlapping}.
  • A qualifier is a small box at one end of an association; an association class is attached to its association by a dashed line.
  • An interface lists operations but no methods and cannot be instantiated; a class realizes it with a dashed line and a hollow triangle.
  • A «type» describes a set of objects and their operations without methods, and a role is the face an object shows in one context.
  • A package is drawn as a tabbed folder and owns its elements, so deleting the package deletes them; qualified names use ::, as in Cryptanalysis::Control.
  • «import» is a public import and «access» a private import of another package's public elements.
  • Packages are used to model groups of related elements and the architectural views of a system.
  • In the cryptanalysis case study every plain letter is replaced by one fixed cipher letter, and the system must recover the plain text.
  • The blackboard holds the sentence, its words and cipher letters and the assumptions; knowledge sources post assumptions and the controller picks which knowledge source acts next.
  • An assumption that leads to a contradiction is retracted, so the solver can back up and try another letter.
  • Useful knowledge sources include letter frequency (E is the most common English letter), small words (a one-letter word is usually A or I) and double letters.

Learn these by heart

  • Attribute: [visibility] name : type [multiplicity] = initial value {property}, for example - id : Integer {readOnly}.
  • Operation: [visibility] name (direction parameter : type) : return type {property}, with direction in, out or inout.
  • Visibility: + public, # protected, - private, ~ package.
  • Object name: objectName : ClassName, underlined; :ClassName names an anonymous object.
  • Generalization arrow: solid line, hollow triangle at the parent; realization: dashed line, hollow triangle at the interface; dependency: dashed arrow to the supplier.
  • Composition: filled diamond at the whole; aggregation: hollow diamond at the whole.
  • Ball (lollipop) = provided interface; socket = required interface.
  • Blackboard architecture = blackboard + knowledge sources + controller.

2-mark questions

1 What is a class diagram? List the elements it usually contains. 2 marks
Model answer

A class diagram shows a set of classes, interfaces and collaborations and the relationships among them. It usually contains classes, interfaces and collaborations; dependency, generalization, association and realization relationships; and notes, constraints and packages. It models the static design view of a system and is the most common diagram in object-oriented modeling.

2 What is an object diagram? How does it differ from a class diagram? 2 marks
Model answer

An object diagram shows a set of objects and the links among them at one moment, like a snapshot. A class diagram gives the classes and associations that hold in every possible state of the system, while an object diagram shows one particular state: concrete instances with underlined names, their attribute values, and links that are instances of the associations.

3 Name the four visibility levels of a UML class feature with their symbols. 2 marks
Model answer
  • public (+): any classifier that can see the class can use the feature.
  • protected (#): only the class and its descendants can use it.
  • private (-): only the class itself can use it.
  • package (~): only classifiers declared in the same package can use it.
4 Distinguish between aggregation and composition with an example of each. 2 marks
Model answer

Both are whole-part associations. Aggregation (hollow diamond at the whole) is a loose has-a relation: a Team has Players, and a player can exist alone or join another team. Composition (filled diamond) is strong ownership: each part belongs to at most one whole at a time, and deleting the whole deletes the parts it still holds, like the OrderLines of an Order.

5 What is the difference between a provided interface and a required interface? 2 marks
Model answer

A provided interface is one that a class or component realizes, offering its operations to others; it is drawn as a ball (lollipop) attached to that element. A required interface is one the element needs from others, drawn as a socket (half circle). A ball fitted into a socket shows one part supplying what the other needs.

6 Name the three parts of a blackboard architecture used for cryptanalysis and state the role of each. 2 marks
Model answer
  • Blackboard: holds the shared problem state: the cryptogram and the current assumptions about which plain letter each cipher letter stands for.
  • Knowledge sources: independent specialists, such as letter frequency or small words, that study the blackboard and post assumptions.
  • Controller: chooses which knowledge source acts next; an assumption that leads to a contradiction is retracted so that another can be tried.

10-mark questions

1 What is a class diagram? Explain its terms, contents and common modeling techniques, and draw the class diagram of the blackboard in a cryptanalysis system. 10 marks
Model answer

A class diagram shows a set of classes, interfaces and collaborations and the relationships among them. It is the most common UML diagram and models the static design view of a system: its vocabulary and structure rather than its behavior over time.

Terms and contents:

  • Things: classes, interfaces and collaborations.
  • Relationships: dependency, generalization, association (including aggregation and composition) and realization.
  • Notes and constraints, and packages that group elements.

Common modeling techniques:

1. Modeling the vocabulary of a system: find the abstractions that users and developers use to describe the problem, give each a set of responsibilities, and decide which lie inside the system boundary.

2. Modeling simple collaborations: draw a small society of classes that together give a behavior no single class gives, showing only the relationships that matter for it.

3. Modeling a logical database schema: mark the classes whose objects must persist and give them attributes and associations with multiplicities, so the diagram becomes the blueprint of the tables.

4. Forward and reverse engineering: forward engineering turns the diagram into code in a language such as Java; reverse engineering builds the diagram from existing code. UML can say more than most languages, so details such as constraints may be lost going forward.

Example: a cryptogram is a sentence in which each plain letter has been replaced by one fixed cipher letter. A blackboard design solves it: knowledge sources post assumptions about cipher letters on a shared blackboard, and a controller decides which knowledge source acts next.

Class diagram of the cryptanalysis blackboardController monitors Blackboard and activates 1..* KnowledgeSource, which posts 0..* Assumption and uses Blackboard; Blackboard has compositions to 1 Sentence and 0..* Assumption, Sentence to 1..* Word and Word to 1..* CipherLetter. Sentence, Word and CipherLetter generalize to the abstract BlackboardObject, and LetterFrequency and SmallWords to the abstract KnowledgeSource.ControllerBlackboardKnowledgeSource{abstract}AssumptionLetterFrequencySmallWordsBlackboardObject{abstract}SentenceWordCipherLettermonitorsactivates 1..*«use»dependencycomposition0..*posts 0..*generalizationgeneralizationcomposition 1composition1..*composition1..*generalizationgeneralizationgeneralization
Class diagram of the cryptanalysis blackboard
Blackboard
  + post(a : Assumption)
  + retract(a : Assumption)
  + isSolved() : Boolean
Sentence
  - text : String
Word
  - text : String
Assumption
  - cipher : Char
  - plain : Char
KnowledgeSource {abstract}
  + evaluate(b : Blackboard)

Reading the diagram:

  • Composition: each arrow runs from the whole to the part; on paper a filled diamond is drawn at the whole. Blackboard owns 1 Sentence and 0..* Assumption; a Sentence owns 1..* Word and a Word owns 1..* CipherLetter, both {ordered}.
  • Generalization: each arrow points from the child to the parent, drawn with a hollow triangle. Sentence, Word and CipherLetter specialize the abstract BlackboardObject; LetterFrequency and SmallWords specialize the abstract KnowledgeSource.
  • Associations: the Controller monitors the Blackboard and activates 1..* KnowledgeSource; each KnowledgeSource posts 0..* Assumption.
  • Dependency, a dashed arrow: KnowledgeSource uses Blackboard, the parameter type of evaluate().

The diagram fixes the vocabulary of the solver: every object that appears at run time, such as a particular assumption, is an instance of one of these classes.

2 What is an object diagram? Explain its terms, concepts and modeling techniques, and draw an object diagram showing the blackboard of a cryptanalysis system while it solves a cryptogram. 10 marks
Model answer

An object diagram shows a set of objects and the links among them at one moment. It is a snapshot of instances of the classes in a class diagram, showing the static design view through concrete examples.

Terms and concepts:

  • Object: a concrete instance of a class, drawn as a rectangle whose name is underlined. It may be named with its class (w1 : Word), anonymous (:Controller), or an orphan whose class is not shown (w1).
  • Attribute values: a second compartment lists name = value pairs; together they give the object's state at that moment.
  • Link: an instance of an association, drawn as a plain line between two objects. A link may exist only where the class diagram has an association between the two classes or their parents.
  • Contents: objects and links, plus notes and constraints where needed.

Modeling object structures (the main technique):

1. Pick the mechanism to study and the moment to freeze.

2. Find the classes and associations that take part in it.

3. Draw each participating object, naming those that must be referred to.

4. Show only the attribute values needed to understand that moment.

5. Draw the links among the objects.

Forward engineering an object diagram into code is of limited use, because objects are created and destroyed while the program runs. Reverse engineering is useful: a debugger can capture the objects and links at a breakpoint and show them as an object diagram.

Example: the cryptogram K WQQ MBQ MZQQ is on the blackboard of a cryptanalysis system. LetterFrequency counts the 11 cipher letters and finds Q 5 times, far more than any other, so it posts a1: Q stands for E, the most common English letter. SmallWords sees the one-letter word K, which is almost always A or I, and posts a2: K stands for I; if that leads to a contradiction, a2 is retracted and A is tried. The sentence now reads I _EE __E __EE.

Object diagram: the blackboard after two assumptions:Controller is linked to bb : Blackboard by monitors and activates lf : LetterFrequency and sw : SmallWords. bb is linked to s : Sentence, a1 : Assumption and a2 : Assumption, s is linked to w1, w2, w3 and w4 of class Word, and lf posts a1 while sw posts a2.:Controllerlf :LetterFrequencybb : Blackboardsw : SmallWordsa1 : Assumptions : Sentencea2 : Assumptionw1 : Wordw2 : Wordw3 : Wordw4 : Wordactivatesmonitorsactivatespostsposts
Object diagram: the blackboard after two assumptions
Object           Attribute values
s : Sentence     text = "K WQQ MBQ MZQQ"
w1 : Word        text = "K"
w2 : Word        text = "WQQ"
w3 : Word        text = "MBQ"
w4 : Word        text = "MZQQ"
a1 : Assumption  cipher = 'Q', plain = 'E'
a2 : Assumption  cipher = 'K', plain = 'I'

Each link instantiates an association: bb with s (Blackboard owns Sentence), s with w1 to w4 (Sentence owns Word), bb with a1 and a2 (Blackboard owns Assumption), lf with a1 and sw with a2 (posts, inherited from their common abstract parent class), and the Controller's monitors and activates links. Later assumptions complete the solution as I SEE THE TREE.

3 Explain the advanced features of classes in UML: classifiers, visibility, scope, abstract, leaf and polymorphic elements, attributes, operations and template classes. 10 marks
Model answer

Beyond a name, attributes and operations, UML lets a designer state who may use each feature, whether it belongs to each object or to the class, how the class takes part in inheritance, and how it can be parameterized.

1. Classifiers: a classifier is a model element that describes structural features (attributes) and behavioral features (operations). Classifiers include classes, interfaces, datatypes, signals, components, nodes, use cases and subsystems.

2. Visibility: + public (any classifier that can see the class), # protected (the class and its descendants), - private (the class only) and ~ package (the same package).

3. Scope: a feature with instance scope has a separate value for each object; a static feature has one value shared by all objects of the class and is underlined.

4. Abstract, leaf and polymorphic elements: an abstract class has no direct instances and its name is written in italics (or marked {abstract}); an abstract operation has no method in that class. A class marked {leaf} cannot have children. A polymorphic operation can be given a different method in each descendant, and the class of the actual object decides which method runs; an operation marked {leaf} cannot be overridden.

5. Attributes: [visibility] name [: type] [multiplicity] [= initial value] [{property}], where the parts in brackets are optional; for example # tags : String [0..*] and - id : Integer {readOnly}.

6. Operations: [visibility] name ([direction] parameter : type, ...) [: return type] [{property}]. A direction is in, out or inout; properties include query (no side effects) and the concurrency values sequential, guarded and concurrent.

Shape {abstract}
---------------------------------
# origin : Point = (0, 0)
- id : Integer {readOnly}
+ count : Integer = 0    (static)
---------------------------------
+ draw()               (abstract)
+ area() : Real {query}
+ move(in dx : Real, in dy : Real)

7. Template classes: a template is a class with formal parameters, written in a dashed box at its upper-right corner. It cannot have instances until it is bound to actual arguments.

Abstract, leaf and template classesCircle and Polygon have generalization arrows to Shape {abstract}, and Square {leaf} has a generalization arrow to Polygon. JobQueue has a «bind» dependency arrow, binding T to Job, to the template Queue with parameter T.Abstract and leaf classesTemplate bindingShape {abstract}CirclePolygonSquare {leaf}Queue(template, T)JobQueuegeneralizationgeneralizationgeneralization«bind»T to Job
Abstract, leaf and template classes

In the figure, Shape is abstract and draw() is abstract and polymorphic: Circle and Polygon each give their own draw(). Square is a leaf class, so no class may specialize it. Generalization arrows point from child to parent, with a hollow triangle on paper. Queue is a template with the parameter T; JobQueue binds T to Job through a «bind» dependency, a dashed arrow from JobQueue to Queue. An anonymous bound class is written Queue<T -> Job>.

On paper, count is underlined and the names Shape and draw() are in italics. A class stereotyped «utility» has only static attributes and operations. These features make a class precise enough for code generation.

4 Explain the advanced relationships in UML: dependency stereotypes, generalization constraints, association adornments and realization, with an example class diagram. 10 marks
Model answer

The four basic relationships (dependency, generalization, association and realization) need extra detail to model real systems precisely. UML adds stereotypes to dependencies, constraints to generalizations and adornments to associations.

1. Dependency: a using relationship drawn as a dashed arrow from the client to the supplier. Stereotypes refine it:

  • «use»: the client needs the supplier, for example as a parameter type.
  • «bind»: binds a template to actual arguments.
  • «derive»: the client can be computed from the supplier.
  • «instantiate»: the client creates instances of the supplier.
  • «refine» and «trace»: the same concept at different levels of abstraction or in different models.
  • «import» and «access» between packages, and «include» and «extend» between use cases.

2. Generalization: a solid line with a hollow triangle at the parent. A class may have more than one parent (multiple inheritance). A set of children can carry constraints: {complete} means every instance of the parent is an instance of some listed child and {incomplete} allows other children; {disjoint} means an object belongs to at most one child and {overlapping} allows several.

3. Association adornments:

  • Navigation: an open arrowhead shows the direction in which the association can be traversed.
  • Qualification: a qualifier, a small box at one end holding an attribute, selects the objects at the other end.
  • Composition: a filled diamond at the whole; the parts live and die with it.
  • Association class: a class attached to an association by a dashed line, holding properties of each link.
  • Constraints on an end, such as {ordered}.

4. Realization: a dashed line with a hollow triangle from the element that carries out a contract to the element that specifies it, such as a class realizing an interface.

Example: a bank.

Advanced relationships in a bank modelBank is linked to Account by the qualifier [accountNo] with multiplicity 0..1, Customer owns Account, Account has an ordered composition of Transaction, and StatementPrinter has a «use» dependency on Account. SavingsAccount and CurrentAccount have generalization arrows to Account under {disjoint, complete}, and SavingsAccount has a realization arrow to «interface» InterestBearing.StatementPrinterBankCustomer«interface»InterestBearingAccountTransactionSavingsAccount{disjoint,complete}CurrentAccount«use»dependency[accountNo]0..1ownscomposition{ordered}generalizationgeneralizationrealization
Advanced relationships in a bank model
Customer 1..* ---- owns ---- 1..* Account
                    :
                 Holding
                 - since : Date
  • Bank with the qualifier [accountNo], drawn on paper as a small box at the Bank end, identifies 0..1 Account; without the qualifier a bank has many accounts. The arrowhead shows navigation from Bank to Account.
  • Account owns 0..* Transaction by composition, kept {ordered} by time; on paper the filled diamond sits at the Account end.
  • SavingsAccount and CurrentAccount specialize Account under {disjoint, complete}: every account is exactly one of the two.
  • SavingsAccount realizes the interface InterestBearing.
  • StatementPrinter has a «use» dependency on Account, the parameter type of its print operation.
  • Holding is an association class on owns (the dotted line stands for the dashed line), recording since when a customer has held an account.

These adornments let one class diagram state rules that would otherwise live only in comments or code.

5 Explain interfaces, types and roles in UML with their notation, and describe how interfaces are used to model the seams of a system. 10 marks
Model answer

Interfaces, types and roles separate what an element promises from how it keeps that promise. They are the main tools for modeling the seams between the parts of a system.

1. Interface: an interface is a named collection of operations that specifies a service of a class or component. It has no implementation (no methods) and cannot be instantiated; a class or component that realizes it supplies the methods. Like a class, an interface can take part in generalization, association and dependency, and it is the target of realization.

2. Notation:

  • Expanded form: a rectangle with the keyword «interface» above the name and the operations listed below.
  • Realization: a dashed line with a hollow triangle from the realizing class to the interface.
  • Usage: a dashed arrow (dependency) from a client to the interface it needs.
  • Iconic form: a provided interface is a ball (lollipop) on the realizing class, and a required interface is a socket on the client; a ball fitted into a socket shows the two sides connected.

3. Type: «type» is a class stereotype that names a set of objects and the operations defined on them, without saying how those operations are carried out (no methods). It is useful in analysis, before any implementation is chosen.

4. Role: a role is the face an entity shows in one particular context. One class may play several roles: a Person is an employee to a Company and a customer to a Bank. A role appears as a role name at an association end, and an interface can define which operations that role exposes. An object may gain or lose roles during its life.

Roles of a Person defined by interfacesPerson has realization arrows to «interface» IEmployee and «interface» ICustomer. Company has an association arrow with role employee 1..* to IEmployee, and Bank an association arrow with role customer 0..* to ICustomer.«interface»IEmployee«interface»ICustomerCompanyPersonBankrealizationrealizationemployee 1..*customer 0..*
Roles of a Person defined by interfaces
«interface» IEmployee
---------------------------
+ getId() : Integer
+ getSalary() : Real

«interface» ICustomer
---------------------------
+ getAccountNo() : String

Person realizes both IEmployee and ICustomer. Company has an association whose end, named employee with multiplicity 1..*, is typed by IEmployee, so the company sees a Person only through getId() and getSalary(). Bank's end, customer with multiplicity 0..*, is typed by ICustomer. On paper the same facts can be drawn as two balls on Person, with a socket on Company and another on Bank.

5. Modeling the seams of a system:

  • Find the boundaries where parts may change or be replaced independently.
  • Collect the operations that cross each boundary into an interface.
  • Let one side realize the interface and the other depend on it.
  • Check each interface against scenarios, then keep it stable so both sides can change separately.

A client that depends only on an interface keeps working when the class behind it is replaced, which is what makes large systems easier to change.

6 What is a package in UML? Explain names, owned elements, visibility and importing, and the common modeling techniques for packages, with a package diagram. 10 marks
Model answer

A package is a general-purpose mechanism for organizing model elements into groups. It is drawn as a tabbed folder with its name on the tab or in the body. A package may hold classes, interfaces, components, nodes, collaborations, use cases, diagrams and other packages; it is purely a modeling construct and has no instances at run time.

Terms and concepts:

1. Names: a package has a simple name such as Control, or a qualified name that adds the enclosing package, such as Cryptanalysis::Control. Elements are named the same way, for example BlackboardModel::Assumption.

2. Owned elements: a package owns its elements, each element is owned by exactly one package, and two elements of the same kind cannot share a name within a package. Deleting a package deletes everything it owns.

3. Nesting: packages can contain packages; shallow nesting keeps qualified names readable.

4. Visibility: each owned element is marked + public, usable by packages that import this one, or - private, hidden outside. The public elements form the package's exports.

5. Importing: a dependency stereotyped «import» lets the client package use the supplier's public elements by their simple names, and the imported names become public members of the client. «access» does the same privately: the names are usable only inside the client. Both are dashed arrows from the client to the supplier.

Example: the cryptanalysis system organized as four packages nested in the package Cryptanalysis. In the figure each box stands for a tabbed folder and the outer region is Cryptanalysis.

Package diagram of the cryptanalysis systemInside the package Cryptanalysis, UserInterface imports Control, Control imports KnowledgeSources and accesses BlackboardModel, and KnowledgeSources accesses BlackboardModel. Each arrow is a dashed dependency from the client package to the supplier package.CryptanalysisUserInterfaceControlKnowledgeSourcesBlackboardModel«import»«import»«access»«access»
Package diagram of the cryptanalysis system
BlackboardModel
  + Blackboard
  + BlackboardObject {abstract}
  + Sentence
  + Word
  - CipherLetter
  + Assumption
KnowledgeSources
  + KnowledgeSource {abstract}
  + LetterFrequency
  + SmallWords
Control
  + Controller
UserInterface
  + SolverWindow
  • KnowledgeSources accesses BlackboardModel, so LetterFrequency can name Blackboard, Sentence, Word and Assumption directly. CipherLetter is private and stays hidden; knowledge sources read letters through Word.
  • Control imports KnowledgeSources and accesses BlackboardModel, so Controller can name the knowledge source classes and the public blackboard classes. Because BlackboardModel is reached only through «access», its names do not become public members of KnowledgeSources or Control.
  • UserInterface imports Control, so SolverWindow can start the Controller.

Common modeling techniques:

  • Modeling groups of elements: put elements that are close in meaning and tend to change together into one package, keep dependencies between packages few and in one direction, and make public only what other packages need.
  • Modeling architectural views: make one top-level package per view, for example the design, implementation and deployment views, so each stakeholder can study a view on its own.

A diagram that shows packages and the dependencies among them, like the figure, is called a package diagram.

Unit 4

Basic Behavioral Modeling

Syllabus: Interactions; Interaction diagrams; Use cases; Use case diagrams; Activity diagrams; Case study: web application for a vacation tracking system

One-page revision summary

  • An interaction is a set of messages exchanged among objects in a context to achieve a purpose, and it models the dynamic aspect of a system.
  • An interaction can be set in the context of a system or subsystem, of one operation, or of a single class.
  • A link is a run-time connection between two objects, usually an instance of an association, and messages pass along links.
  • The kinds of message are call, return, send (asynchronous), create and destroy.
  • UML 2 has four interaction diagrams: sequence, communication, timing and interaction overview diagrams.
  • A sequence diagram shows lifelines, messages in time order, execution specifications and combined fragments such as alt, opt and loop.
  • A communication diagram shows objects joined by links, with decimal sequence numbers on the messages.
  • A use case describes the steps a system performs to give an actor a result of value; an actor is a role outside the system.
  • A flow of events gives the main flow, alternate flows, preconditions and postconditions; a scenario is one path through a use case.
  • A use case diagram shows actors, use cases inside the system boundary, and association, include, extend and generalization relationships.
  • Use case diagrams model the context of a system (who uses it) and its requirements (what it must do).
  • An activity diagram shows the flow of control from action to action, with decisions, merges, forks, joins and swimlanes.
  • An object node in an activity diagram shows an object passing from one action to another along an object flow.
  • The vacation tracking system has the actors Employee, Manager, HR Clerk and Email System, with Manager a child of Employee.
  • In the vacation tracking system, Request Vacation, Cancel Request and Approve Request include Send Notification, and Record Rejection Reason extends Approve Request.
  • A swimlane activity diagram for a vacation request uses Employee, VTS and Manager lanes, a balance decision, a fork and join, and a merge after approval.

Learn these by heart

  • «include»: dashed arrow from the base use case to the included one; the included steps always run.
  • «extend»: dashed arrow from the extending use case to the base; the extra steps run only when the condition at the extension point holds.
  • Generalization: solid line with a hollow triangle pointing at the parent actor or use case.
  • Synchronous call: filled arrowhead; asynchronous send: open arrowhead; return: dashed arrow.
  • Nested sequence numbers: 1, 1.1, 1.2, 2; message 1.1 is sent while message 1 is being handled.
  • Fork splits one flow into concurrent flows; join waits for all of them; merge rejoins alternative paths without waiting.

2-mark questions

1 Define an interaction and a message in UML. 2 marks
Model answer

An interaction is a behaviour in which a set of objects, within some context, exchange messages to achieve a purpose. A message is one communication from a sender object to a receiver object, such as calling an operation or sending a signal, and it is expected to make the receiver carry out some activity.

2 How does a sequence diagram differ from a communication diagram? 2 marks
Model answer

Both are interaction diagrams. A sequence diagram orders the messages by time: lifelines run down the page and messages are read from top to bottom. A communication diagram shows the objects and the links between them, and decimal sequence numbers such as 1, 1.1 and 2 on the messages give their order.

3 What is a use case, and what is an actor? 2 marks
Model answer

A use case describes the steps, with their variations, that a system performs to give an actor a result of value; it is drawn as an ellipse. An actor is a role that a person, device or external system plays when it interacts with the system; it is drawn as a stick figure outside the system boundary.

4 Distinguish the «include» and «extend» relationships between use cases. 2 marks
Model answer

«include»: the base use case always performs the included one, so shared steps are written once; its dashed arrow points from the base to the included use case. «extend»: the extending use case adds optional steps to the base only when a condition holds at an extension point; its dashed arrow points from the extending use case to the base.

5 What are fork and join nodes in an activity diagram? 2 marks
Model answer

A fork node splits one incoming flow into several flows that run concurrently. A join node waits until all of its incoming concurrent flows have arrived and then continues as a single flow. Both are drawn as a short thick bar, and each fork is normally matched by a later join.

6 State the purpose of the vacation tracking system and name its actors. 2 marks
Model answer

The vacation tracking system is a web application in which employees request and cancel vacation and view their leave balance, managers approve or reject requests, and HR clerks adjust balances. Its actors are Employee, Manager (a specialised Employee), HR Clerk and Email System, an external system that delivers the notifications.

10-mark questions

1 Explain interactions in UML. Describe the context of an interaction, objects and roles, links, messages and sequencing, and list the kinds of messages with an example. 10 marks
Model answer

An interaction models the dynamic side of a system. Class and object diagrams show what exists; an interaction shows how a group of objects cooperate at run time, by exchanging messages, to achieve one purpose such as withdrawing cash from an ATM.

1. Context. Every interaction happens inside some context. It may describe how the objects of a system or subsystem collaborate, how the objects that carry out one operation work together, or how the attributes and parts of a single class cooperate.

2. Objects and roles. The participants are objects that play roles. A participant is written name:Class, for example atm:ATM. The name may be dropped, as in :Account, when any instance of the class can play that role.

3. Links. A link is a run-time connection between two objects, usually an instance of an association between their classes. A message passes from one object to another along a link, so the links form the paths of the interaction.

4. Messages. A message specifies one communication from a sender to a receiver, and the receiver is expected to carry out some activity in response. The kinds of message are:

  • call: invokes an operation; a synchronous call waits for the reply and is drawn with a filled arrowhead
  • return: hands a value back to the caller, drawn as a dashed arrow
  • send: delivers a signal asynchronously, so the sender does not wait; drawn with an open arrowhead
  • create: brings a new object into existence
  • destroy: ends an object's life, shown by an X at the end of its lifeline

5. Sequencing. The order in which messages are sent is the sequence. In nested (procedural) numbering, a message sent while message 1 is still being handled is numbered 1.1, the next 1.2, and so on; in flat numbering the messages are simply 1, 2, 3.

The cash withdrawal below uses every kind, in time order and with flat numbering. Here acct is an Account, r a Receipt and log an AuditLog; -> is a call, --> a return and ->> an asynchronous send.

1  atm -> acct : debit(500)     call
   acct --> atm : true          return
2  atm -> r : «create»          create
3  atm -> r : print()           call
4  atm -> r : «destroy»         destroy
5  atm ->> log : record(txn)    send

In conclusion, an interaction captures behaviour as messages passed between linked objects in a set order. UML draws it with interaction diagrams: the sequence diagram stresses the time order and the communication diagram stresses the links between the objects.

2 What is a use case? Explain actors, flows of events, scenarios and the include, extend and generalization relationships, with a use case diagram for a library system. 10 marks
Model answer

A use case captures one goal that an actor achieves with a system: it describes the steps, with their variations, that the system performs to give the actor a result of value. Use cases state what the system must do, not how it does it, so they are the main tool for capturing requirements.

1. Actors. An actor is a role played by a person, a device or another system that interacts with the system. It lies outside the system boundary and is drawn as a stick figure. In a library system, Member searches the catalog and reserves books, and Librarian issues and returns books.

2. Flow of events. Each use case is described in text by its flow of events: how it starts, the main flow, alternate flows for errors and options, and how it ends, with any preconditions and postconditions. For example:

Use case: Issue Book   Actor: Librarian
Main flow:
 1. Librarian enters member and book ids.
 2. Include Verify Member.
 3. System records a loan due in 14 days.
 4. System marks the book as issued.
Alternate flow:
 2a. Member is blocked: the loan is
     refused and the use case ends.

3. Scenarios. A scenario is one particular path through a use case, an instance of it. Issuing a book to an active member follows the main flow; trying to issue one to a blocked member follows flow 2a. A use case therefore stands for a set of related scenarios.

4. Relationships among use cases.

  • «include»: the base use case always performs the included one, so shared steps are written once. Issue Book and Reserve Book both include Verify Member. It is drawn as a dashed arrow from the base to the included use case.
  • «extend»: the extending use case adds optional steps to the base at an extension point, only when its condition holds. Pay Fine extends Return Book when the book is returned late. The dashed arrow points from the extending use case to the base.
  • Generalization: a child use case inherits the parent's behaviour and may add to it. Search by Title is a kind of Search Catalog. It is drawn as a solid line with a hollow triangle at the parent.

In the use case diagram below, use cases are ellipses inside the system boundary rectangle, and actors are joined to their use cases by plain association lines. In the figure actors are drawn as boxes and every relationship as a solid arrow named by its label; on paper actors are stick figures, «include» and «extend» are dashed arrows, and generalization ends in a hollow triangle at the parent.

Use case diagram of a library systemMember is associated with Search Catalog and Reserve Book, and Librarian with Issue Book and Return Book, inside the Library System boundary. Search by Title generalizes to Search Catalog, Reserve Book and Issue Book include Verify Member, and Pay Fine extends Return Book.Library SystemMemberSearch CatalogSearch by TitleReserve BookVerify MemberIssue BookLibrarianReturn BookPay Finegeneralization«include»«include»«extend»
Use case diagram of a library system

In short, use cases with their flows of events and scenarios capture what the system must do for each actor, and the use case diagram gives a one-page picture of those requirements.

3 Explain sequence diagrams and communication diagrams. Model the interaction that issues a book in a library in both forms, and compare the two. 10 marks
Model answer

Interaction diagrams show an interaction: a set of objects and the messages they exchange. UML 2 defines four of them (sequence, communication, timing and interaction overview diagrams); the sequence and communication diagrams are the two studied here.

1. Sequence diagram. It stresses the time order of the messages.

  • Each participant is a lifeline: a box holding name:Class with a dashed line running down the page. Time flows downward.
  • Messages are horizontal arrows between lifelines, read from top to bottom. A synchronous call has a filled arrowhead, an asynchronous message an open arrowhead, and a return is a dashed arrow.
  • A thin rectangle on a lifeline is an execution specification (focus of control): the period in which the object is performing an action.
  • A created object's lifeline starts lower down, where the create message arrives; a destroyed object's lifeline ends with an X.
  • Combined fragments such as alt (choice), opt (option) and loop (repetition) frame parts of the diagram.

2. Communication diagram. It stresses the structural organisation of the objects that exchange messages.

  • Objects are rectangles placed anywhere on the page and joined by links, drawn as plain lines.
  • Each message is a small arrow beside a link, with a sequence number. Decimal numbers show nesting: 1.1 and 1.2 are sent while message 1 is being handled.

Example: when a Librarian issues a book, the participants are l:Librarian, c:IssueController, m:Member, b:Book and the new loan n:Loan. The sequence diagram, as a message list in time order:

1    l -> c : issue(mId, bId)
1.1  c -> m : isActive()
     m --> c : true
1.2  c -> b : isAvailable()
     b --> c : true
1.3  c -> n : «create»
1.4  c -> b : setIssued()

On paper l, c, m and b are lifelines across the top, n's lifeline begins at message 1.3, and c shows one execution specification from message 1 to the end of 1.4. The same interaction as a communication diagram. In the figure each arrow is one message; on paper each pair of objects is joined by a single plain link, so the link from c to b carries both 1.2 and 1.4, each with a small arrow beside its label:

Communication diagram for issuing a bookl : Librarian sends 1: issue(mId, bId) to c : IssueController. c sends 1.1: isActive() to m : Member, 1.2: isAvailable() and 1.4: setIssued() to b : Book, and 1.3: «create» to n : Loan.l : Librarianc :IssueControllerm : Memberb : Bookn : Loan1: issue(mId,bId)1.1:isActive()1.2:isAvailable()1.3: «create»1.4:setIssued()
Communication diagram for issuing a book

3. Comparison.

  • The sequence diagram shows time order directly, together with lifelines, execution specifications and fragments; the communication diagram shows which objects are linked and gets the order only from the numbers.
  • Apart from the return arrows and fragments, which the communication diagram leaves out, both carry the same messages in the same order, so a tool can convert one into the other.

In conclusion, a sequence diagram suits a design in which the timing of messages matters, and a communication diagram suits one in which the links among the objects matter.

4 What is an activity diagram? Explain its elements, including decisions, forks, joins and swimlanes, with an activity diagram for processing an online order. 10 marks
Model answer

An activity diagram shows the flow of control from one action to the next. It works like a flowchart extended with concurrency and responsibility, and it models the dynamic side of a system: the steps of a use case, a business process or the body of an operation.

The elements of an activity diagram are:

  • Initial and final nodes: a filled circle marks where the flow starts; an activity final node, a circle with a dot inside (bull's eye), ends the whole activity. An activity may have more than one final node.
  • Actions: one step of work, drawn as a rounded rectangle, such as Pack goods. An atomic step is also called an action state, and a step that expands into a further activity an activity state.
  • Control flows: arrows between nodes; when an action finishes, control moves along its outgoing arrow.
  • Decision and merge: a decision is a diamond with one incoming flow and several outgoing flows, each with a guard in square brackets such as [payment ok]; the guards should cover every case without overlapping. A merge is a diamond that brings alternative paths back into one flow.
  • Fork and join: a fork is a thick bar that splits one flow into concurrent flows; a join is a thick bar that waits for all of its incoming flows before it continues.
  • Swimlanes (activity partitions): lanes, usually vertical columns, that divide the diagram, one for each person, department or object responsible for the actions placed in it.
  • Object flow: an object node, drawn as a rectangle, shows an object such as an invoice passing from one action to another.

Example: processing an online order, with swimlanes for Sales, Warehouse and Accounts. In the figure the decision is drawn as a circle and the fork and join as boxes; on paper they are a diamond and two thick bars.

Activity diagram for processing an online orderIn the Sales lane the initial node leads to Receive order and a decision: [payment failed] leads to Reject order and a final node, and [payment ok] leads to a fork. The fork starts Pack goods in the Warehouse lane and Prepare invoice in the Accounts lane; both meet at a join, followed by Ship order and a final node.SalesWarehouseAccountsInitial nodeReceive orderDecisionReject orderFinal nodeForkPack goodsPrepare invoiceJoinShip orderFinal node[paymentfailed][payment ok]
Activity diagram for processing an online order

1. The flow starts at the initial node in the Sales lane, and Sales performs Receive order.

2. A decision tests the payment. On [payment failed], Sales performs Reject order and that path reaches a final node.

3. On [payment ok], a fork starts two concurrent flows: the Warehouse performs Pack goods while Accounts performs Prepare invoice.

4. The join waits until both actions are done. The Warehouse then performs Ship order, and the activity reaches its final node.

No merge node is needed here, because each branch of the decision ends in its own final node.

In conclusion, an activity diagram shows the order of the actions, the choices, the work done in parallel and who is responsible for each step.

5 Case study: identify the actors and use cases of a web-based vacation tracking system, draw its use case diagram and write the flow of events for the Request Vacation use case. 10 marks
Model answer

The vacation tracking system (VTS) is a web application in which employees request time off, managers approve or reject the requests, and HR staff keep leave balances correct. It sends its notifications through an external email system. Use case modelling starts by finding who uses the system and what each user wants from it.

1. Actors.

  • Employee: requests vacation, cancels a request and views the leave balance.
  • Manager: approves or rejects the requests of the team. A manager is also an employee, so Manager is a child of Employee (actor generalization, drawn as a solid line with a hollow triangle at Employee) and inherits all of Employee's use cases.
  • HR Clerk: adjusts an employee's balance, for example to correct an error.
  • Email System: an external system, a secondary actor that delivers the notifications.

2. Use cases and relationships.

  • Request Vacation, Cancel Request and View Balance belong to Employee, Approve Request to Manager, and Adjust Balance to HR Clerk; each actor is joined to its use cases by a plain association line.
  • Send Notification is shared, so Request Vacation, Cancel Request and Approve Request each «include» it (dashed arrows from each base use case to Send Notification). It is the only use case associated with Email System.
  • Record Rejection Reason extends Approve Request («extend») at the extension point rejection, under the condition [request rejected] (a dashed arrow from Record Rejection Reason to Approve Request).

In the figure actors are drawn as boxes and every relationship as a solid arrow named by its label; on paper actors are stick figures, «include» and «extend» are dashed arrows, and generalization ends in a hollow triangle at Employee.

Use case diagram of the vacation tracking systemEmployee is associated with Request Vacation, Cancel Request and View Balance; Manager, a child of Employee, with Approve Request; HR Clerk with Adjust Balance; and Email System with Send Notification. Request Vacation, Cancel Request and Approve Request include Send Notification, and Record Rejection Reason extends Approve Request.Vacation Tracking SystemEmployeeRequest VacationCancel RequestSendNotificationEmail SystemView BalanceManagerApprove RequestRecordRejection ReasonHR ClerkAdjust Balancegeneralization«include»«include»«include»«extend»
Use case diagram of the vacation tracking system

3. Flow of events for Request Vacation:

Actor: Employee
Precondition: employee is logged in.
Main flow:
 1. Employee opens the request form.
 2. System shows the leave balance.
 3. Employee enters start and end dates.
 4. System checks days <= balance.
 5. System saves the request as pending
    and emails the manager (include
    Send Notification).
Alternate flow:
 4a. Days > balance: system shows an
     error and the use case ends.
Postcondition: a pending request
waits for the manager.

The main flow is the scenario in which the dates fit the balance; flow 4a is the scenario in which they do not. Each scenario is one path through the use case.

In conclusion, the use case diagram fixes the scope of the VTS: four actors, seven use cases inside the system boundary, and include, extend and generalization relationships that keep the model free of repetition.

6 Case study: draw and explain an activity diagram with swimlanes for submitting and approving a vacation request in a web-based vacation tracking system. 10 marks
Model answer

An activity diagram with swimlanes shows not only the order of the steps in a workflow but also who performs each step. Submitting and approving a vacation request in the vacation tracking system (VTS) needs three swimlanes: Employee, VTS and Manager.

On paper the actions are rounded rectangles, the initial node is a filled circle, the final nodes are bull's eyes, the decision and merge nodes are diamonds with guards in square brackets on their outgoing flows, and the fork and join are thick bars. In the figure the decision and merge nodes are drawn as circles and the fork and join as boxes.

Activity diagram with swimlanes for a vacation requestThe Employee lane has the initial node and Submit request; in the VTS lane a decision leads on [balance too low] to Show error and a final node, and on [balance enough] to a fork into Save as pending and Email manager, which meet at a join. In the Manager lane Review request and a decision lead on [approve] to Deduct balance and on [reject] to Record rejection reason; a merge then leads to Email employee and the final node.EmployeeVTSManagerInitial nodeSubmit requestDecisionShow errorFinal nodeForkSave as pendingEmail managerJoinReview requestDecisionDeduct balanceRecordrejection reasonMergeEmail employeeFinal node[balancetoo low][balanceenough][approve][reject]
Activity diagram with swimlanes for a vacation request

1. The flow starts at the initial node in the Employee lane. The employee performs Submit request, giving the start and end dates.

2. Control passes to the VTS lane, where a decision compares the requested days with the leave balance. On [balance too low] the system performs Show error and that path reaches a final node; the employee must submit a new request.

3. On [balance enough], meaning the days do not exceed the balance, a fork starts two concurrent flows: Save as pending stores the request, and Email manager sends a notification to the manager. The join waits until both are complete.

4. Control passes to the Manager lane. The manager performs Review request, and a second decision follows. On [approve] the system performs Deduct balance, reducing the employee's remaining leave. On [reject] the manager performs Record rejection reason.

5. A merge in the VTS lane brings the two paths together, since exactly one of them runs. The system then performs Email employee to report the outcome, and the flow reaches the final node.

Points to note:

  • Each action lies in the lane of the person or system that performs it, so the diagram shows responsibility as well as order.
  • The guards of each decision cover every case and never overlap: balance enough or balance too low; approve or reject.
  • A merge, not a join, follows the approval decision, because only one branch runs; a join there would wait for ever.
  • Email manager and Email employee are the notification steps of the use case model, and Record rejection reason is the optional extension of approval in that model.

In conclusion, the activity diagram ties the VTS use cases into one workflow and shows where the work moves between the employee, the system and the manager.

Unit 5

Advanced Behavioral Modeling and Architectural Modeling

Syllabus: Events and signals; State machines; Processes and threads; Time and space; State chart diagrams; Components; Deployment; Component diagrams; Deployment diagrams; Case study: weather forecasting

One-page revision summary

  • An event is a noteworthy happening at a definite time and place, and UML models signal, call, time and change events.
  • A signal is sent asynchronously and is modeled as a «signal» class whose attributes are its parameters and which can take part in generalization.
  • A state machine models one object's lifetime as states, the events that move it between them and its responses to those events.
  • A state has a name, entry and exit effects, internal transitions, substates and deferred events, and it may run a do activity.
  • A composite state holds sequential substates or concurrent regions; a shallow history state (H) resumes the last active substate and a deep history state (H*) the innermost ones.
  • A statechart diagram draws states as rounded rectangles, the initial state as a filled circle, the final state as a ringed circle and transitions as labelled arrows.
  • An active object owns a process or thread, and its active class is drawn with double vertical lines on both sides.
  • A synchronous message makes the sender wait, while an asynchronous message lets it continue.
  • A passive object shared by several flows marks each operation sequential (callers must coordinate), guarded (calls take turns) or concurrent (calls may run at once).
  • Timing constraints in braces limit absolute or relative time, and location is the placement of an artifact on a node.
  • A component is a replaceable part that offers provided interfaces (ball) and uses required interfaces (socket), often through ports.
  • A component diagram shows components, interfaces, ports and their dependencies, and artifacts such as .jar files manifest the components.
  • A node is a run-time computational resource drawn as a cube, and nodes are joined by communication paths.
  • A deployment diagram shows nodes, their connections and the artifacts deployed on them, and it models embedded, client/server and fully distributed systems.
  • In the weather forecasting case, stations sample sensors every 10 minutes and send readings to a forecast server, and a web server publishes the forecasts.

Learn these by heart

  • Transition label: event(parameters) [guard] / effect; its five parts are source state, event trigger, guard condition, effect and target state.
  • Four event kinds: signal, call, time (after or at) and change (when).
  • A change event fires when its condition becomes true; a guard is checked only when its event occurs.
  • Process: heavyweight flow in its own address space; thread: lightweight flow inside a process.
  • Provided interface: ball or realization; required interface: socket or dependency.
  • «deploy» runs from an artifact to a node; «manifest» runs from an artifact to the component it implements.

2-mark questions

1 What is an event in UML? Name the four kinds of events that can trigger a transition. 2 marks
Model answer

An event is something noteworthy that happens at a definite time and place and that an object can react to; in a state machine it can trigger a transition. UML has four kinds: signal events (a signal is received), call events (an operation is invoked), time events (after 5 seconds) and change events (when temperature > 40).

2 Define a transition in a state machine and list its five parts. 2 marks
Model answer

A transition is a move from a source state to a target state that happens when its trigger event occurs and its guard is true; the object runs the transition's effect on the way. Its five parts are the source state, event trigger, guard condition, effect and target state, written event [guard] / effect on the arrow.

3 Distinguish between a process and a thread, and state how UML shows an active class. 2 marks
Model answer

A process is a heavyweight flow of control with its own address space, scheduled alongside other processes. A thread is a lightweight flow of control that runs beside sibling threads inside one process and shares that process's memory. Both are active classes, stereotyped «process» or «thread», drawn as class boxes with double vertical lines on the left and right sides.

4 What are a timing constraint and a location in the UML modeling of time and space? 2 marks
Model answer

A timing constraint is a condition on time, such as a deadline or a maximum duration, written in braces beside the element it limits, for example {response < 2 s}. A location is the placement of an artifact, and the objects it holds, on a node, shown by drawing the artifact inside the node or with a «deploy» dependency.

5 What is a component? Differentiate between its provided and required interfaces. 2 marks
Model answer

A component is a self-contained, replaceable building block of a system: its inside is hidden and other parts use it only through interfaces. A provided interface lists the services the component implements for others and is drawn as a ball (lollipop). A required interface lists the services it needs from other components and is drawn as a socket (half circle).

6 What is a node in a deployment model, and how does a node differ from an artifact? 2 marks
Model answer

A node is a computing resource present at run time, with memory and usually a processor, such as a server or a weather station; it is drawn as a 3-D cube. An artifact is a physical file, such as a .jar or .exe file, that is deployed on a node: artifacts are what runs, nodes are where it runs.

10-mark questions

1 Explain events and signals in UML. Describe the four kinds of events, how signals are sent and received, and how a family of signals is modeled. 10 marks
Model answer

In UML an event is something noteworthy that happens at a definite time and place and that an object can react to. Events drive behavior: in a state machine an event can trigger a transition, and in an interaction it arrives as a message. External events pass between the system and its actors (a user presses a button); internal events pass between objects inside the system (an overflow exception).

The four kinds of events are:

1. Signal event: the receipt of a signal, a message object with a name and possibly data that one object sends to another without waiting for a reply. A signal is modeled as a class with the keyword «signal», and its attributes are its parameters. Exceptions are a kind of signal.

2. Call event: the dispatch of an operation on the receiving object. It is usually synchronous, so the caller waits until the operation ends. In a state machine it is written like a signal event, as name(parameters).

3. Time event: the passing of time, written with after for a relative time (after 30 seconds) or with at for an absolute time (at 23:59).

4. Change event: a condition becoming true, written with when, for example when (temperature > 40). A guard is checked only when its event occurs, but the condition of a change event is watched all the time.

Sending and receiving: an object sends a signal as the effect of a transition (/ send GasLeak) or as a message in an interaction. The receiver declares the signals it can accept and reacts to them in its state machine. A «send» dependency from an operation to a signal shows that the operation sends that signal.

Family of signals: the signals of a system are arranged in a generalization hierarchy, with the common parameters in the parent:

«signal» Alarm
raisedAt : Time
zone : Integer
A family of alarm signalsA generalization hierarchy of signals: SecurityAlarm and SafetyAlarm point to the parent signal Alarm; DoorForced and WindowBroken point to SecurityAlarm; SmokeDetected and GasLeak point to SafetyAlarm.«signal» AlarmSecurityAlarmSafetyAlarmDoorForcedWindowBrokenSmokeDetectedGasLeakgeneralizationgeneralizationgeneralizationgeneralizationgeneralizationgeneralization
A family of alarm signals

SecurityAlarm and SafetyAlarm specialize Alarm; DoorForced and WindowBroken specialize SecurityAlarm; SmokeDetected and GasLeak specialize SafetyAlarm. Every child inherits raisedAt and zone. On paper each generalization is a solid line with a hollow triangle at the parent end. Signal events are polymorphic: a transition triggered by SecurityAlarm also fires when DoorForced or WindowBroken is received.

To conclude, events tell an object when to react, and modeling signals as classes lets them carry data and be organized into families.

2 Explain how UML models processes and threads, and how it models time and space. Illustrate with the active objects of a print server. 10 marks
Model answer

A sequential system has one flow of control; a concurrent system has several flows running at once. UML models each independent flow with an active object, an object that has its own process or thread and so can act without being called. Its class is an active class, drawn as a class box with double vertical lines on its left and right sides. Objects without their own flow are passive.

  • A process is a heavyweight flow with its own address space, scheduled alongside other processes; its active class carries the stereotype «process».
  • A thread is a lightweight flow that runs beside sibling threads inside one process and shares that process's memory; its active class carries «thread».

Example: a PrintServer process holds two threads, receiver : JobReceiver and worker : PrintWorker, and a passive object queue : JobQueue that both threads use. A client : Client in another process submits jobs.

JobQueue
- jobs : Job[*]
+ add(job : Job)
+ take() : Job
Active objects in a print serverclient : Client sends message 1: submit(job) to receiver : JobReceiver. Inside the PrintServer process, receiver sends 1.1: add(job) and worker : PrintWorker sends 2: take() to the shared queue : JobQueue.PrintServer «process»client : Clientreceiver :JobReceiverqueue : JobQueueworker :PrintWorker1: submit(job)1.1: add(job)2: take()
Active objects in a print server

Communication:

  • 1: submit(job) is asynchronous: the client sends it as a signal and carries on (open arrowhead).
  • 1.1: add(job) and 2: take() are synchronous calls: the caller waits until the operation finishes (filled arrowhead).

On paper the objects are joined by link lines and each numbered message is a small arrow beside its link.

Synchronization: when several flows pass through one passive object, each operation has one of three concurrency kinds:

1. sequential: callers coordinate outside the object, and only one flow may be inside at a time;

2. guarded: the object makes callers take turns, so calls run one at a time;

3. concurrent: the object stays correct while several calls run at once.

The operations of JobQueue are guarded, so receiver and worker never corrupt the queue.

Time: UML models time with time events (after 10 seconds, at 06:00), time and duration observations in interactions, and timing constraints written in braces beside the element they limit, such as {1.1 completes in < 10 ms}.

Space: location is the placement of an artifact, and the objects it holds, on a node. Here the client runs on a user PC node and the PrintServer process on a server node; this is shown by drawing the artifact of each program inside its node or with a «deploy» dependency.

In short, active classes, message kinds and synchronization model concurrency, while timing constraints and location model time and space.

3 Explain the parts of a state and of a transition in a UML state machine, and draw a statechart diagram for an online shopping order. 10 marks
Model answer

A state machine describes the behavior of one object as the states it passes through during its lifetime, the events that move it from state to state and the way it responds to each event. A statechart diagram (called a state machine diagram in UML 2) shows a state machine and stresses the flow from state to state. It is used to model reactive objects such as an order.

Parts of a state:

1. Name, such as Paid.

2. Entry and exit effects: actions run on entering (entry / ...) and on leaving (exit / ...).

3. Internal transitions: events handled without leaving the state, so entry and exit effects do not run.

4. Substates: nested states, either sequential (one active at a time) or concurrent (orthogonal regions).

5. Deferred events: events postponed and queued until a state that handles them is active (event / defer).

A state may also run a do activity (do / ...) while it is active.

Parts of a transition: source state, event trigger, guard condition, effect and target state, written event [guard] / effect. A transition with no event is a completion transition, which fires when the source state finishes its work.

Example: an online Order.

Paid
entry / reserveStock
do / packItems
changeAddress / updateLabel

Paid has an entry effect, a do activity and an internal transition (changeAddress / updateLabel).

Statechart diagram of an online OrderFrom the Initial state the Order enters Pending. pay [amount = total] leads to Paid and after 24 hours leads to Cancelled. From Paid, ship / notifyBuyer leads to Shipped and cancel / refund to Cancelled. deliver takes Shipped to Delivered, and Delivered and Cancelled both reach the Final state.Initial statePendingPaidShippedCancelledDeliveredFinal statepay [amount= total]after 24 hourscancel/ refundship /notifyBuyerdeliver
Statechart diagram of an online Order

Transitions:

1. Initial state to Pending when the order is created.

2. Pending to Paid on pay [amount = total]: a call event with a guard; if the amount is wrong, the order stays Pending.

3. Pending to Cancelled on after 24 hours: a time event cancels an unpaid order.

4. Paid to Cancelled on cancel / refund: a signal event with an effect.

5. Paid to Shipped on ship / notifyBuyer.

6. Shipped to Delivered on deliver.

7. Delivered and Cancelled each reach the Final state by a completion transition.

On paper the initial state is a small filled black circle, the final state a filled circle inside a ring, each state a rounded rectangle and each transition a solid arrow with its label. A composite state may also hold a history state: H (shallow) resumes the last active substate, H* (deep) the innermost ones.

Thus a statechart diagram captures the complete, event-ordered lifetime of one reactive object.

4 What is a component in UML? Explain interfaces, ports and component diagrams, and draw a component diagram for an online shopping system. 10 marks
Model answer

A component is a self-contained, replaceable building block of a system: its inside is hidden and other parts use its behavior only through its interfaces. Because other parts depend only on those interfaces, a component can be replaced by any component that offers the same interfaces. On paper a component is a rectangle with the keyword «component» or a small icon with two tabs in its upper-right corner.

Main ideas:

1. Interface: a named set of operations. A provided interface is one the component realizes for others, drawn as a ball (lollipop) or as a realization, a dashed line with a hollow triangle, from the component to the interface. A required interface is one the component needs, drawn as a socket (half circle) or as a dependency, a dashed arrow, from the component to the interface.

2. Port: a small square on the component's boundary, a named window through which interfaces are offered, so the inside stays hidden.

3. Internal structure: a large component may contain parts joined by connectors. An assembly connector, a ball fitted into a socket, joins a required interface to a matching provided interface; a delegation connector links a port to the inner part that does the work.

4. Artifacts: a component is manifested by an artifact, a physical file such as shop.jar, shown by a «manifest» dependency.

Example, an online shopping system:

«component» ShoppingCart
  required: IOrder
«component» OrderManager
  provided: IOrder
  required: IPayment, IStock
«component» PaymentGateway
  provided: IPayment
«component» Inventory
  provided: IStock
Component diagram of an online shopping systemShoppingCart requires the interface IOrder, which OrderManager provides. OrderManager requires IPayment, provided by PaymentGateway, and IStock, provided by Inventory.ShoppingCartIOrderOrderManagerIPaymentIStockPaymentGatewayInventoryrequires(dependency)provides(realization)requires(dependency)requires(dependency)provides(realization)provides(realization)
Component diagram of an online shopping system

ShoppingCart requires IOrder, which OrderManager provides. OrderManager in turn requires IPayment from PaymentGateway and IStock from Inventory. Another payment component can replace PaymentGateway as long as it provides IPayment, and ShoppingCart and OrderManager need no change. In the figure each arrow is labelled provides (realization) or requires (dependency).

A component diagram shows a set of components, their interfaces and ports, and the dependencies among them; it models the static implementation view of a system. Together with artifact diagrams, which show the files that manifest the components, it is used to model source code, executable releases, physical databases and adaptable systems.

In conclusion, components and their interfaces let a system be built, replaced and reused in pieces.

5 Explain nodes, artifacts and connections in a UML deployment diagram, and draw a deployment diagram for a weather forecasting system. 10 marks
Model answer

A deployment diagram shows the processing nodes of a running system, how they are connected and which artifacts are deployed on each. It models the static deployment view of a system: which hardware exists, how it is linked and where each piece of software runs.

Elements:

1. Node: a computing resource present at run time, with memory and usually a processor, drawn as a 3-D cube. A hardware node may carry the stereotype «device»; a software platform such as an application server is an «executionEnvironment» nested in a device.

2. Artifact: a physical file, such as an executable, library, script or database file, drawn as a rectangle with the keyword «artifact» or a page icon with a folded corner. An artifact manifests components.

3. Deployment: an artifact is placed on a node by drawing it inside the node's cube or by a «deploy» dependency, a dashed arrow from the artifact to the node.

4. Connection: a communication path between two nodes, drawn as a solid line and often stereotyped with the kind of link, such as «HTTPS».

Case study: field weather stations measure temperature, pressure, humidity and wind every 10 minutes and send the readings over a cellular link to a forecast server. The server stores them in a database, runs a forecast model and saves forecasts, which a web server publishes to people using a browser on a user PC.

Artifact      Manifests or holds
station.bin   SensorReader
forecast.jar  DataCollector,
              ForecastEngine
weather.db    readings, forecasts
portal.war    ForecastPortal
Deployment diagram of a weather forecasting systemstation.bin, forecast.jar, weather.db and portal.war are deployed on the Weather Station, Forecast Server, Database Server and Web Server respectively. The Weather Station links to the Forecast Server by «cellular», both servers link to the Database Server by «LAN», and the User PC links to the Web Server by «HTTPS».station.binWeather Station«device»forecast.jarForecastServer «device»weather.dbDatabaseServer «device»portal.warWeb Server«device»User PC «device»«deploy»«deploy»«deploy»«deploy»«cellular»«LAN»«LAN»«HTTPS»
Deployment diagram of a weather forecasting system

Reading the diagram:

  • station.bin is deployed on the Weather Station, which reaches the Forecast Server over a «cellular» path.
  • forecast.jar runs on the Forecast Server: DataCollector receives the readings and ForecastEngine runs the model.
  • weather.db lives on the Database Server, joined by «LAN» paths to the Forecast Server and the Web Server.
  • portal.war runs on the Web Server, which the User PC reaches over «HTTPS».

Every station runs the same artifact, so the Weather Station node is drawn once and stands for all the stations in the field.

Deployment diagrams are used to model embedded systems, client/server systems and fully distributed systems. This one is distributed: sensing, forecasting, storage and publishing run on separate nodes, so each can be replaced or scaled on its own.

6 Draw and explain a statechart diagram for the weather station of a weather forecasting system, showing the events, guards and effects on its transitions. 10 marks
Model answer

A statechart diagram (a state machine diagram in UML 2) shows the states a reactive object passes through and the events that move it between them. In the weather forecasting system each field weather station measures temperature, pressure, humidity and wind every 10 minutes, sends the readings to the forecast server and waits for an acknowledgement. Its behavior depends on its state, so a statechart diagram suits it.

WeatherStation
- stationId : String
- battery : Integer
- buffer : Reading[*]
+ checkSensors()
+ readSensors()
+ sendReadings()
+ clearBuffer()
+ alertOperator()
+ shutdown()

States:

1. SelfTest: entry / checkSensors.

2. Idle: waiting for the next sample time.

3. Sampling: do / readSensors.

4. AwaitingAck: readings sent, waiting for the server's reply.

5. Fault: entry / alertOperator.

Statechart diagram of a weather stationFrom the Initial state the station enters SelfTest, then Idle on [all sensors ok] or Fault on [sensor failed]. after 10 minutes leads from Idle to Sampling, / sendReadings to AwaitingAck, and ack / clearBuffer back to Idle. after 5 minutes and when (battery ≤ 10%) lead to Fault; reset returns to SelfTest and shutdown reaches the Final state.Initial stateSelfTestIdleSamplingFaultAwaitingAckFinal state[allsensors ok][sensorfailed]after 10minutes/ sendReadingsack /clearBufferafter 5minuteswhen (battery≤ 10%)resetshutdown
Statechart diagram of a weather station

Transitions, written event [guard] / effect:

1. Initial state to SelfTest when the station powers up.

2. SelfTest to Idle on [all sensors ok], or to Fault on [sensor failed]. These completion transitions have no event: they fire when checkSensors finishes, and the guards choose the branch.

3. Idle to Sampling on after 10 minutes, a time event.

4. Sampling to AwaitingAck on / sendReadings, a completion transition that fires when readSensors finishes and has the effect sendReadings.

5. AwaitingAck to Idle on ack / clearBuffer, where ack is a signal from the forecast server.

6. AwaitingAck to Fault on after 5 minutes, a time event for a missing ack.

7. Idle to Fault on when (battery ≤ 10%), a change event.

8. Fault to SelfTest on reset, a signal sent by the operator.

9. Fault to the Final state on shutdown, a call event.

On paper the initial state is a filled black circle, the final state a filled circle inside a ring, each state a rounded rectangle holding its entry or do action, and each transition a solid arrow with its label.

The diagram uses all four kinds of events (signal, call, time and change), guards and effects, so the station's reactive behavior is fixed clearly before it is coded.

Public sources that settled doubtful points

Only the points the second AI pass doubted were looked up. These are the pages that confirmed or contradicted them; nothing here is copied from them.

34 pages

Further reading

Titles only, for your own study. Nothing on this page is copied from them. The units follow the official JNTUK R23 CSE syllabus (PDF) ↗.

  • Object-Oriented Analysis and Design with Applications · Grady Booch, Robert A. Maksimchuk, Michael W. Engle, Bobbi J. Young, Jim Conallen and Kelli A. Houston
  • The Unified Modeling Language User Guide · Grady Booch, James Rumbaugh and Ivar Jacobson
  • Fundamentals of Object-Oriented Design in UML · Meilir Page-Jones
  • Modeling Software Systems Using UML2 · Pascal Roques
  • Object Oriented Analysis & Design · Atul Kahate
  • Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and the Unified Process · Craig Larman