UMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUMLUML
Motivation
When developing a software system for a customer, the initial challenge is to clearly understand their specific requirements This crucial first step significantly impacts the project's success or failure Effective communication with the customer is essential to ensure that their needs are accurately captured and understood.
Natural language can often be imprecise and ambiguous, leading to misunderstandings, especially among individuals from different professional backgrounds, such as computer scientists and business managers This lack of clarity poses a significant risk of miscommunication, which can have serious consequences.
What you need is to be able to create a model for your software This model highlights the important aspects of the software in a clear form
M Seidl et al emphasize the importance of using a simplified notation in UML, similar to architectural models like construction plans, which focus on essential details such as the floor plan while omitting irrelevant information like construction materials or electrical layouts This approach prevents unnecessary complexity and allows individuals from diverse backgrounds, such as architects and builders, to effectively read, interpret, and implement the model in information technology.
Modeling languageswere developed precisely for such scenarios and
Modeling languages establish clear rules for structured system descriptions and can be either textual, like Java, or visual, using symbols for components such as transistors and diodes These languages may be domain-specific, tailored for particular fields like web applications, offering efficient problem-solving tools while potentially being restrictive Conversely, general-purpose modeling languages, such as UML, provide broader applicability This book focuses on UML to explore key concepts in object-oriented modeling.
Object-oriented modeling is a form of modeling that obeys the
Object-oriented modeling is rooted in the object-oriented paradigm In the upcoming sections, we will explore the concept of a model and the fundamental principles of object orientation, laying a solid foundation for our later analysis of object-oriented modeling using UML.
Models
Models allow us to describe systems efficiently and elegantly Asystem
A system is a cohesive unit composed of interconnected components that influence one another, allowing them to function as a single, purpose-driven entity These systems distinguish themselves from their external environments Examples include tangible objects like cars and airplanes, natural ecosystems such as lakes and forests, and organizational structures like universities and companies In the realm of information technology, the focus is primarily on software systems and the models that describe them.
Software systems themselves are based onabstractionsthat repre- Abstraction sent machine-processible facts of reality In this context, abstraction means generalization—setting aside specific and individual features.
Abstract is the opposite of concrete Abstracting therefore means mov- ing away from specifics, distinguishing the substance from the inciden- tal, recognizing common characteristics [29].
Selecting appropriate means of abstraction is crucial in software system development, as it facilitates both implementation and future usability The right abstraction simplifies programming by creating small, straightforward interfaces, allowing for the seamless introduction of new functionalities without extensive reorganization Conversely, improper abstraction can lead to complex interfaces and challenges in implementing changes, making it difficult to manage the growing complexity of modern software systems Effective modeling can offer significant benefits in this context.
To enhance your grasp of modeling concepts, we outline widely accepted definitions of a model and the essential characteristics that a quality model must exhibit.
The concept of a model is crucial across various scientific fields, including information technology, mathematics, philosophy, psychology, and economics Originating from the Latin term "modulus," meaning a scale in architecture, the Italian word "modello" was used during the Renaissance to refer to an illustrative object that showcased the design of a proposed building, aiding in client presentations and clarifying architectural concepts Over time, the term "model" has evolved to represent a simplified representation of complex realities in multiple scientific disciplines.
In 1973, Herbert Stachowiak proposed a model theory that is distin- Definition by Herbert
Stachowiak guished by three characteristics [48]:
1 Mapping:a model is always an image (mapping) of something, a representation of natural or artificial originals that can be models themselves.
2 Reduction:a model does not capture all attributes of the original, rather only those that seem relevant to the modeler or user of the model.
3 Pragmatism: pragmatism means orientation toward usefulness A model is assigned to an original based on the following questions:
For whom? Why? What for?A model is used by the modeler or user instead of the original within a specific time frame and for a specific purpose.
Models simplify complex systems by focusing on essential elements, allowing for easier management and understanding Typically, a system is represented through multiple perspectives, each contributing to a cohesive overall understanding For instance, one perspective may detail the objects and their relationships, while another may illustrate the behaviors and interactions among various objects.
Models must be created with great care and due consideration Ac-
Properties of models cording to Bran Selic [47], five characteristics determine the quality of a model:
Abstraction is the process of creating a simplified model that represents a system by omitting irrelevant details This reduction allows users to grasp the core essence of the system more easily, facilitating better understanding and analysis.
To enhance understandability in modeling, it's essential to present key elements intuitively, often through graphical notation, rather than merely omitting irrelevant details The expressiveness of the modeling language plays a crucial role, defined as the capacity to convey complex information using minimal concepts A well-designed model significantly reduces the intellectual effort needed to grasp the depicted content In contrast, traditional programming languages often lack expressiveness for human readers, requiring substantial effort to comprehend the program's content.
• Accuracy:a model must highlight the relevant properties of the real system, reflecting reality as closely as possible.
• Predictiveness:a model must enable prediction of interesting but not obvious properties of the system being modeled This can be done via simulation or analysis of formal properties.
• Cost-effectiveness:in the long-run, it must be cheaper to create the model than to create the system being modeled.
Models can be used for various purposes Thus we distinguish be- tween descriptive and prescriptive models [17] Descriptive models
Descriptive models simplify reality to enhance understanding of specific aspects, much like a city map aids non-locals in navigating urban routes.
Prescriptive model tive modelsare used to offer a construction manual for the system to be developed.
This book explores the modeling of various aspects of a software system using the Unified Modeling Language (UML), enabling the derivation of executable code through manual processes.
Executable code as model or (semi)automatically, or easily understandable documentation can be
Executable code, developed in programming languages like Java, serves as a model that represents the problem to be solved and is optimized for computer execution.
To summarize, there are three applications for models [19]:
Models serve as simplified sketches to effectively communicate key elements of a system, focusing on essential aspects necessary for problem-solving Unlike comprehensive mappings, these selective sketches highlight alternative solutions, facilitating discussions among development team members Consequently, models play a crucial role in fostering collaborative dialogue during the development process.
When utilizing models as blueprints, completeness is crucial, as these models must provide enough detail for developers to create fully functional systems without needing to make design decisions Typically, these blueprints do not encompass the entire system but focus on specific components, such as interface definitions between subsystems, allowing developers the freedom to determine internal implementation details Additionally, if the models include behavioral descriptions, they can be simulated and tested to detect potential faults early in the development process.
Models serve as essential sketches and blueprints in both forward and backward engineering processes In forward engineering, these models facilitate code creation, while in backward engineering, they are derived from existing code to provide clear and comprehensible documentation.
Models can function as executable programs, allowing for precise specifications from which code can be automatically generated In recent years, model-based software development utilizing UML has gained significant popularity, providing a framework for treating UML as a programming language This topic will be further explored in Chapter 9, following a discussion of UML basics In fields like embedded systems development, models are increasingly replacing traditional programming languages, while ongoing research aims to elevate software system development to a more maintainable and less error-prone abstraction level.
Object Orientation
Classes
In many object-oriented approaches, it is possible to defineclassesthat
A class abstractly defines the attributes and behaviors of a group of objects, known as instances, by grouping their common features For instance, a person has attributes like a name, address, and social security number, while a course is characterized by a unique identifier, title, and description Additionally, a lecture hall includes a name and location Classes also establish a set of permitted operations for their instances, such as reserving a lecture hall for a specific date or allowing a student to register for an exam, thereby outlining the behavior of the objects they represent.
Objects
The instances of a class are referred to as itsobjects For example,lh1,
Lecture Hall 1 at the Vienna University of Technology exemplifies the class LectureHall, showcasing how individual objects possess unique identities Each instance of a class can be distinctly identified, as demonstrated by the beamer in Lecture Hall 1, which is separate and distinct from the beamer found in Lecture Hall 2.
1.3 Object Orientation 7 if the devices are of the same type Here we refer toidenticaldevices but not thesamedevice The situation for concrete values of data types is different: the number1, which is a concrete value of the data type
Integer, does not have a distinguishable identity.
An object consistently possesses a specific state, which is defined by the values of its attributes; for instance, a lecture hall can be either occupied or free Additionally, an object exhibits behavior that is characterized by its operations, which are activated through the sending of messages.
Encapsulation
Encapsulation is a fundamental concept in object-oriented programming that safeguards an object's internal state from unauthorized access through a clearly defined interface It utilizes varying levels of visibility, such as public, private, and protected, to establish different access permissions In Java, the public marker allows access to all, private restricts access solely to the object itself, and protected permits access to members of the same class, its subclasses, and those within the same package.
Messages
Objects communicate through messages, which serve as requests for operations to be executed The decision to execute an operation rests with the object, contingent on the sender's authorization and the availability of a suitable implementation Visibility regulations determine the authorization process Additionally, many object-oriented programming and modeling languages support overloading, allowing operations to be defined differently based on parameter types For instance, the operator "+" behaves differently when adding integers compared to other data types.
= 2) or to concatenate character strings (e.g.,“a” + “b” = “ab”).
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows new classes, known as subclasses, to be created from existing classes, referred to as superclasses Subclasses inherit all visible attributes and operations from their superclasses, enabling code reuse and enhancing functionality.
• Define new attributes and/or operations
• Overwrite the implementation of inherited operations
• Add its own code to inherited operations
Inheritance enables extensible classes and as a consequence, the cre- ation ofclass hierarchiesas the basis for object-oriented system devel-
Class hierarchy opment A class hierarchy consists of classes with similar properties, for example,Person←Employee←Professor← where
Properly utilized, inheritance provides numerous benefits, including the reuse of program components to minimize redundancy and errors, the establishment of consistent interfaces, and the facilitation of natural categorization for modeling purposes Additionally, it supports incremental development, allowing for a gradual refinement from general to specific concepts.
Polymorphism
In general terms,polymorphismis the ability to adopt different forms.
A polymorphic attribute in a program can reference objects from various classes, with a specific type assigned statically at compile time (e.g., class Person) However, during runtime, this attribute can dynamically bind to a subtype, such as subclass Employee or subclass Student.
Polymorphic operations enable the execution of functions on objects from various classes, each with distinct semantics This can be achieved through several methods: (i) parametric polymorphism, or genericity, where type parameters are utilized, such as in Java where concrete classes are passed as arguments; (ii) inclusion polymorphism, allowing operations on classes and their subclasses; (iii) operation overloading; and (iv) coercion, which involves type conversion The first two methods fall under universal polymorphism, while the latter two are categorized as ad hoc polymorphism.
The Structure of the Book
1.4 The Structure of the Book
In Chapter 2, we provide an overview of UML, highlighting its historical development and its 14 distinct diagrams Chapter 3 focuses on use case diagrams, which outline the system requirements for development Chapter 4 introduces class diagrams, detailing the structural aspects of a system To model system behavior, Chapter 5 covers state machine diagrams, followed by sequence diagrams in Chapter 6 and activity diagrams in Chapter 7 Chapter 8 illustrates the interactions among these diagram types through three examples Finally, Chapter 9 explores advanced concepts crucial for effectively utilizing UML in practical applications.
This article utilizes examples rooted in the typical Austrian university setting to explain concepts, often simplifying scenarios for clarity Our aim is not to create a comprehensive model, as this could lead to an overwhelming focus on technical details Instead, we have chosen examples for their educational value and clarity, often making assumptions that simplify complex realities for better understanding.
UML is fundamentally rooted in object-oriented concepts, with the class diagram serving as a clear representation that can be seamlessly translated into object-oriented programming languages In Chapter 4, we will explore the class diagram and its potential translations into program code It is important to note that UML is not tailored to any specific object-oriented language; instead, we adopt a notion of object-orientation akin to that found in contemporary programming languages such as Java and C#.
Before introducing the most important concepts of UML in the follow- ing chapters, we first explain the background of this modeling language.
We look at how UML came into being and what the “U” for “Unified” actually means We then answer the question of how UML itself is de-
This article explores the origins of the rules that define valid UML models, highlights the applications of UML, and provides a brief overview of the 14 UML diagrams included in version 2.4.1 of the UML standard specification, which can be utilized for modeling both structural and behavioral aspects.
The History of UML
The origins of object-oriented concepts in information technology can be traced back to the early 1960s, with pioneering systems like Sketchpad introducing innovative graphical communication methods between humans and computers.
Today, the programming language SIMULA [24] is regarded as the SIMULA
SIMULA, the first object-oriented programming language, was primarily designed for developing simulation software Although it was not widely adopted, it introduced foundational concepts such as classes, objects, inheritance, and dynamic binding, which have significantly influenced modern programming languages.
The introduction of object-oriented programming concepts sparked a revolution in software development, leading to the emergence of numerous programming languages over the following decades Notable languages such as C++, Eiffel, and Smalltalk were developed based on the object-oriented paradigm, incorporating essential features that are still relevant in modern programming today.
M Seidl et al., UML @ Classroom , Undergraduate Topics in Computer Science, DOI 10.1007/978-3-319-12742-2_ 2
Object-oriented programming (OOP) has significantly influenced software engineering, providing a robust framework for managing the complexities of software systems This well-established methodology extends beyond programming languages, finding applications in databases and user interface design.
Software systems serve as abstractions to address real-world problems through machine support However, procedural programming languages may not effectively represent these issues due to significant disparities between natural problem descriptions and their programmatic implementations Object-oriented programming emerged as a solution to create programs that are not only more effective but also easier to maintain.
Object orientation has emerged as the leading software development paradigm, evident in languages like Java and C#, as well as modeling languages such as UML The evolution of software development to its current state-of-the-art has been a complex journey.
In the 1980s, the programming language Ada, funded by the United
The Ada programming language gained significant popularity within the United States Department of Defense due to its powerful concepts and efficient compilers It supported abstract data types through packages and facilitated concurrency with tasks, allowing for a clear separation between specification and implementation This capability set Ada apart from contemporaneous languages like Fortran and Cobol, leading to a heightened demand for object-oriented analysis and design methods tailored to simplify Ada program development Consequently, modeling methods emerged that specifically addressed Ada's unique characteristics, with Grady Booch being one of the pioneering researchers to publish relevant work in this area.
Booch method on the object-oriented design of Ada programs [5].
Over the years, various object-oriented modeling methods have emerged, each with distinct focuses Some, like the Booch method, are closely tied to programming languages, while others emphasize data modeling For a comprehensive overview, refer to [12].
The Object Modeling Technique (OMT), developed by James Rumbaugh and colleagues, enhances the entity-relationship model to facilitate the development of complex objects in object-oriented programming Meanwhile, Ivar Jacobson and his team introduced their own methodologies, further advancing the field of object-oriented design.
Jacobson et al Oriented Software Engineering(OOSE) approach [27] This approach was originally developed to describe telecommunication systems.
In the 1980s and early 1990s, the modeling industry faced significant challenges due to the emergence of numerous modeling languages, leading to what is known as the "method war." This proliferation resulted in compatibility issues among models from different project partners, making it difficult to reuse models across various projects Consequently, extensive debates over differing notations distracted from addressing core modeling problems With new languages constantly emerging, it was unclear which were worth investing in and which were merely fleeting trends Ultimately, if a modeling language failed to gain acceptance, all prior investments in its implementation were typically lost, highlighting the chaotic landscape of that era.
To put an end to this unsatisfactory situation, in 1996 the Object Object Management
Management Group(OMG) [33], the most important standardization body for object-oriented software development, called for the specifica- tion of a uniform modeling standard.
In the previous year, 1995, Grady Booch, Ivar Jacobson, and James
Rumbaugh had combined their ideas and approaches at the OOPSLA conference (OOPSLA stands for Object-Oriented Programming, Sys- tems, Languages, and Applications) Since then, Booch, Jacobson, and
Rumbaugh have often been called the “three amigos” They set them- Three amigos selves the following objectives [1]:
• Use of object-oriented concepts to represent complete systems rather than just one part of the software
• Establishment of an explicit relationship between modeling concepts and executable program code
• Consideration of scaling factors that are inherent in complex and crit- ical systems
• Creation of a modeling language that can be processed by machines but can also be read by human beings
The result of their efforts was theUnified Modeling Language(UML) Unified Modeling
The Unified Modeling Language (UML), first submitted in version 1.0 in 1997 in response to the Object Management Group's (OMG) call, saw the involvement of several former competitors in the development of version 1.1, released in 1998 A primary objective of this update was to establish a consistent specification for UML's core language, which is thoroughly documented in the metamodel.
The Unified Modeling Language (UML) offers essential model elements that are crucial for effective system design To ensure these elements meet specific requirements, the Object Constraint Language (OCL) is utilized, providing a framework for formulating necessary constraints.
The Object Constraint Language (OCL) predicate logic was introduced, leading to revisions in various language concepts These updates included mechanisms for model interchangeability, specifically utilizing the XML Metadata Interchange format.
(XMI) [38] were added In addition to these rather small changes, in
In 2000, the Object Management Group (OMG) began a modernization process for the Unified Modeling Language (UML), culminating in the adoption of the UML 2.0 standard in 2005 Since then, minor updates through interim versions have led to the current version, UML 2.4.1, which will be the focus of this book.
UML, a widely used graphical object-oriented modeling language, retains its foundational elements from the Booch method, OMT, and OOSE despite numerous revisions It effectively models complex object relationships and concurrent processes, making it a versatile tool across various application areas With its intuitive graphical notation and comprehensive modeling concepts, UML facilitates the specification, design, visualization, and documentation of software systems The outcome of UML modeling is a graphical model that presents multiple perspectives of a system through various diagrams.
Usage
UML is a versatile modeling language that is independent of any specific development tool, programming language, or target platform It does not prescribe a software development process but distinguishes between the modeling language and the modeling method, which can be tailored to individual projects or organizations Notably, UML's concepts support an iterative and incremental development approach.
UML can be used consistently across the entire software develop-
In the software development process, consistent language concepts and notations can be utilized across all stages, allowing for gradual refinement of models without the need for translation into different modeling languages This approach supports an iterative and incremental development methodology UML (Unified Modeling Language) is particularly effective across diverse application domains, accommodating varying requirements related to complexity, data volume, and real-time processing The proper application of UML model elements is outlined in the UML metamodel, which defines the language concepts comprehensively.
The UML standard is designed to be broadly applicable and flexible, intentionally maintaining vagueness in certain areas to allow for diverse interpretations and semantic variations.
Semantic variation points can enhance flexibility in language standards, but they also result in diverse implementations by modeling tools This diversity complicates the exchange of models, posing challenges for interoperability.
Diagrams
Structure Diagrams
UML provides seven diagram types to model a system's structure from various perspectives However, these diagrams do not account for the dynamic behavior of the elements, focusing instead on their static characteristics.
Just like the concepts of the object diagram (see next paragraph), the Class diagram
The class diagram, rooted in conceptual data modeling and object-oriented software development, serves to define the data and object structures within a system Key concepts of the class diagram include class, generalization, and association For instance, it illustrates the relationships among the classes Course, Student, and Professor, where professors teach courses and students attend them Additionally, both students and professors share common attributes as members of the class Person.
This is expressed by a generalization relationship.
Based on the definitions of the related class diagram, an object dia- Object diagram
(see Chapter 4) henryFoster :Professor oom:Course oop:Course gramshows a concrete snapshot of the system state at a specific execu- tion time For example, an object diagram could show that a professor
Henry Foster (henryFoster) teaches the courses Object-Oriented Model- ing (oom) and Object-Oriented Programming (oop).
18 2 A Short Tour of UML The Package Diagram
Thepackage diagramgroups diagrams or model elements according to
In a university administration system, functional cohesion is exemplified through the integration of packages that encompass teaching, research, and administrative information These packages are typically incorporated into various diagrams, rather than being displayed in isolation, highlighting their interconnected roles within the system.
UML pays homage to component-oriented software development by
Administration offers component diagrams, which depict components as independent, executable units that provide or utilize services from other components UML allows for a flexible integration of object-oriented and component-oriented concepts without strict separation When modeling a component, two explicit views can be specified: the external view (black box view) representing the component's specification, and the internal view (white box view) detailing the component's implementation.
Thecomposition structure diagramallows a hierarchical decomposition
A composition structure diagram effectively illustrates the internal architecture of classes or components within a system, allowing for a more detailed representation than traditional class diagrams This approach enables context-specific modeling, where you can outline the precise internal structures relevant to the specific context being analyzed.
The hardware topology used and the runtime system assigned can be
The client is illustrated through a deployment diagram, highlighting the hardware components, which consist of processing units represented as nodes Additionally, it emphasizes the communication relationships that exist between these nodes The runtime system comprises artifacts that are specifically deployed to these nodes.
Usingprofiles, you can extend UML to introduce domain-specific con- Profile diagram ômetaclassằ
The core language definition of UML, represented by its meta-model, remains stable, allowing for the reuse of modeling tools without the need for modifications This stability enables the introduction of concepts such as Java Enterprise Beans through the use of profiles.
Behavior Diagrams
With thebehavior diagrams, UML offers the infrastructure that enables you to define behavior in detail.
Behavior encompasses the direct outcomes of an action performed by at least one object, influencing how the states of those objects evolve over time It can be defined by the actions of an individual object or emerge from the interactions among multiple objects.
UML offers theuse case diagramto enable you to define the require- Use case diagram
A university administration system must meet specific requirements, illustrating how different users interact with its functionalities This overview highlights the various use cases, such as the Registration feature, which is primarily utilized by students While the diagram identifies user interactions, it does not delve into the implementation details of the system.
Within their life cycle, objects go through different states For example, State machine diagram
When a person first visits a website, they are in the "logged out" state This state transitions to "logged in" after successfully entering their username and password Once the user logs out, they revert to the "logged out" state This behavior can be effectively illustrated using a UML state machine diagram, which outlines the permissible behaviors of an object through various states and the transitions triggered by specific events.
20 2 A Short Tour of UML The Activity Diagram
You can model processes of any kind usingactivity diagrams: both busi-
Activity diagrams play a crucial role in illustrating the necessary actions for students to engage in lectures and assignments They provide both control flow and data flow mechanisms, effectively coordinating the various actions involved in a specific process.
Thesequence diagramdescribes the interactions between objects to ful-
This article discusses the process of completing specific tasks, such as registering for an exam within a university administration system It emphasizes the importance of maintaining a chronological order in the messages exchanged between participants Additionally, it highlights various constructs that facilitate the control of message sequences and modularization concepts that enable the modeling of complex interactions.
Similarly to the sequence diagram, the communication diagram de-
DB illustrates the communication dynamics among various objects, emphasizing the relationships between interaction partners instead of the sequence of message exchanges It does not incorporate complex control structures, making it straightforward This diagram effectively clarifies the interactions between different entities.
Thetiming diagramexplicitly shows the state changes of the interaction
:System :Student :DB active log.in log.out busy idle login check login: ″ok″ check:
"OK" partners can arise from time events or message exchanges For instance, when a user is logged in and receives a notification from the university administration system confirming that their password is valid, this interaction exemplifies such a partnership.
Theinteraction overview diagrammodels the connection between dif- Interaction overview diagram (see Chapter 6) reg.() reg.:″ok″
:Sys. :Stud. sd Registration sd Forum [authorized] [else] ferent interaction processes by setting individual interaction diagrams
Interaction overview diagrams, such as sequence, communication, and timing diagrams, illustrate processes in a time-based and causal sequence, outlining the conditions under which interactions occur To effectively model control flow, elements from activity diagrams are incorporated For instance, in a university administration system, a user must first log in—an essential interaction—before accessing additional functionalities.
Diagrams Presented in this Book
This book focuses on the five most essential UML diagrams: use case diagram, class diagram (including object diagram), state machine diagram, sequence diagram, and activity diagram These diagrams are presented in the typical sequence used in software development projects We start with the use case diagram, which outlines the fundamental functionality of a software system Next, the class diagram identifies the objects or classes that contribute to this functionality The state machine diagram illustrates the behavior within individual objects, while the sequence diagram details the interactions between objects Lastly, the activity diagram provides a comprehensive view of the workflow within the system.
fine those processes that “implement” the use cases from the use case diagram.
A use case diagram visually represents the potential usage scenarios (use cases) for a system, outlining its expected functionalities without delving into implementation specifics like data structures or algorithms These implementation details are explored in other diagrams, such as class diagrams and interaction diagrams.
Chapter 6) The use case diagram also models which user of the system uses which functionality, i.e., it expresses who will actually work with the system to be built.
Use cases are essential in object-oriented development, guiding the analysis and design phases by capturing customer requirements for the system They provide a high-level overview of the system's intended functions and purposes Additionally, use case diagrams can document the functionalities of existing systems and track user permissions for various features.
Specifically, we can employ a use case diagram to answer the fol- lowing questions:
1 What is being described? (The system.)
2 Who interacts with the system? (The actors.)
3 What can the actors do? (The use cases.)
The use case diagram, while appearing simple at first, is often underestimated in its importance It effectively captures the customer's expectations for the system being developed and serves as a crucial documentation tool for the requirements that the system must meet This documentation is vital for creating a detailed technical design Neglecting to accurately specify or include use cases can lead to significant oversights in the development process.
In their work, M Seidl et al emphasize the critical importance of meticulously crafting use cases in software development, as neglecting this can lead to severe consequences such as increased development and maintenance costs and user dissatisfaction These issues can ultimately result in a system that fails to meet its intended goals, diminishing the return on investment Although the focus of the book is not on software engineering or requirements analysis, the authors highlight common pitfalls and advocate for a systematic approach to avoid errors in this process For a comprehensive understanding of these topics, readers are encouraged to refer to additional resources.
Use Cases
Ause casedescribes functionality expected from the system to be de-
A use case represents a specific interaction between actors and a system, providing tangible benefits through its defined functions While a use case diagram illustrates these interactions, it does not detail the internal structure or implementation Typically, a use case is initiated by an actor's invocation or a trigger event, such as a specific action or condition that prompts the interaction.
Trigger the semester has ended and hence the use caseIssue certificatemust be executed.
Use cases are essential for capturing customer needs and analyzing specified problems in natural language, forming the foundation for requirements analysis They also serve to document the functionalities offered by a system Typically, a use case is depicted as an ellipse with its name placed inside or directly beneath it Alternatively, it can be illustrated as a rectangle featuring the use case name at the center and a small ellipse in the top right corner Various notation options for the use case "Query Student Data" are presented in Figure 3.1 While all representations are valid, the elliptical format with the name inside is the most commonly utilized.
Notation alternatives for use cases
Query student data Query student data Query student data
Actors
The comprehensive collection of use cases outlines the functionalities provided by a software system, typically represented within a rectangle that denotes the system's boundaries For instance, the Student Administration system encompasses three key use cases: querying student data, issuing certificates, and announcing exams, all of which can be initiated by the actor, Professor.
Figure 3.2 Representation of system boundaries
To fully describe a system, it is crucial to document its functionalities as well as the individuals who interact with it In a use case diagram, actors play a vital role by engaging with the system, highlighting the importance of understanding both system capabilities and user interactions.
X tem in the context of their use cases, that is, the use cases with which they are associated The example inFigure 3.2contains only the actor
In a use case diagram, actors such as professors and students can be represented by stick figures, rectangles with additional information, or custom symbols, all of which are valid notation options These actors may be human, like students and professors, or non-human, such as an email server The choice of symbols for representing actors depends on the model creator or the specific tool used Interestingly, non-human actors can also be depicted as stick figures, despite the potential for confusion this may cause.
Notation alternatives for actors ôactorằ
An actor interacts with the system by using the system as an ac- tiveactor, meaning that the actor initiates the execution of use cases;
In use case diagrams, actors can be classified as primary or secondary, with primary actors actively benefiting from the execution of a use case, while secondary actors provide necessary functionality but do not gain direct benefits For instance, in the use case "Inform Student," the Professor serves as a primary actor, while the E-Mail Server is a secondary actor, both essential for the process Additionally, in the "Exam" use case, both the Professor and the Student are active participants, but the Student is the primary beneficiary, highlighting that secondary actors can also be actively involved Importantly, use case diagrams do not visually distinguish between primary and secondary actors, nor between active and passive roles, or between human and non-human entities.
An actor exists outside the system, meaning a user is not integrated within it However, user data can be accessed within the system and may be depicted in a class diagram Determining whether an element belongs to the system can sometimes be challenging.
Associations
mented or serves as an actor In example (a) inFigure 3.4, theE-Mail
In the context of the use case "Inform Student," the server acts as an essential actor only when external support is needed If the student administration system includes its own email functionality or server, the E-Mail Server is no longer considered an actor Consequently, the Professor is solely responsible for communicating news and updates to students.
In Figure 3.4, actors are linked to use cases through solid lines, indicating associations that demonstrate the relationship between the actor and the use cases These associations illustrate how actors interact with the system's functionalities.
In system design, every actor must engage with at least one use case to ensure meaningful interaction; otherwise, an actor without interaction becomes irrelevant Similarly, each use case should be linked to at least one actor, as a functionality without users is unnecessary and ineffective.
An association in use case diagrams is inherently binary, linking one use case to one actor Multiplicities can define the number of instances involved; for instance, a multiplicity greater than 1 indicates multiple actor instances participating in the use case For example, in the use case "Conduct Oral Exam," one to three students and exactly one assistant are involved If no multiplicity is indicated for the actor, a default value of 1 is assumed Conversely, the multiplicity at the use case's end is often unrestricted and rarely specified explicitly.
Actors do not represent a specific user—they represent roles that
Users can adopt specific roles that authorize them to execute associated use cases, allowing for simultaneous involvement in multiple roles, such as serving as both an assistant and a student for different assignments This role concept is also applicable in various UML diagrams, including class diagrams, sequence diagrams, and activity diagrams.
Relationships between Actors
Actors often have common properties and some use cases can be used
In the context of data access, various actors, such as professors and research assistants, may be granted permission to view student data This relationship can be illustrated through an inheritance model, where a sub-actor inherits the attributes and use cases of a super-actor Essentially, this generalization reflects an "is a" relationship, indicating that the sub-actor shares all relevant use cases associated with the super-actor.
Example of generalization for actors
In the relationships between actors, the hierarchy is illustrated with a triangular arrowhead pointing towards the super-actor For instance, in the example provided, both the Professor and Assistant inherit from the Research Associate, establishing that all professors and assistants are classified as research associates Each research associate has the capability to execute the use case "Query student data." However, only professors have the authority to create a new course, while assistants are solely responsible for publishing tasks Additionally, to execute the use case "Issue certificate," a Professor is required, with the option for an Assistant to participate, indicated by the multiplicity of 0 1.
The distinction between two actors directly involved in a use case and two actors sharing a common super-actor is significant In the former scenario, both actors are required to engage in the use case together Conversely, in the latter situation, each actor inherits the association from the super-actor, allowing them to participate in the use case individually.
Figure 3.7 Example with and without generalization
actor These abstract actors may be identified by italicizing their names For instance, the actor "Research Associate" depicted in Figure 3.7(b) serves as an example of an abstract actor It is essential to indicate that either a
Professoror anAssistantis involved in the use caseQuery student data.
Abstract actors are meaningful primarily within an inheritance framework, where shared characteristics of sub-actors are consolidated and articulated through a common, abstract super-actor.
Generalization is a fundamental concept of object orientation and can be applied to many different language elements of UML For a more detailed introduction to generalization, see Chapter 4.
Relationships between Use Cases
So far, we have explored the relationships between use cases and actors, as well as the generalization of actors However, it is essential to recognize that use cases can also interact with one another This interaction can be categorized into three main types: "include" relationships, "extend" relationships, and the generalization of use cases.
Example of ôincludeằ and ôextendằ
If a use caseAincludes a use caseB, represented as a dashed arrow ôincludeằ
In use case modeling, the "include" relationship signifies that the behavior of one use case (B) is integrated into another (A), with A being the base use case and B the included use case The base use case relies on the included use case to function effectively, while the included use case can operate independently This relationship is similar to calling a subroutine in procedural programming For instance, in a use case diagram, if "Announce Lecture" is the base use case, then "Assign Lecturer" must also be executed whenever a new lecture is announced, involving the actor Professor in both cases Additionally, a single use case can include multiple other use cases, and it can also be included by various different use cases, necessitating careful management to avoid cyclic dependencies.
If a use caseBis in anôextendằrelationship with a use caseA, then
Acan use the behavior ofBbut does not have to Use caseBcan there- fore be activated byA in order to insert the behavior ofB inA Here,
Ais again referred to as thebase use caseandBas theextending use case Anôextendằrelationship is shown with a dashed arrow from the ôextendằ
In use case modeling, an "extend" relationship allows one use case to extend the functionality of a base use case, while both can operate independently For instance, in the example illustrated in Figure 3.8, the use cases "Announce Lecture" and "Reserve Lecture Hall" demonstrate this relationship, where reserving a lecture hall is optional when a new lecture is announced A use case can serve as an extending use case multiple times or be extended by several other use cases, provided that no cycles occur It's important to note that the arrow representing an "extend" relationship points towards the base use case, whereas an "include" relationship is indicated by an arrow that originates from the base use case and points to the included use case.
In use case modeling, a condition must be met for the base use case to execute the behavior of the extending use case, which can be specified for each "extend" relationship This condition is noted within curly brackets and linked to the respective "extend" relationship, preceded by the keyword "Condition:" For instance, in the use case "Announce Lecture," a lecture hall can only be reserved if it is available.
Furthermore, an exam can only be created if the required data has been entered.
By usingextension points, you can define the point at which the be- Extension point havior of the extending use cases must be inserted in the base use case.
The extension points are written directly within the use case, as illus- trated in the use caseAnnounce lecture in the example inFigure 3.9.
Within the use case symbol, the extension points have a separate sec-
Reserve lecture hall Announce lecture
Extension points are identified by the keyword "extension points" in a use case When a use case features multiple extension points, they can be linked to the corresponding "extend" relationship through specifications noted in a similar manner to conditions.
In the same way as for actors,generalizationis also possible between
Use cases can be organized into a parent-child hierarchy, where common properties and behaviors are grouped When a use case A generalizes another use case B, B inherits A's behavior and can choose to extend or modify it Additionally, B inherits all relationships from A, allowing it to utilize A's core functionality while determining which aspects to execute or alter An abstract use case cannot be executed directly; only the specific use cases derived from it are executable.
The use case diagram in Figure 3.10 illustrates the generalization of use cases, where the abstract use case "Announce event" transfers its properties and behavior to the specific use cases "Announce lecture" and "Announce talk." Due to an "include" relationship, both use cases are required to execute the behavior of the "Assign lecturer" use case Additionally, when a lecture is announced, an exam may also be announced simultaneously All use cases maintain a connection to at least one actor, specifically the Professor, fulfilling the prerequisite for accurate use case diagrams.
Example of generalization of use cases
Examples of Relationships
Generalization enables the consolidation of shared characteristics between the use cases "Announce Lecture" and "Announce Talk," eliminating the need to duplicate the modeling of the "include" relationship and the association with the professor.
In order to clarify the interactions between various relationship types in a use case diagram, we will examine the use case diagram illustrated in Figure 3.11 and explore several notable scenarios that arise within it.
Figure 3.11 Examples of relationships in a use case diagram
Use case A encompasses both use cases E and D, with actor O participating in all three scenarios It remains unspecified whether actor O represents the same user across these instances or if different users are involved.
• The use case H inherits from the use case C As use caseCis executed by the actorL, an actorLmust also be involved in the execution ofH.
The actorsNandMinherit fromL Therefore, both use casesCand
Hcan also be executed by an actorMorN.
• The use case J inherits from the use case B As a result of the inheri- tance relationship, an actorOis involved in the execution of use case
An association with O is also modeled for J directly, resulting in the involvement of two actors in the role of O during the execution of J It is important to note that these two actors may overlap.
Use case F inherits from use case G, resulting in the involvement of actor N in its execution Additionally, use case F directly associates with actor L Consequently, either actor L, actor M, or actor N, due to the inheritance relationship among actors L, N, and M, participates in the execution of use case F In cases where two actors N are involved, they may overlap.
• The use case I extends the use case F As use caseFinherits from use caseGand asIextends use caseG, this relationship is passed on toF.
IfGandIwere in anôincludeằrelationship, this relationship would also be passed on toFin the same way.
• The use case J extends the use case H This is as a result of the inher- itance relationships fromBtoJand fromCtoH.
Creating a Use Case Diagram
Identifying Actors and Use Cases
According to [30], there are two ways to identify use cases for prospec- tive system design:
2 Analysis of the expectations of future users
Requirements documents are generally natural language specifications that explain what the customer expects from a system They should doc-
3.7 Creating a Use Case Diagram 35 ument relatively precisely who will use the system and how they will use it If you follow the second approach for finding use cases, you must first identify the future users—that is, the actors To identify the actors that appear in a use case diagram, you must answer the following questions:
• Who uses the main use cases? Questions for identifying actors
• Who needs support for their daily work?
• Who is responsible for system administration?
• What are the external devices/(software) systems with which the sys- tem must communicate?
• Who has an interest in the results of the system?
Once you know the actors, you can derive the use cases by asking the following questions about the actors [27]:
• What are the main tasks that an actor must perform? Questions for identifying use cases
• Does an actor want to query or even modify information contained in the system?
• Does an actor want to inform the system about changes in other sys- tems?
• Should an actor be informed about unexpected events within the sys- tem?
In the iterative and incremental modeling of use cases, it is essential to begin with high-level requirements that align with the business objectives of the software This process involves refining these initial requirements until they are detailed enough to define the system's technical capabilities For instance, a primary requirement for a university administration system might state that it should facilitate student administration, which can then be further elaborated upon to specify its functionalities.
fine that new students should be able to register at the university and enroll for studies, that the students’ grades for different courses should be stored, etc.
Describing Use Cases
To maintain clarity in large use case diagrams, it is crucial to use short and concise names for each use case When the intention and interpretation of a use case are ambiguous, providing clear and concise descriptions becomes essential This ensures that readers fully understand the content, as lengthy or unclear descriptions may lead to skimming rather than thorough comprehension.
A generally recognized guideline for the length of use case descrip-
Alistair Cockburn outlines a structured method for detailing use cases, which typically spans 1 to 2 pages per case This approach emphasizes the importance of providing comprehensive information to effectively convey the purpose and functionality of each use case.
• Precondition: prerequisite for successful execution
• Postcondition: system state after successful execution
• Error situations: errors relevant to the problem domain
• System state on the occurrence of an error
• Actors that communicate with the use case
• Trigger: events which initiate/start the use case
• Standard process: individual steps to be taken
• Alternative processes: deviations from the standard process
Short description: An employee reserves a lecture hall at the university for an event.
Precondition: The employee is authorized to reserve lecture halls.
Employee is logged in to the system.
Postcondition: A lecture hall is reserved.
Error situations: There is no free lecture hall.
System state in the event of an error:
The employee has not reserved a lecture hall.
Trigger: Employee requires a lecture hall.
Standard process: (1) Employee selects the lecture hall.
(3) System confirms that the lecture hall is free.
Alternative processes: (3’) Lecture hall is not free.
(4’) System proposes an alternative lecture hall. (5’) Employee selects the alternative lecture hall and confirms the reservation.
Table 3.1 outlines the use case for reserving a lecture hall within a student administration system While the description is simplified, it sufficiently conveys the essential elements The standard and alternative processes can be further refined, and additional error scenarios may be explored For instance, it is feasible to reserve a lecture hall even when an event, such as an exam, is already scheduled, allowing for more efficient use of resources by minimizing the number of required exam supervisors In a practical application, the specifics would be informed by customer requirements and preferences.
Pitfalls
Unfortunately, errors are often made when creating use case diagrams.
Six examples of typical types of errors are discussed below For a more detailed treatment of this topic, see [39].
Even if it is often very tempting to model entire (business) processes or workflows in a use case diagram, this is an incorrect use of the diagram.
In the system model for the Student Office, it is essential that students are notified when their certificates are ready for collection This notification occurs only after the lecturer has sent the issued certificate to the student office, ensuring that all necessary steps are completed before the student can collect their certificate.
The use cases "Collect Certificate," "Send Notification," and "Issue Certificate" can be chronologically linked; however, they should not be depicted as interconnected in a use case diagram It is incorrect to associate these use cases through "include" or "extend" relationships.
The functionalities of each use case are distinct and do not overlap, requiring them to be utilized independently from one another.
Collect certificate ôincludeằ Send ôincludeằ notification
Figure 3.12 Incorrect excerpt of a use case diagram: modeling processes
Error 2: Setting system boundaries incorrectly
When creating a use case diagram, it's crucial to define the system boundaries clearly, as this can often be ambiguous Actors, representing users or external systems, should always be positioned outside these boundaries; if they are placed within, they become part of the system and should not be depicted as actors.
In the context of the Student Administration System, employees can be viewed in two ways: as integral components of the system or as external actors If employees are considered part of the system, they should not be modeled as actors; instead, an external entity must take that role Conversely, if employees are essential for executing use cases but are not part of the system, they should be represented as actors outside the system boundaries.
Incorrect excerpt of a use case diagram: incorrect system boundaries Student Administration
When identifying use cases, it is crucial to maintain consistency in their abstraction levels Avoid mixing high-level use cases, such as managing student data, with technical use cases like selecting a printer in the same diagram To prevent this mistake, adopt an iterative approach: start by creating a use case diagram focused on business objectives, and then refine these use cases to address the technical requirements.
Figure 3.14 Incorrect excerpt of a use case diagram: mixing ab- straction levels
Use cases, including those that are extended or included, should always be executable independently; if they can only function within another use case, they do not qualify as use cases and should not be represented as such Instead, their functionality should be integrated into the description of the primary use case For example, in the illustration of the use case "Issue Certificate," the individual subfunctions required for its execution are detailed While these subfunctions may be represented as use cases, some, like "Enter Data," may not hold significance as independent use cases.
To execute the use case of issue certificate, users must first log in with sufficient authorizations, as this functionality is not inherently included in the process.
Therefore, a reduced use case diagram, as shown inFigure 3.15(b), is sufficient The other information specified in Figure 3.15(a)must be specified in the use case description.
In use case scenarios involving two actors, both are essential for executing the use case, rather than one being optional For instance, in the use case diagram illustrated in Figure 3.16(a), the actors Assistant and Professor are depicted as necessary for the execution of the use case Issue Information, which may lead to confusion To clarify this relationship, we can introduce a new abstract actor, Research, to accurately represent the collaborative nature of the use case.
Associatefrom which the two actorsAssistantandProfessorinherit The actorEmployeeis now connected with the use caseIssue information(see
Incorrect excerpt of a use case diagram: functional decomposition
Error 6: Modeling redundant use cases
When modeling use cases, it can be appealing to develop distinct use cases for every possible scenario, as illustrated in Figure 3.17(a), where separate use cases for creating, updating, and deleting courses are presented This approach effectively highlights the various options for course management within the system In a concise use case diagram like Figure 3.17(a), detailing these distinctions is manageable and beneficial.
Incorrect excerpt of a use case diagram: incorrect associations
When modeling a real application, diagrams can quickly become overwhelming To address this issue, it is beneficial to group use cases with a common goal, such as course management This approach is illustrated in Figure 3.17(b), where the individual steps are detailed in the description of the standard process.
Figure 3.17Modeling redundant use cases
A Final Example
To conclude this chapter, we create a use case diagram that describes the functionality of the information system of a student office in accordance
Information system of the student office of a university with the following specification:
The student office plays a crucial role in managing key administrative tasks at a university, including matriculation, enrollment, and withdrawal from studies Matriculation specifically refers to the process of registering for academic programs.
Students collect their certificates from the student office, where an employee prints them Lecturers submit grading information to the student office, which automatically notifies students when their certificates are issued.
In the student office, employees are categorized into two distinct types: service employees (ServEmp), who focus solely on managing student data, and administration employees (AdminEmp), who handle various other tasks Despite their different roles, both ServEmp and AdminEmp are authorized to provide information.
• Administration employees issue certificates when the students come to collect them Administration employees also create courses When creating courses, they can reserve lecture halls.
To develop a use case diagram from a simplified specification, we begin by identifying the actors and their interrelationships Next, we outline the use cases and how they relate to one another Finally, we connect the actors to their respective use cases.
The textual specification identifies five potential actors: Lecturer, Student, employees categorized as ServEmp and AdminEmp, and the Notification System Since both types of employees share the common behavior of issuing information, it is logical to introduce a super-actor, StudOfficeEmp, from which ServEmp and AdminEmp can inherit The Notification System is considered separate from the student office, thus it is included as an additional actor Figure 3.18 provides a summary of these actors in the example.
In the next step, we identify the use cases (seeFig 3.19) In doing so, we determine which functionalities the student office must fulfill. ôextend ằ ôinclude ằ
The objective of the specification is to model the information system that supports student office employees, rather than the functionalities provided to students For instance, a use case like "Collect Certificate," which involves student interaction, is not included since it pertains to student services rather than employee support Conversely, the use case "Print Certificate" is relevant, but the printer is not listed as an actor because it is considered an integral part of the system being modeled.
The functions Register, Enroll, and Withdraw can be grouped under the use case Manage Student Data, as they are all performed by the actor ServEmp However, combining them would obscure the important distinction that matriculation involves enrollment for studies Therefore, we maintain the individual use cases and establish an "include" relationship between Register and Enroll While these three use cases share a common association with ServEmp, we introduce the abstract use case Manage Student Data, from which Register, Enroll, and Withdraw inherit This approach preserves the unique characteristics of each use case while highlighting their connection.
Lecturers can utilize the "Send Certificate" use case to notify students when a certificate is sent to the student office It is important to note that there is no separate "Notify Student" use case, as notifications only occur within the context of sending a certificate Additionally, the system includes other use cases such as "Issue Information," "Reserve Lecture Hall," and "Create Course," with "Reserve Lecture Hall" extending the "Create Course" use case, as illustrated in Figure 3.19.
We have updated our actor associations and use cases, resulting in two fewer actors than previously identified Notably, students have been excluded from our model, as they do not interact with the information system in the defined manner Additionally, the notification system has been removed, as it is now considered part of the student office functionality.
Finally, we need a meaningful description of the use cases.
Manage student data ôextend ằ ôinclude ằ
Figure 3.20 Use case diagram of the information system of the student office of a university
Table 3.2shows the description of the use casePrint certificateas an example.
Short description: On request from a student, an employee prints the student’s certificate for a course on paper.
Precondition: All data relevant for the certificate has been sent and the stu- dent has been graded.
Postcondition: Certificate is available to the student in printed form. Error situations: Printer is not working.
System state in the event of an error:
Trigger: Student requests printed certificate.
Standard process: (1) Student enters the student office and requests a certificate.
(2) AdminEmp enters the student’s matriculation number.
(4) AdminEmp enters the print command.
(5) System confirms that the certificate was printed.
(6) Certificate is handed over to the student.
(1’) Student requests certificate via e-mail.
(2-5) As above(6’) Certificate is sent by post.
Summary
A use case diagram illustrates a system's behavior from the user's perspective, highlighting its functionalities without delving into internal implementation details It clearly defines the system's boundaries, indicating what it can and cannot do Users, or actors, exist outside the system and interact with its functionalities represented as use cases The association between a use case and an actor is crucial, while generalization helps maintain compactness by allowing common properties to be extracted for both actors and use cases Additionally, use cases can leverage functionalities from other use cases through "include" and "extend" relationships Key notation elements are summarized in Table 3.3.
Boundaries between the system and the users of the system
Use case A Unit of functionality of the system
X Role of the users of the system
X participates in the execution of A
B inherits all properties and the entire behavior of A
Y inherits from X; Y participates in all use cases in which X participates
B extends A: optional incorporation of use case B into use case A
A ôinclude ằ A includes B: required incorporation of use case B into use case A
Table 3.3Notation elements for the use case diagram
A class diagram is utilized to represent the static structure of a system, illustrating its elements and the enduring relationships among them These elements, such as students, who possess attributes like a name and a matriculation number, remain constant over time, despite the specific instances of students and courses changing This approach effectively captures the fundamental aspects of a university's structure, ensuring relevance and validity for years to come.
The class diagram is the most widely used UML diagram, essential throughout various phases of the software development process Its level of detail varies, providing a conceptual view of the system in early project phases and defining the necessary vocabulary This vocabulary can be refined into a programming language leading up to implementation In object-oriented programming, the class diagram visualizes the system's classes and their interrelationships Its simplicity and popularity make it ideal for quick sketches, while it also supports automatic program code generation and serves documentation purposes.
Before exploring class diagrams, it's essential to understand object diagrams, which represent specific objects within a system at a given moment Classes serve as blueprints for defining these objects, while objects themselves are instances derived from these classes An object diagram effectively visualizes these instances, illustrating how they relate to the corresponding class diagram.
M Seidl et al., UML @ Classroom , Undergraduate Topics in Computer Science, DOI 10.1007/978-3-319-12742-2_ 4
Objects
A system comprises various unique individuals, which can include people, animals, plants, and inanimate objects For instance, in her IT Studies program, Helen Lewis participates in the Object-Oriented Modeling (OOM) lecture at the university In this context, Helen Lewis, IT Studies, and Object-Oriented Modeling are distinct entities within the university administration system, illustrating their interconnected relationships.
The object diagram illustrates three students: Helen Lewis, Mike Fox, and Paul Schubert, each with specific attributes such as first name, last name, date of birth, and matriculation number Helen Lewis, born on February 4, 1980, is enrolled in the "OOM" course during the Summer semester, which has a duration of 2.0 hours and takes place in Lecture Hall LH1, accommodating 400 seats Mike Fox, born on January 2, 1988, is studying "IPROG" in the Winter semester for 4.0 hours in Lecture Hall LH2, which has 100 seats Paul Schubert, born on April 11, 1984, is taking the "Databases" course in the Summer semester for 2.0 hours.
In UML, we depict concrete objects of a system and their rela- tionships (links) using object diagrams.Figure 4.1shows a small ob-
The object diagram features three student objects: Helen Lewis, Mike Fox, and Paul Schubert, each with their respective first names, last names, date of birth, and matriculation numbers The system includes three courses: Object-Oriented Modeling (oom), Introduction to Programming (iprog), and Databases (db) The iprog course is held in lecture hall lh1, while the db course takes place in lecture hall lh2, with no specified information for oom Among the students, Helen Lewis attends both the oom and iprog courses, Mike Fox is enrolled in iprog, and Paul Schubert is the only one attending the db course.
An object possesses a distinct identity along with various characteristics that provide detailed descriptions Typically, it does not exist in isolation; rather, it interacts and communicates with other objects, forming relationships known as links The characteristics of an object encompass its structural attributes and behaviors, represented through operations While specific values are assigned to the attributes in an object diagram, operations are usually not illustrated, as they are consistent across all objects of a class and are generally described at the class level.
In an object diagram, objects are represented as rectangles divided into compartments, with the first compartment displaying the format objectName:Class, where the object name is centered and underlined For instance, in the example provided, "helenLewis" and "doom" are object names, while "Student" and "Course" are class names It's important to note that the object name or class specification can be omitted; if only the class name is present, it must be prefixed by a colon, and if the class name is absent, the colon is also omitted An object without a name is referred to as an anonymous object, as illustrated in the various notational alternatives shown in the figures.
:Person firstName = "Max" lastName = "Miller" dob = 03-05-1973
Figure 4.2 Notation alternatives for objects
If the rectangle has a second compartment, this compartment con- tains the attributes of the object and the current values of these attributes
In our system, links are depicted as continuous lines connecting related objects, emphasizing the relationships between them While each object must have a unique name, it's possible for different objects to share identical attribute values For instance, if two individuals named Max Miller were born on the same day, they would be represented as distinct objects with unique identifiers, such as maxMiller1 and maxMiller2, despite having the same attribute values.
The values of attributes, such as a person's last name, can change over time without altering the individual's identity For instance, if Max Miller decides to change his last name, only the value of the attribute 'lastName' is affected, while the essence of the person remains the same.
The class diagram serves as a snapshot of objects at a specific moment, capturing their current state Over time, these objects can evolve and change, reflecting their dynamic nature The absence of certain objects in the diagram does not imply their non-existence; rather, it indicates that these unrepresented objects are not relevant at that particular time.
Many individuals that appear in a system have identical character-
In programming, transitioning from individual objects to classes simplifies the representation of similar entities, such as people, courses, and lecture halls For instance, every person has a first name, last name, and date of birth, while students possess a matriculation number Courses are characterized by a name, duration in hours, and the semester they occur in, and lecture halls are defined by their seating capacity By utilizing classes, we can efficiently model these attributes collectively, avoiding the complexity and maintenance challenges that arise from detailing each object separately.
Classes
Notation
In a class diagram, a class is depicted as a rectangle divided into several compartments The top compartment features the class name, typically starting with a capital letter and displayed in bold, centered text (e.g., Course in Figure 4.4).
Class names should be singular nouns that accurately reflect the class's purpose using terminology relevant to the application domain The second compartment of the class rectangle includes its attributes, while the third compartment contains additional details.
Course name semester hours getCredits() getLecturer() getGPA()
+ getCredits(): int + getLecturer(): Lecturer + getGPA(): float + getHours(): float + setHours(hours: float): void
Figure 4.4Representation of a class and its characteristics
Class diagrams feature compartments that detail the operations and attributes of a class, typically left-justified and optional The level of detail varies based on the software development phase being analyzed For instance, Figure 4.4(a) lacks specifics for the class Course, while Figure 4.4(b) offers a more detailed view, highlighting three attributes and three operations Figure 4.4(c) further elaborates with type information and visibility, crucial for implementation and automatic code generation The absence of certain information in a diagram does not indicate its non-existence; rather, it reflects its current irrelevance or the need to maintain diagram simplicity Attributes and operations are usually identified by names that adhere to naming conventions, starting with a lowercase letter.
Attributes
Figure 4.5 shows the syntax of attributes An attribute has at least a
An attribute is defined by its name, with an optional type specification following it, indicated as "name: Type." The attribute types can include primitive data types like integers and strings, as well as composite data types such as dates and enumerations.
In this article, we explore user-defined classes, specifically focusing on the attribute definition using the syntax `name: String`, which establishes the attribute `name` with the type `String` Further examples of attribute types are illustrated in Figure 4.6 Additionally, we will examine the optional multiplicity specification in greater detail in the following section.
Syntax of the attribute specification
To define adefault valuefor an attribute, you specify= Default , where Default value
In a system, a default value or expression is used when a user has not explicitly set an attribute value, ensuring that no attribute remains without a value For instance, when a new user is created, a default password, such as "pw123," is assigned, which remains valid until changed The system also requires specific attributes, including first name, last name, date of birth, address (which must be unique and ordered), and a read-only social security number.
/age: int password: String = "pw123" personsCounter: int
Person getName(out fn: String, out ln: String): void updateLastName(newName: String): boolean getPersonsCounter(): int age = now.getYear() - dob.getYear()
You can define additional properties of an attribute using curly brackets For instance, the property {readOnly} indicates that the attribute's value is immutable once it has been set.
Figure 4.6, the social security numberssNois an attribute that must not be changed Further properties will be introduced in the next section within the description of multiplicity specifications.
A forward slash before an attribute name signifies that the attribute's value is derived from other attributes, such as a person's age, which can be calculated from their date of birth In Figure 4.6, a note illustrates a calculation rule for determining age Depending on the development tool, these notes may be expressed in natural language, programming language, or pseudocode Additionally, an optional visibility marker (+, –, #) can be used to indicate the accessibility of the attribute.
∼) in front of an attribute name or operation name as shown inFig- ure 4.4(c)is discussed in detail on page 58.
Multiplicities
The multiplicity of an attribute defines the number of values it can hold, allowing for the creation of arrays similar to those in programming languages This concept is represented as an interval enclosed in square brackets.
In a class diagram, multiplicities are indicated using the format [minimum maximum], where minimum and maximum are natural numbers representing the interval's lower and upper limits, respectively The minimum value must be less than or equal to the maximum An asterisk (*) signifies no upper limit For example, the class Person in Figure 4.6 features an attribute address: String [1 *], indicating that a person can have one or more addresses If minimum and maximum are the same, only the value is needed, such as [5], which means exactly five values The notation [*] is equivalent to [0 *] By default, if no multiplicity is specified, it is assumed to be 1, indicating a single-valued attribute Figure 4.7 summarizes the valid notation for multiplicities.
Syntax of the multiplicity specification [ Min Max ]
If an attribute can adopt multiple values, it makes sense to specify whether the attribute is:
• A set (no fixed order of elements, no duplicates)
• A multi-set (no fixed order of elements, duplicates possible)
• An ordered set (fixed order, no duplicates)
• A list (fixed order, duplicates possible) You can make this specification by combining the properties{non-
In data modeling, attributes can be classified as unique or non-unique, and as ordered or unordered For instance, the attribute "address" is defined as String [1 *] {unique, ordered}, indicating that each address for a person must be unique and that the order of these addresses is significant This means that the first address listed may represent the individual's primary residence.
Operations
Operationsare characterized by their name, their parameters, and the
When an operation is invoked in a program, it executes the behavior assigned to it, which corresponds to a method declaration in programming languages.
The syntax for operation specifications or function declarations is defined but not implemented, highlighting that class diagrams are inadequate for detailing object behavior, as they only represent operation signatures without illustrating their actual implementations To effectively depict how these operations are implemented, UML provides specialized behavior diagrams, such as activity diagrams, which are discussed in Chapter 7.
In a class diagram, the operation name is accompanied by a list of parameters in parentheses, which can be empty Each parameter is represented like an attribute, with the parameter name being the only mandatory detail Additional information such as type, multiplicity, default value, and properties like ordered or unique are optional.
The optional return value of an operation is defined by its return type For example, in the class Person, the operation updateLastName(newName: String): boolean takes a parameter called newName and returns a boolean indicating the success of the operation.
Name, has the typeStringand specifies the new name for a person The return value has the typeboolean Iftrueis returned, the renaming was successful, otherwisefalseis returned.
If required, you can also prepend a direction to the parameter name Input and output parameters
This direction can have one of the following values:in,out, orinout(see
The parameter's value indicates its role as either an input, output, or both When a parameter is designated as "in," it signifies that a value is required during the operation Conversely, the "out" direction indicates that the parameter will hold a new value after the operation is completed.
If an operation should have multiple return values rather than just one, you can express this using multiple parameters with the directionout.
The specification ofinoutindicates a combined input/output parameter.
In programming, if no direction is specified, the default value is 'in' For instance, in the operation getName(out fn: String, out ln: String), both parameters are designated with the 'out' direction When this operation is utilized in a program, such as by calling getName(firstName, lastName), it effectively outputs the results for the specified parameters.
In the Class Diagram, the variables firstName and lastName function similarly to those in imperative programming languages Upon successful execution of the getName operation, the firstName variable holds the object's first name, while the lastName variable contains the object's last name for instances of the Person type.
Syntax of the parameter specification
Name : Type Multiplicity out inout in
Visibility Markers
Thevisibilityof attributes and operations specifies who is and who is not
Visibility in UML defines who can access attributes and operations within a class Attributes marked as private are only accessible by the object itself, while public attributes can be viewed by anyone Protected attributes are accessible only to the class and its subclasses, and package attributes can only be accessed by classes within the same package The visibility of an operation determines who can utilize its functionality It's important to note that the interpretation of visibility can differ across various programming and modeling languages, despite having similar terminology.
Visibilities are used to realizeinformation hiding, an important con-
Information hiding is a fundamental concept in computing that safeguards an object's state by marking its attributes as private, preventing unauthorized access Access to this state is restricted and can only occur through a well-defined interface, typically using operations that are declared public.
Class diagrams may include only the externally visible attributes and operations of a class, often omitting private attributes and operations While these private elements are crucial for the internal implementation of the class, they are not necessary for its external use.
Therefore, whether or not attributes and operations marked asprivate are specified depends on the intention behind and the time of creation of the class diagram.
In programming, access modifiers define the visibility of class members: public (+) allows access from any class, private (-) restricts access to the defining object only, protected (#) permits access from the same class and its subclasses, and package (∼) enables access for classes within the same package.
Class Variables and Class Operations
Attributes are typically defined at the instance level, meaning that when an object is created in a programming language, memory is allocated for each attribute These attributes are commonly known as instance variables or instance attributes.
In an object-oriented programming context, instance variables such as lastName and dob are used to store attributes of a class, like Person For example, if person1 is an instance of the Person class, person1.lastName can be accessed to retrieve the individual's last name However, the date of birth (dob) is private, meaning it cannot be directly accessed To obtain person1's date of birth, the method person1.getDob() must be invoked, which can only be executed if the instance person1 has been created beforehand This operation can utilize all publicly accessible instance variables.
In contrast to instance variables, class variables are created only Synonyms:
• Static attribute once for a class rather than separately for every instance of this class.
Static attributes, also known as class attributes, include counters for class instances and constants like π In class diagrams, these static attributes are indicated by underlining, similar to static operations.
Static operations, also calledclass operations, can be used if no instance of the corresponding class was created Examples of static operations Synonyms:
• Static operation are mathematical functions such assin(x)or constructors Construc- tors are special functions called to create a new instance of a class The method invocationPerson.getPCounter()uses the static opera-
In object-oriented programming, attributes and operations typically refer to instance attributes and instance operations, as illustrated by the getPCounter() operation in Figure 4.10, which is invoked directly through the class rather than an instance This convention is consistently followed throughout this book.
UML to Java class Person { public String firstName; public String lastName; private Date dob; protected String[] address; private static int pCounter; public static int getPCounter() {…} public Date getDob() {…}
Associations
Binary Associations
Abinary associationallows us to associate the instances of two classes
Binary association with one another The relationships are shown as edges (solid line) be- tween the partner classes involved The edge can be labeled with the
A c B name of the associationoptionally followed by thereading direction, a small, black triangle The reading direction is directed towards one end annaMiller:Professor frankStone:Professor helenLewis:Student paulSchubert:Student mikeFox:Student
In a class diagram, a binary association illustrates the relationship between two entities, guiding the reader on how to interpret the association name For instance, as demonstrated in Figure 4.11, the reading direction signifies that professors deliver lectures to students, emphasizing the one-way nature of this relationship.
If the edge is directed, that is, at least one of the two ends has an open Navigability
Navigability in object-oriented design refers to an object's ability to recognize and access its partner objects' attributes and operations This concept is distinct from reading direction; for example, while professors deliver lectures to students, it is the students who can access the visible characteristics of the professors Conversely, professors do not have access to the attributes of the students attending their lectures, as they do not possess knowledge of them.
A non-navigable association end is indicated by the explicit specifi- Non-navigability
In UML class diagrams, an association end marked with an "X" indicates that the associated class cannot access the attributes and operations of the other class, including public ones While bidirectional edges without arrowheads or "X" do not specify navigation direction, bidirectional navigability is generally assumed The navigation direction serves as a guideline for implementation in object-oriented programming, where associations are represented as references to associated objects Additionally, associations can be depicted as attributes with the appropriate multiplicity, where the attribute type corresponds to the class of the associated objects, maintaining the same semantics as a navigable association end.
Java class Professor {…} class Student { public Professor[] lecturer;
The article presents two class diagrams illustrating the student-professor relationship: (a) one that models the relationship explicitly as an association, and (b) another that represents it as an attribute within the Student class The preferred diagram, shown in Figure 4.12(a), clearly visualizes the relationship between the classes, making it immediately apparent In contrast, Figure 4.12(b) obscures this association, requiring readers to interpret the type information of the lecturer attribute to recognize the connection between Student and Professor.
Examples of multiplicity specifications in binary associations
Multiplicity in associations is defined using an interval format, expressed as minimum maximum, indicating the number of objects that can be linked to a single object on the opposing side The minimum and maximum values can be natural numbers or an asterisk (*), which signifies no restrictions If the minimum and maximum values are the same, the notation can be simplified by omitting the dots.
In binary associations, the notation 0 ∗ is equivalent to ∗ As illustrated in Figure 4.13, a lecturer can issue zero, one, or multiple assignments, while each assignment is linked to exactly one lecturer, emphasizing that no assignment exists without a lecturer Additionally, Figure 4.13 highlights that a lecturer is required to give at least one lecture, and conversely, each lecture must be presented by at least one lecturer.
In Figure 4.13(c), it is illustrated that an examiner can evaluate any number of individuals (zero or more), while an examinee can be assessed by multiple examiners The model also allows for the possibility of individuals examining themselves; however, if self-examination is not permitted, specific constraints need to be established.
In association relationships, it is important to label the ends with role names to clarify the involvement of objects The term "Arolede- Role" describes the specific role an object plays within this relationship For example, in the association illustrated in Figure 4.13(c), the Person takes on the roles of either examiner or examinee.
To express that an object of classAis to be associated with an object xor constraint
In class diagrams, you can establish an exclusive or (xor) constraint to indicate that an object can belong to either class B or class C, but not both simultaneously This mutual exclusivity can be visually represented by connecting the two associations with a dashed line labeled {xor} For instance, an exam can be conducted in either an office or a lecture hall, but it cannot occur in both locations at the same time.
Figure 4.14Examples of associations with xor constraints
N-Ary Associations
If more than two partner objects are involved in a relationship, you can
An n-ary association is depicted with a hollow diamond at its center, connecting to all relationship partners through undirected edges The association's name is placed adjacent to the diamond, and while there are no navigation directions for n-ary associations, multiplicities are still defined.
Multiplicity in n-ary associations and role names allows for the specification of how many instances of a role or class can be linked to a specific (n−1)-tuple of objects from other roles or classes This definition is crucial for understanding the relationships and constraints within a given model.
Figure 4.15 illustrates the relationship between the classes Lecturer, Student, and Exam, highlighting their multiplicities A specific student may take one specific exam either without a lecturer or with exactly one lecturer, which is represented by the multiplicity 0 1 for the Lecturer class Conversely, a single exam with one lecturer can be taken by multiple students, and one student can receive grades from one lecturer for numerous exams, indicated by the multiplicity * Notably, the model prohibits multiple lecturers from grading the same student for the same exam.
Example of n-ary (here ternary) association
Using binary associations to represent a ternary relationship can lead to a model with a different interpretation For instance, in the representation depicted in Figure 4.16, multiple lecturers can grade an exam However, the ternary association illustrated in Figure 4.15 distinctly indicates which lecturer a student passed a specific exam with, a clarity that is absent in Figure 4.16.
For example, with the model shown inFigure 4.15, it is possible to express that students1took the exame1with lecturerl1and that student
Figure 4.16 versus example with two binary associations s2 took the same exame1with lecturerl2 With the model shown in
In Figure 4.16, it is indicated that students s1 and s2 participated in exam1, which was evaluated by two examiners, l1 and l2 However, this model does not specify which lecturer is responsible for grading each student.
An alternative to the ternary association illustrated in Figure 4.15 is the introduction of an additional class linked to the original classes through binary associations, as shown in Figure 4.17 This new model allows for the possibility of a student being graded multiple times for the same exam, a scenario not permitted in the model presented in Figure 4.15.
Figure 4.17 versus example with additional class
Association Classes
An association class allows you to assign attributes or operations to the relationship between multiple classes instead of just to a single class This is achieved by representing the association class as a distinct class itself, which enhances the modeling of complex relationships in object-oriented design.
An association, represented by a dashed line, can be either binary or n-ary An association class uniquely combines the characteristics of both a class and an association within a single language construct In diagrams, the class and association of an association class share the same name, though it's not mandatory to name both For example, in Figure 4.18, the association classes are labeled as Enrollment and Grade.
StudyProgram binary association class ternary association class
Grade can also have associations with other classes InFigure 4.18, the asso- ciation classGrade, which contains information about a student’s grade for a specific exam, is associated with the classCertificate.
In modeling the relationship between students and study programs, it is crucial to recognize that an association class cannot be substituted with a standard class linked to the original two classes For instance, a student must enroll in at least one study program and maintain one enrollment per chosen program, while any number of students can enroll in a specific study program.
Figure 4.19(b)shows the attempt to model this situation with only
“normal” classes An enrollment is assigned to precisely one student
Attempt to model an as- sociation class with a
“normal” class and cor- responding relationships
StudyProgram and precisely one study program, while one study program is related to any number of enrollment objects A student has at least one enrollment.
The current requirements have been satisfied; however, a closer inspection of Figure 4.19(b) reveals that a student may have multiple enrollments in the same study program, which is unintended Conversely, Figure 4.19(a) correctly illustrates that a student can enroll in a specific study program only once.
To allow duplicates in an association class, at least one association end must be marked as {non-unique}; otherwise, the default assumption is {unique} For instance, in Figure 4.20(a), a student is restricted to a single exam meeting to discuss their written exam results Conversely, Figure 4.20(b) illustrates a more accommodating approach, where the {non-unique} designation permits multiple exam meetings for the student.
Figure 4.20Example of {unique} and{non-unique} association ends
Aggregations
Shared Aggregations
In the UML standard, ashared aggregationhas intentionally informal
Shared aggregation in A B semantics indicates a weak connection between parts and a whole, allowing for the independent existence of parts This concept accommodates multiple elements being part of various aggregations simultaneously, which can be represented as a directed acyclic graph For instance, in a lab class scenario, any number of students can be involved, but each student is restricted to participating in only one lab class Conversely, a study program can consist of zero or more courses, with each course being linked to at least one study program.
Compositions
The use of acompositionexpresses that a specific part can only be con-
A B tained in at most one composite object at one specific point in time.
In a composite structure, a maximum multiplicity of 1 at the aggregating end signifies a strong existence dependency between composite objects and their components This means that if the composite object is removed, all associated parts are also deleted For example, a lecture hall is an integral part of a building, illustrating this dependency, as the lecture hall cannot exist independently of the building.
If a building is demolished, its associated lecture hall ceases to exist as well In contrast, a beamer, linked to the lecture hall through a composition, can exist independently The multiplicity of 0 1 at the aggregating end indicates that the beamer can be removed from the lecture hall without being affected by its absence.
If the beamer is located in the lecture hall and the lecture hall ceases
When a building is demolished, its components, such as the beamer, also cease to exist Conversely, if the beamer is taken out of the lecture hall before the building is torn down, it remains intact and continues to exist.
A shared aggregation differs from an association by explicitly visualizing a "part of" relationship In contrast, a composition signifies a stronger existence dependency between a composite object and its parts, making them non-interchangeable Compositions are typically employed when the parts are physically embedded in the composite object or are exclusively visible to it If the parts are referenced externally, a shared aggregation may suffice Additionally, when using a composition, deleting or copying the composite object also results in the deletion or copying of its parts.
Generalizations
Inheritance
The generalization relationship expresses that the characteristics (at-
Inheritance allows subclasses to inherit attributes and operations from their superclass, which establishes a generalization relationship This process is commonly known as inheritance in object-oriented programming.
In an "is a" relationship, each instance of a subclass is also considered an indirect instance of its superclass The subclass inherits all instance and class attributes, as well as operations from the superclass, unless they are marked as private Additionally, the subclass can introduce its own attributes and operations and establish independent relationships Consequently, both subclass-specific and superclass-originating operations can be executed directly on a subclass instance.
A generalization relationship is represented by an arrow with a hol-
In object-oriented programming, a superclass serves as an umbrella term for its subclasses, such as the relationship from Student to Person To prevent direct instances of the Person class, it is designated as an abstract class using the keyword {abstract} Consequently, only its non-abstract subclasses can be instantiated, which will be further explored in Section 4.7.
Person name address dob ssNo
Figure 4.24 Class diagram with generalization
The generalization relationship, often referred to as an "is a" relationship, illustrates the concept of transitivity in classifications For instance, every student qualifies as a person, and similarly, all research associates and administrative employees are categorized as employees Consequently, through this transitive property, every administrative employee is also recognized as a person In the context of object-oriented programming, classes represent types, where subclasses and superclasses correspond to subtypes and supertypes.
UML supports multiple inheritance, enabling a class to inherit from multiple superclasses For instance, a tutor can simultaneously be classified as both a university employee and a student This results in single inheritance forming an inheritance hierarchy, while multiple inheritance leads to a directed acyclic inheritance graph.
Classification
Classification denotes the "instanceOf" relationship between an object and its corresponding class In numerous object-oriented programming languages, an object is typically a direct instance of only one specific class.
In contrast, UML allowsmultiple classification With multiple classifi-
Multiple classification allows an object to belong to multiple classes independently, without requiring these classes to be linked through an inheritance relationship Unlike multiple inheritance, this approach does not create a new class that inherits attributes from the involved superclasses.
Employees can be categorized based on their roles, such as researchers or administrators, and their funding sources, whether through the university or specific projects Multiple classification allows an employee to belong to various classes, inheriting the traits of each The generalization relationships are organized into two groups, with the sets Job and Financing forming generalization sets that encompass their respective subclasses.
Generalization set according to multiple independent criteria Generalization sets can be described more precisely by the following constraints:
In a generalization set, objects can either be part of overlapping or disjoint subclasses In an overlapping generalization set, an object can belong to multiple subclasses at the same time, while in a disjoint generalization set, an object can only belong to one subclass at most.
In a complete generalization set, every instance of the superclass is required to be an instance of at least one subclass, ensuring full coverage Conversely, in incomplete generalization sets, this requirement is not necessary, allowing for instances of the superclass that may not belong to any subclass.
There are four possible combinations for categorizing employee relationships: complete and overlapping, incomplete and overlapping, complete and disjoint, and incomplete and disjoint By default, the incomplete and disjoint classification is applied unless specified otherwise For instance, an employee can either belong to the research or administrative personnel, but not both simultaneously Additionally, funding for the employee may come directly from the university, a project, both, or through an unspecified method, such as a scholarship.
Abstract Classes vs Interfaces
Classes that cannot be instantiated themselves are modeled asabstract Abstract class
Abstract classes serve as blueprints for their subclasses, lacking any instantiable objects themselves They emphasize shared characteristics among subclasses, ensuring a coherent structure in object-oriented programming.
In the context of generalization relationships, multiple classification is exemplified by abstract classes, which can have their operations labeled as abstract An abstract operation does not provide any implementation but mandates that concrete subclasses must implement it Conversely, non-abstract operations inherit their behavior to all subclasses, ensuring consistent functionality across the hierarchy.
Abstract classes and operations are denoted in italic font or by the keyword {abstract} preceding their names For manually created class diagrams, it is advisable to use the latter notation, as italic handwriting can be challenging to read.
Figure 4.27 Notation for abstract classes
In the example inFigure 4.28, the class Personis abstract Hence, there cannot be any instances ofPersonitself but there can be instances of the specific subclassesEmployeeandStudent.
Similarly to the abstract class, aninterfacealso does not have an im- Interface plementation or any direct instances An interface represents a contract.
Classes that implement an interface commit to delivering the behaviors defined by that interface Unlike the relationship between an abstract class and its subclasses, there is no "is a" relationship required between an interface and the implementing classes It's important to note that interfaces do not provide implementations for their operations.
An interface in programming is defined similarly to a class, but it includes the keyword "interface" before its name A dashed inheritance arrow with a hollow triangular arrowhead indicates that a class implements the interface, while a dashed arrow with an open head and the keyword "use" signifies that a class utilizes the interface For example, the classes Person and Course implement the Printable interface, requiring them to provide a print() operation that varies by class For Course, the print() method outputs the name and number of hours, whereas for Person, it prints the name and address The Student class redefines the print() method, enhancing the behavior inherited from Person by including the matriculation number In contrast, the Employee class may not need to override print() if the existing implementation in Person suffices Consequently, the Printer class can handle any class that implements the Printable interface, allowing for unique print() implementations without altering the Printer class itself.
Example of an interface ôinterfaceằ ôuseằ
+ name: String + address: String + dob: Date + ssNo: int
Data Types
In programming, attributes, parameters, and return values are defined by types, which specify the concrete forms they can take, distinguishing between classes and data types For instance, a person's name is categorized as a typeString Understanding the difference between classes and data types is essential for effective coding and data management.
Instances of data types are also referred to as theirvalues In contrast to instances of classes (objects), values do not have their own identity.
When two values are identical, they cannot be distinguished from one another For instance, in the context of a classBook, various instances represent different copies of the bookUML@Classroom, which can be uniquely identified despite having identical attributes In contrast, distinct occurrences of a value, such as the number 2, remain indistinguishable This lack of differentiation is particularly noticeable when using comparison operations, such as the equality operator (==) in Java.
When comparing two integer variables with the same value, the comparison operation yields true However, when using the equality operator (==) to compare two different objects, the result is generally false, even if all their attributes hold identical values.
In UML, data types are represented similarly to classes, with the distinction that their names are prefixed by the keyword "datatype." As illustrated in Figure 4.29(b), data types can possess an internal structure characterized by attributes.
In UML, there are also two special forms of data types, namely primitive data types and enumerations.
Primitive data types lack internal structure and are represented in UML by four predefined types: Boolean, Integer, Unlimited Natural, and String User-defined primitive data types are recognized by the keyword "primitive." These data types can also have operations performed on their values.
Enumerations are data types whose values are defined in a list Enumeration
The enumeration AcademicDegree is defined in Figure 4.29(c) and includes all known academic degrees within our system Attributes of the type AcademicDegree can take literal values such as bachelor, master, and PhD These values are referred to as literals.
Figure 4.29Examples of data types
User -defined types play a crucial role in defining attributes and operations, as illustrated in the syntax descriptions found in Figures 4.5 and 4.8 Revisiting the type definitions from Figure 4.29, we can see their application in various attribute definitions, such as weight defined as Float, dob as Date, and title as AcademicDegree.
Creating a Class Diagram
Generalizations
The following sentences strongly indicate a generalization relationship:
In a university setting, employees are categorized into two main groups: research personnel and administrative personnel Some research associates also take on teaching responsibilities, earning the title of lecturers To represent this structure, we can conceptualize the class of Employee as an abstract entity that encompasses both categories.
Associations and Aggregations
To finalize the class diagram, it is essential to incorporate associations and aggregations along with their respective multiplicities The classes Lecturer and Course are connected through the association "teaches." Additionally, an employee assumes the role of a dean, overseeing the faculty.
+ ssNo: int + name: String + email: String + counter: int
The identified generalization relationships involve multiple institutes, where research associates are assigned to an institute, indicating their membership While a composition model is inappropriate due to the lack of existence dependency between Employee and Institute, a shared aggregation effectively represents the parts-whole relationship Additionally, the participation of research associates in projects is quantified by the association class Participation, which details the relationship between the project and the research associate, including the number of hours contributed The complete class diagram for this scenario is illustrated in Figure 4.33.
The resulting model is not unique, as it varies based on the intended application and the modeler's style For instance, if the goal was to generate code, the interfaces would likely be designed with more precision and differentiated visibilities It is subjective whether "Lecturer" is treated as a separate class while "dean" is viewed as a role Alternatively, "Lecturer" could have been defined as a role at the end of the association "teaches," which connects the "ResearchAssociate" and "Course" classes.
Class diagram of the in- formation system of a university
+ name: String + id: int + hours: float
+ ssNo: int + name: String + email: String + counter: int
+ name: String + start: Date + end: Date leads teaches
Code Generation
Class diagrams are often created with the intention of implementing
Forward engineering in object-oriented programming languages allows for the automatic translation of class diagram concepts into languages like Java, C#, and C++, often needing minimal manual adjustments Additionally, class diagrams serve as effective documentation tools for existing program code, enhancing clarity and understanding.
Reverse engineering tage that the relationships between classes are represented graphically. There are a number of tools for reverse engineering program code into class diagrams automatically.
Data modeling shares concepts with class diagrams, particularly through the use of entity-relationship diagrams (ER diagrams), which resemble class diagrams despite differing notations Both diagrams illustrate system elements—classes or entities—and their relationships, characterized by attributes However, they differ significantly in focus: ER diagrams detail database elements, while class diagrams outline the implementation of systems in object-oriented programming languages In ER diagrams, key attributes can be defined to identify table entries, a feature not directly applicable to class diagrams, where each object is uniquely identified by its own attributes.
ID In contrast, the specification of behavior, which is possible in the class diagram through operations, is not supported in the ER diagram.
To effectively address the problem at hand, it is advisable to select the most suitable diagram type For instance, the relationship between a class diagram (refer to Fig 4.34) and its corresponding Java code (see Fig 4.35) is exemplified in the following example.
Figure 4.34 Class diagram from which code is to be generated
In coding, both abstract and concrete classes can be directly translated with their attributes and operations Associations are represented as attributes within the code, and the multiplicity of an association end is indicated by the type of the attribute.
In a class diagram, when the multiplicity exceeds one, we can utilize arrays, similar to how we managed courses Alternatively, we can implement generic data types, such as the Java Collection type, which eliminates the need to specify the size at initialization, unlike arrays.
To ensure effective implementation of navigation directions, it's crucial to accurately interpret the navigation information indicated by arrowheads at the association ends These arrowheads signify which classes need to be aware of other classes, and this relationship is established through the attributes that define the association ends.
Association classes and n-ary associations are not directly available in common programming languages like Java, necessitating their simulation In our example, we implement the association class Support using a hash table, a data structure that organizes elements as (key, data) pairs This allows for efficient retrieval of related data when the unique key is known.
In this article, we have outlined the structure of elements and their interrelationships, but we have yet to address behavior For instance, the operation getAcctNo() simply returns an employee's account number, with its method body automatically generated as a getter that encapsulates access to a corresponding variable However, for operations requiring calculations, automatic implementation is not feasible UML provides additional diagrams for modeling behavior, which will be explored in subsequent chapters To summarize, Table 4.2 highlights the key concepts of class and object diagrams.
} class Student extends UniversityMember { public int matNo; public CourseExecution [] cC; // completed c
} class Employee extends UniversityMember { private int acctNo; public CourseExecution [] cE; // supported c public int getAcctNo { return acctNo; }
} class CourseExecution { public int year; public ESemester semester; public Student [] student; public Course course; public Hashtable support;
// Key: employee // Value: (role, hours)
} class Course { public int courseNo;
Enumeration ERole { lecturer; tutor; examiner;
Figure 4.35Java code that can be gen- erated automatically fromFig 4.34
Notation elements of the class and object diagrams
Description of the structure and be- havior of a set of objects
A Class that cannot be instantiated
Relationship between classes: navi- gability unspecified (a), navigable in both directions (b), not navigable in one direction (c)
Relationship between N (in this case
More detailed description of an asso- ciation xor relationship
B C An object of A is in a relationship with an object of B or with an object of C but not with both
Existence-dependent parts-whole re- lationship (A is part of B; if B is deleted, related instances of A are also deleted)
Parts-whole relationship (A is part of B; if B is deleted, related instances of
Generalization A B Inheritance relationship (A inherits from B)
Every object or system experiences a limited number of distinct states throughout its lifetime A state machine diagram effectively models these potential states, illustrating how transitions occur in response to specific events and detailing the behavior exhibited by the system or object in each state.
A lecture hall can exist in two states: free or occupied When a lecture begins, the hall transitions from free to occupied After the lecture concludes and the hall is vacated, it returns to its free state.
Figure 5.1 State machine diagram of a lecture hall (simplified presentation)
The state machine diagram, rooted in David Harel's work and finite automata concepts, is a crucial tool in UML It categorizes state machines into two types: behavior state machines and protocol state machines This book focuses exclusively on behavior state machines, commonly known as state machine diagrams or state charts, which are widely used in practice.
A state machine diagram, like any other diagram, focuses solely on the relevant aspects of a system for its intended purpose For instance, when modeling the various states of a lecture hall for requirement gathering or documentation, a simplified model, such as the one illustrated in Figure 5.1, may be adequate.
However, if you are already in a late phase of the development process, a representation that is close to code, as shown inFigure 5.2, is ben-
M Seidl et al., UML @ Classroom , Undergraduate Topics in Computer Science, DOI 10.1007/978-3-319-12742-2_ 5
The State Machine Diagram illustrates a class named LectureHall, which features an attribute called free that can be either true or false When the occupy operation is invoked, it sets the free attribute to false, transitioning the lecture hall object to the occupied state, as represented in Figure 5.1 The events depicted in the state machine diagram correspond to the operations associated with the LectureHall class.
State machine diagram, class diagram, and pseu- docode of a lecture hall
+ occupy() + release() class LectureHall { private boolean free; public void occupy() { freese;
} public void release() { free=true;
} } free= true occupy() release() free= false
States and State Transitions
A state machine diagram is a graph withstatesas nodes andstate tran- State
In the diagram, a state is represented as a rounded rectangle labeled with its name, indicating that when an object is in that specific state, it can execute all internal activities defined for it If internal activities are specified, the state is divided into two compartments: the upper compartment displays the state name, while the lower compartment lists the internal activities, which may consist of multiple actions.
S entry/Activity( ) do/Activity( ) exit/Activity( )
We will present the relationship between activities and actions in detail in Chapter 7, which looks at activity diagrams.
In a state, three key activities can be modeled based on specific triggers: an entry activity that executes when an object enters the state, an exit activity that runs upon leaving the state, and a do activity that occurs continuously while the object remains in the active state Each activity is clearly identified with a forward slash prefix to distinguish it as an activity.
In the reservation system illustrated in Figure 5.3, a lecture hall transitions between two states: free and occupied When in the free state, the system displays the lecture hall as available Once occupied, the system executes the Save user reservation activity, recording the occupant's name, and updates the display to indicate that the lecture hall is now occupied When the lecture hall is no longer needed, it is released, reverting to the free state, at which point the Delete user reservation activity is executed This process ensures accurate tracking of the lecture hall's status and user reservations.
Figure 5.3 State machine diagram of a lecture hall with internal activities
The change from one state to another is referred to as a state tran- sition or simplytransition A transition is represented with a directed Transition e[g]/A
The S T edge represents a transition in a directed graph, indicated by an arrowhead that shows the direction of the transition The starting point of this transition is known as the source state, while the endpoint is referred to as the target state Additionally, various properties can be defined for a transition, enriching its description and functionality.
• The event (also called “trigger”) that triggers the state transition
• The guard (also called “guard condition” or simply “condition”) that enables the execution of the transition
• Activities (also called “effects”) executed during the change to the target state
Events are external stimuli that can initiate a state transition within a system When a specified event occurs, a guard, which is a boolean expression, is evaluated to determine if it is true or false If the guard evaluates to true, the current state's activities are halted, any necessary exit activities are performed, and the transition occurs During this transition, any activities associated with it are executed Conceptually, a transition does not require time, meaning the system is always in a state rather than in transition, and the activities linked to a transition should not demand significant time.
When a guard evaluates to false, the event is not consumed, and no state transition occurs Even if the guard later evaluates to true, the event must be triggered again for the transition to take place.
In the absence of a guard at a transition, the default value of true is applied Additionally, if no event is defined for a transition, it will be activated once the entry and do activities of the current state are finished.
Finishing these activities creates a completion event that triggers the
A completion event, also known as a completion transition, occurs when an event happens that lacks a specified response in the current state In such cases, the event is not acknowledged and is effectively disregarded.
Guards are enclosed in square brackets to distinguish them from events and activities, while activities are indicated with a forward slash, including those in states The syntax of a transition specification is illustrated in Figure 5.4.
You can modelinternal transitionswithin states These internal tran-
Events and activities in a system manage the occurrence of specific situations within a state They are utilized to model the system's response to an event while remaining in the current state, indicating that entry and exit activities are not performed.
Figure 5.5 illustrates the two statuses a student can have regarding an exam: not registered and registered While in the not registered state, the student consistently checks for available exam dates to determine if they have enough time to take the exam This checking process occurs every time a new exam date is announced If the student decides to register, the transition to the registered state takes place.
Student registration for the exam is confirmed, and the exam date is marked on the calendar While the registration remains active, the student continues their studies Should any issues arise, they are addressed collaboratively with fellow students.
In the event of a withdrawal from the registered status, two scenarios can arise If withdrawal is permitted, the student's exam preparation is halted, and their status changes to not registered, resulting in the removal of the exam date from the calendar Conversely, if withdrawal is not allowed, the student remains registered and must continue their exam studies Interestingly, in the authors' home country, students can withdraw from exams without facing any consequences.
Figure 5.5 State machine diagram of the registration status for an exam
To further illustrate the concept of events, guards, and activities,
Figure 5.6 shows abstract examples of transitions The transition in
In Figure 5.6(a), the transition occurs immediately after the completion of activity A1, as there are no events or guards involved Figure 5.6(b) shows a similar scenario, but with activity A2 being executed during the transition In contrast, Figure 5.6(c) indicates that the transition is triggered by the occurrence of event e1, which interrupts the execution of activity A1 and transitions the system to state S2 Upon exiting state S1, the exit activity A2 is executed.
In Figure 5.6(d), the guard g1 is evaluated when event e1 occurs; if the guard is true, activity A1 is terminated, resulting in a transition to state S2 Conversely, if the guard is false, event e1 is disregarded, and A1 continues without interruption Figure 5.6(e) parallels this scenario but includes the execution of activity A2 during the transition.
Types of States
In addition to the states outlined in Section 5.1, there are various types of states that facilitate the modeling of intricate content using state machine diagrams A key distinction exists between "real" states and pseudostates Pseudostates are transient in nature, indicating that the system cannot remain in a pseudostate Rather than being true states, pseudostates function as control structures that allow for the representation of more complex states and transitions within the system.
Pseudostates, such as the initial state, decision nodes, parallelization and synchronization nodes, history states, entry and exit points, and terminate nodes, cannot have annotations attached to them.
Theinitial state is represented in the diagram as a small black circle
The initial state in a state machine diagram signifies the beginning of the process and is characterized by having no incoming edges and typically one outgoing edge leading to the first operational state If multiple outgoing edges are present, they must have mutually exclusive guard conditions that encompass all scenarios to ensure that only one target state is reached Transitioning from the initial state to the next occurs instantaneously, without any time delay, and does not allow for event specification on the outgoing edge, except for events that create the modeled object, such as new() or create() However, specifying activities during this transition is permitted.
Thedecision nodeis represented in the diagram with a diamond You
In modeling alternative transitions, a decision node features one incoming edge and at least two outgoing edges The incoming edge represents the triggering event for the transition, while the outgoing edges specify the guards for the different paths Activities can be defined at both the incoming and outgoing edges Upon the occurrence of the triggering event, the system enters the transition and briefly pauses at the decision node to evaluate the guards, selecting the appropriate outgoing edge To avoid the system getting stuck, all possible situations must be covered by the guards, and using an [else] clause can help achieve this If guards are not mutually exclusive and multiple edges are true, one edge is chosen nondeterministically For example, if event e1 occurs, the system evaluates the guards [b ≤ 0] and [b > 0] at the decision node, transitioning to either state S2 or S3 This behavior can also be modeled without a decision node.
Figure 5.7(b) In contrast,Figure 5.7(c)andFigure 5.7(d)show differ- ent behavior.Figure 5.7(c)shows that if evente1occurs, the transition starts andbis increased by the value1 The guards are then evaluated.
In Figure 5.7(d), the variable 'b' increases by 1 following the evaluation of the guards, leading to different state transitions in the two models Consequently, Figures 5.7(c) and 5.7(d) are not semantically equivalent.
Figure 5.7 Modeling with and without decision nodes
Figure 5.8 illustrates the various states a student experiences while enrolled in a specific course When a student is in the "not graded" state and receives a grade, they transition to either the "positive" or "negative" state based on their performance Additionally, the model features a "terminate node," which will be explained further in this chapter.
Theparallelization nodeis represented with a black bar It has ex- Parallelization node
A parallelization node in a state machine diagram has one incoming edge and at least two outgoing edges, allowing it to divide the flow into multiple concurrent transitions It is important to note that no events or guards can be specified on the outgoing edges of this node.
Thesynchronization nodeis also represented with a black bar It has Synchronization node
A synchronization node requires at least two incoming edges and exactly one outgoing edge, serving to merge multiple concurrent flows It is important to note that no events or guards can be specified at the incoming edges of a synchronization node For further details on this pseudostate and the history state, refer to Section 5.5 Additionally, it is crucial to distinguish synchronization nodes from decision nodes to avoid confusion.
States of a student’s course participation not graded graded registered withdraw performance correction [new grade=5] negative positive correction [new grade 1] and [x < 3] creates ambiguity when x = 2, making it impossible to select a unique path When a token reaches a decision node, the system must evaluate the current context, such as variable values, to decide the path the token will follow An example illustrates that if the action "Register" is executed, it leads to the action "Select group" if spots are available; otherwise, it triggers the action "Enter on waiting list."
Figure 7.9 Example of a decision node
Decision behavior can be specified for a decision node, allowing for efficient evaluation of guards by avoiding redundant calculations This behavior enables access to calculation results across different guards without causing side effects, meaning it does not alter the values of objects or variables The decision behavior is noted as a comment labeled "decisionInput." For example, once exam results are available, a central department decides whether students can inspect their corrected papers If approved, students review their exams before receiving their certificates; if denied, certificates are issued immediately.
Allow inspection of exam paper?
If you want to bring alternative subpaths back together again, you
The merge node, represented as a diamond with multiple incoming edges and a single outgoing edge, allows for the modeling of execution steps, including loops Notably, a token can only exist at one incoming edge at any given time By utilizing both decision and merge nodes, we can effectively illustrate repeated execution processes.
Example of a loop Write exam
You can also combine decision and merge nodes This combined
Combined decision and merge node
In a flowchart, nodes can have multiple incoming and outgoing edges, with decision and merge nodes activating only one path at a time To model concurrency at the start of an activity, multiple initial nodes can be utilized When an execution path later splits into several simultaneously active paths, this can be represented using a parallelization node, which is specifically designed for this purpose.
A black bar node, depicted in Figure 7.12, features one incoming edge and multiple outgoing edges After registering for a course, a student attends lectures and works on assignments concurrently The student is eligible to take the exam only after completing both the lecture and the assignment.
You can merge concurrent subpaths using asynchronization node. Synchronization node
This node is the counterpart to the parallelization node It is depicted as a black bar with multiple incoming edges but only one outgoing edge.
Once all preceding actions are completed and tokens are present at all incoming edges, these tokens are combined into a single token that is then transmitted through the outgoing edge.
Figure 7.12 Example of the use of parallelization and syn- chronization nodes
In the same way that you can combine decision and merge nodes, Combined parallelization and synchronization node
you can also combine synchronization and parallelization nodes using a bar with multiple incoming edges and multiple outgoing edges.
Object Flows
Up to this point, we have looked mainly at the control flow, concen-
Control tokens and data tokens play distinct roles in the logical sequence of actions within activity diagrams While the focus has primarily been on control tokens, it's important to recognize that data tokens facilitate the exchange of information during these processes Although not explicitly represented in diagrams, data tokens are essential for conveying execution semantics They influence the flow of activities, as they can serve as outputs from one action and inputs for subsequent actions Additionally, data can be received through input parameters and transferred to output parameters, further enhancing the activity's functionality.
Input parameters are usually only read once at the beginning of the activity and output parameters are written once at the end of the activity.
To enable continuous reading and writing of parameters during an activity's execution, label the input or output parameters with the keyword {stream} As illustrated in Figure 7.16, streaming parameters for actions are represented by a filled rectangle, allowing for dynamic data handling throughout the process.
Example of streams {stream} video : String
Transmit lecture {stream} data : String
When the activity is ended, any output parameters that have no token are assigned a null token Within an activity, you can useobject nodesto
Object nodes serve as explicit representations of data exchange and can be illustrated in different formats They may appear as standalone nodes, as shown in the object diagram, or be directly connected to an action through input or output pins For instance, Figure 7.17 presents an independent object node depicted as a rectangle, positioned between the data-producing action and the data-consuming action This rectangle not only includes the name of the represented object but can also specify an object type Additionally, the object's required state can be indicated within square brackets.
Figure 7.17 Example of an object node
Thepin notationfor actions corresponds to the notation of parame- Pins
Action terms represent the inputs and outputs of activities, often depicted as small rectangles at the edges of corresponding actions These pins can be annotated similarly to how object nodes are represented as rectangles An example of this can be seen in Figure 7.18.
Figure 7.18 Example of an object node in pin notation
The activity diagram offers special object nodes for saving and pass- ing on data tokens: the central buffer and the data store Thecentral Central buffer ôcentralBufferằ
A CB buffer is a unique object node that facilitates data flow between various sources and receivers, allowing it to accept incoming data tokens from object nodes and transmit them to others Unlike pins and activity parameters, a central buffer operates independently of specific actions or activities When a data token is retrieved from the central buffer, it is permanently deleted and cannot be reused For instance, in the action of granting access authorization, a key is removed from the KeyCabinet, making it unavailable until it is returned during the action.
In adata store, all data tokens that flow into the data store are saved Data store ôdatastoreằ
A data store permanently retains data by copying it before any retrieval occurs Users can define queries related to the data store's content at its outgoing edges, which are denoted by a note symbol Consequently, a data store can effectively replicate the functionality of a database.
Example of a central buffer Key management for the seminar room
The ExamData data store efficiently manages course participant performance by tracking assignment assessments and exam results, which are essential for calculating overall grades.
Example of a data store points
Issue certificate points student data points ôdatastoreằ
A central buffer serves as transient memory, allowing information to be used only once before it is lost, while a data store functions as permanent memory, enabling repeated access to saved information.
Partitions
Apartitionallows you to group nodes and edges of an activity based on
In a business process, partitions can be utilized to group actions executed by specific entities, reflecting organizational units or roles responsible for those actions UML allows flexibility in grouping criteria, enabling partitions to be specified at various levels of detail, even down to individual classes These partitions can overlap and nest as needed without altering the execution semantics of the activity diagram, which is determined by tokens Consequently, partitions do not affect token flow but provide a logical representation of the components, enhancing diagram clarity and facilitating quick identification of areas of responsibility while adding detailed information to the model.
Partitions can be represented graphically or textually, with graphical representations shown as "open" rectangles on an activity diagram All elements within an "open" rectangle are part of a common group, and the partition's name is indicated at one end of the rectangle These graphical partitions are often called swimlanes.
• Swimlane partitions in an activity diagram that models the execution of an exam.
The parties involved are a student, an assistant, and a professor The use of partitions allows each of these actors to be assigned the actions that they have to perform.
Figure 7.21 Example of one- dimensional partitions
A partition can itself be subdivided into multiplesubpartitions.Fig- Subpartition ure 7.22shows an example of this In this example, the institute employ- eesProfessorandSecretaryare involved in the execution of an exam.
Multi-dimensional partitions are essential for modeling complex interactions between different entities, as illustrated in the correspondence example between a professor at Johannes Kepler University Linz (JKU Linz) and a professor at the Vienna University of Technology (TU Vienna) In this scenario, the TU Vienna professor sends a letter to the JKU Linz professor, which is processed by the secretary at TU Vienna and later retrieved by the secretary at JKU Linz upon arrival This example highlights the necessity of multi-dimensional partitions to accommodate the diverse roles and interactions among various groups of actors.
Example of multi- dimensional partitions
JKU LinzTU Vienna Take letter to post office
You can assign actions to individual partitions or, for multi-dimensional partitions, to a set of partitions in text form To do this, list the partitions in parentheses above the action name If an action is associated with multiple partitions, separate them with a comma, such as (Partition 1, Partition 2).
(TU Vienna,Secretary) Take letter to post office
(JKU Linz,Secretary) Empty mailbox
The example in Figure 7.24 illustrates multi-dimensional partitions using textual notation for subpartitions, denoted by a double colon (Partition::Subpartition) to represent hierarchical partitioning This is further exemplified in the activity diagram from Figure 7.24, which reflects the example presented in Figure 7.23.
Exception Handling
When an error occurs during the execution of an action, the process is halted, and there is no assurance that the action will produce the anticipated results However, if an action includes an exception handler, it can manage errors more effectively.
An exception handler is activated in response to a specific error situation, allowing you to define the system's reaction and minimize the impact of the error By specifying different exception handlers for various error types, you can manage errors more effectively When an error occurs, all tokens in the affected action are deleted, and if a matching exception handler exists, it replaces the original action's content The process then continues along the regular activity path as if the erroneous action had concluded normally.
An exception handler is represented as a rectangle with rounded corners, indicating its role as an activity node The action protected by the exception handler is connected to it via a lightning bolt arrow, which is labeled with the specific type of error For instance, in the event of a paper jam during printing, the process can resume once the jam is cleared Conversely, if the printer is out of paper, it is necessary to insert paper to continue printing until an adequate number of exam instruction copies are produced.
Resolve paper jam paper jam paper tray empty
When multiple exception handlers match, the specific handler to execute remains unspecified If no matching handler is found, the exception is passed to the surrounding structure Should the outermost activity receive the exception without finding a matching handler, the system's behavior becomes undefined.
An exception handler has no explicit incoming or outgoing edges.
The exception handler shares identical access rights to variables and values as the nodes it protects Consequently, the tokens generated during the execution of the exception handler become result tokens for the safeguarded node To maintain consistency, both the exception handler and the safeguarded node must have an equal number of return values, ensuring that all outgoing edges of the safeguarded node receive the necessary token in case of an error.
Theinterruptible activity regionoffers a further way to handle excep-
An interruptible activity region allows for a defined set of actions to be halted immediately upon the occurrence of a specific event, such as an error This region is visually represented as a dashed rectangle with rounded corners, encapsulating the relevant actions while monitoring for the triggering event.
In an interruptible activity region, a special event can trigger specific behaviors, represented by an accept event action that extends outward in a lightning bolt shape to an external activity When this event occurs, all control tokens within the region are removed, activating the action linked to the accept event For instance, if a student withdraws from the university during a course, the action to withdraw the student is executed.
However, a withdrawal is only possible if the student has previously registered and if the actionTake examhas not yet ended In all other cases a certificate is issued.
Figure 7.26Example of an interruptible activity region
Concluding Example
To sum up, we look at the process that has to be executed for a future student of a university to receive a student identification card (student
To obtain a student ID, a student must request it from a student office employee, who provides the necessary registration forms These forms include the student ID, which is traditionally a small cardboard card.
The process of obtaining a student ID involves the student filling out personal data on a card, which the employee verifies against required documents The student ID is only valid if it includes a current semester label After submitting necessary documents like photo identification and certificates, the employee checks for completeness If any documents are missing or the student is unauthorized, the process ends If everything is in order, the employee verifies the accuracy of the student ID form; errors result in the ID being destroyed and a new form needing to be filled out Once correct, the ID is stamped, but it remains invalid until the student receives the semester label by post The process includes two main actors, the Student and the Employee, with defined actions and control flow represented in a diagram A decision node is used to handle invalid documents, while a loop is implemented for correcting form errors Finally, once all steps are completed, the student affixes the semester label, concluding the ID acquisition process.
The activity diagram in Figure 7.27 illustrates the control flow, but it also emphasizes the changes to the student ID, which starts as blank, is filled out, and then stamped The student ID remains invalid until the semester label is affixed Figure 7.28 expands on this by incorporating the object flow of the student ID, clearly indicating the actions required to process and manage this object.
The most important elements of the activity diagram are summarized inTables 7.1and7.2.
Hand over documents and ID
Figure 7.27Activity diagram “Issue student ID”
Activity diagram “Issue student ID” with control and object flow
Hand over documents and ID
Action node Action Actions are atomic, i.e., they cannot be broken down further Activity node Activity Activities can be broken down further
Initial node Start of the execution of an activity
Activity final node End of ALL execution paths of an ac- tivity
Flow final node End of ONE execution path of an ac- tivity
Decision node Splitting of one execution path into two or more alternative execution paths
Merge node Merging of two or more alternative execution paths into one execution path
Parallelization node Splitting of one execution path into two or more concurrent execution paths
Synchronization node Merging of two or more concurrent execution paths into one execution path
Edge A B Connection between the nodes of an activity
Call behavior action A Action A refers to an activity of the same name
Object node Object Contains data and objects that are cre- ated, changed, and read
Parameters for activi- ties Activity Contain data and objects as input and output parameters
(pins) Action Contain data and objects as input and output parameters
Table 7.1Notation elements for the activity diagram
Notation elements for the activity diagram, part 2
B A Grouping of nodes and edges within an activity
Send signal action S Transmission of a signal to a receiver
Asynchronous accept (time) event action
Wait for an event E or a time event T
Exception handler is executed instead of the action in the event of an error e
BFlow continues on a different path if event E is detected
In previous chapters, we explored five UML diagrams that represent various facets of a system, each providing distinct views that must be interpreted collectively rather than in isolation These diagrams complement each other by depicting the system from multiple perspectives This chapter presents three concrete examples from diverse application areas, highlighting the interaction among the different diagrams.
Example 1: Coffee Machine
A coffee machine is a common fixture in universities, particularly the filter coffee machine, which includes essential components such as a water tank, heating plate, coffee pot, and a water pipe connecting the tank to the filter When the machine is activated with water in the tank, it heats the water, creating pressure that pushes it upward through the pipe into the filter, where it mixes with ground coffee to brew a fresh cup.
Finally, the brewed coffee flows out of the filter into the coffee pot.
The coffee machine is available in two different versions, one with a
Model A features a "keep warm" function that activates when the coffee machine is turned on and the water tank is empty, ensuring that the machine remains operational In contrast, Model B does not have this function and will automatically switch off under the same circumstances.
The use case diagrams inFigure 8.2describe the functionality of- Use case diagram
M Seidl et al., UML @ Classroom , Undergraduate Topics in Computer Science, DOI 10.1007/978-3-319-12742-2_ 8
Water tank fered by model A and model B While model A offers the two functions Heat CoffeeandMake Coffee, model B can only be used to make coffee.
In both cases, we assume very simple coffee machines that are limited to the “core competencies” of coffee machines.
Use case diagrams for a coffee machine
Users can easily turn the coffee machine on and off, and essential maintenance tasks like refilling coffee and cleaning the filter are also necessary These activities, while vital, are considered preparatory steps to achieve the main goal of enjoying brewed or heated coffee.
State machine diagram for coffee machine model B on do/Make coffee off switch on
Both coffee machine models, A and B, feature on and off states Model B transitions from the on state automatically after brewing coffee, while Model A requires a manual switch-off for this change In Model A, the on state can be divided into two sub-states: ready, where the heating function is active, and in use, indicating that coffee is currently being brewed The machine can only enter the in-use state when the water tank is filled.
Figure 8.4 State machine diagram for coffee machine model A
The activity diagram in Figure 8.5 illustrates the process for using coffee machine model B To prepare the machine for brewing coffee, one must clean the filter, add ground coffee, fill the machine with water, and then switch it on.
Always clean the filter before adding ground coffee, and ensure water is added before turning on the coffee machine; otherwise, the machine will shut off automatically.
In the activity diagram, actions can be executed in any sequence, illustrated by two concurrent sub-paths with distinct initial nodes Coffee preparation, specifically pouring water through the filter, occurs only when both incoming edges of the synchronization node receive a token Notably, the diagram excludes scenarios where the coffee machine is used without cleaning the filter or adding ground coffee.
The activity diagram in Figure 8.6 illustrates the functionality of model A for a coffee machine Upon activation, the machine initiates the action to heat the coffee Once the machine is fully prepared with ground coffee and water, the keep warm function is disabled, allowing the coffee-making process to commence This sequence is represented using a synchronization node, where the signal to switch off halts the entire operation.
Activity diagram for coffee machine model B
Add ground coffee Switch on
Activity diagram for coffee machine model A
Example 2: Submission System
UML diagrams are essential for illustrating software systems, such as a university's student administration system, which we've explored in various contexts throughout this book While creating a comprehensive and detailed model that can be transformed into executable code exceeds our focus, we will extract a segment of the system to demonstrate the interplay of different diagrams Specifically, we will examine a submission system designed to manage student submissions for assignment tasks.
Each course in the system is managed by assigned lecturers, designated by a course administrator who is also a lecturer These educators are responsible for creating assignments and evaluating student submissions, providing valuable feedback and awarding points based on performance.
The course administrator assigns specific lecturers to evaluate student papers and organizes the issuance of certificates upon course completion A student's final grade is determined by the total points earned from their submitted assignments.
• Students can take courses and upload papers.
All users, including students and lecturers, have the ability to manage their user data, access course information, and view tasks assigned to their courses Students can view their own submitted papers and grades, while lecturers can access only the papers and grades they have assigned The course administrator possesses comprehensive access rights to all user data.
• A course is created and deleted by an administrator.
When creating a course, it's essential to assign at least one administrator, with the option to add more administrators or remove assignments later Additionally, administrators have the authority to delete entire courses when necessary.
• Information about users and administrators is automatically trans- ferred from another system Therefore, functions that allow the cre- ation of user data are not necessary.
• All of the system functions can only be used by persons who are logged in.
The use case diagram in Figure 8.7 summarizes the actors and use cases for the specified system It distinguishes between administrators and other users, categorizing the latter into lecturers and students Additionally, lecturers are further divided into course administrators.
Use case diagram for a submission system
Manage user data View task
The use cases derived from the specification provide a foundational understanding, but they often lack the necessary detail for system implementation It is essential to identify the specific requirements the system must fulfill, although this information is not included in the use case diagram to maintain clarity and readability Instead, these requirements are documented in the descriptions of the use cases, as discussed in Chapter 3.
The log-in and log-out processes are excluded from the use case diagram because they are not desired functions of the actors; rather, they serve to enhance the system's security Logging in is viewed as a prerequisite for utilizing the system effectively.
With the system requirements specified, we can now model the structure and behavior of the submission system, as illustrated in the class diagram This diagram includes all actors from the use case diagram, representing their associated data rather than the actors themselves, which is crucial for implementing authorizations and managing submissions User information is centralized in the User class, with an attribute for authorization distinguishing between administrators (admin) and standard users Administrators can be direct instances of User, while lecturers and students are represented by subclasses inheriting from User, indicating that a lecturer or student can also hold the administrator role This aligns with the use case diagram, where actors represent roles, highlighting that one individual can assume multiple roles However, to enforce strict role differentiation, a separate Admin class or constraints on the authorization attribute would be necessary.
In our class diagram, a lecturer assumes the role of a course administrator through a relationship with a course Tasks are linked to courses, and submissions are associated with these tasks We represent a student's involvement in a course using an association class that tracks the total points and grade, both of which are automatically calculated and designated as derived attributes.
Class diagram for a sub- mission system ôenumerationằ
BType admin standard getCourses() getCourseAdministration()
Lecturer name login password authorization:BType
User notification() updateData() getAuthorization() checkPW() getData()
Submission paper date points correction getData() updateData() assignLecturer() setGrade() setPaper()
Course name semester addCourseAdministrator() delCourseAdministrator() getData() updateData() addParticipation() addTask() issueCertificate() informStudent() informLecturer() informCourseAdministrator() uploadPaper()
Task name description deadline points submissionDeadline getData() updateData() getSubmissions()
/totalPoints /Grade certificateIssued getPoints() getSubmissions() updatePoints() issueCertificate()
Student matNo getData() getParticipations() certificateInfo() * *
The class diagram in Figure 8.8 does not guarantee that a lecturer will only evaluate tasks within their assigned courses, highlighting the need for additional constraints to maintain system consistency To address these restrictions, languages like Object Constraint Language (OCL) can be utilized, although this topic extends beyond the focus of this book Additionally, the compliance check for model instances against these specified restrictions can often be conducted automatically.
The existing class diagram lacks platform-specific details, indicating that the implementation remains undefined To maintain an abstract perspective for the overall system specification, we will continue to focus on this level in the upcoming stages of development.
In this article, we model a typical usage scenario of the submission system, illustrating the interactions among actors, the system, and specified functions Instead of an activity diagram, we utilize a sequence diagram to emphasize communication The scenario begins with a student uploading an assignment paper, prompting the system to notify the course administrator of the new submission and confirm receipt to the student Although the action of saving the paper is not depicted, the course administrator subsequently assigns a lecturer to evaluate the paper The lecturer then downloads the assignment, records the grade in the system, and the student is informed of the grading outcome This communication flow is repeated for each task associated with a course, represented in the sequence diagram as a loop fragment.
After processing all tasks, the course administrator can issue certificates, while the submission system notifies students of their final grades.
The sequence diagram in Figure 8.9 provides a high-level overview of the submission system's functionality, but it lacks specific details To gain a deeper understanding, we will examine the "Issue Certificates" activity depicted in Figure 8.10, where an activity diagram is utilized to illustrate the detailed process involved.
:Submission :Course setPaper() inform Lecturer() getData() setGrade() informStu- dent() update Points() notification() issueCer- tificate()
Course Administrator Student notification() assignLecturer() notification() issueCertificate() notification() certifi- cateInfo() loop(1,numberTasks)
Example 3: Data Type Stack
The final example in this chapter is the modeling of the data structure
A stack is a data structure that allows elements to be added using the push function and removed with the pop function, adhering to the Last In, First Out (LIFO) principle This means that the pop function retrieves the most recently added element The stack class must also include functions to determine the current size of the stack and check for the presence of specific elements To create a stack without size limitations, a recursive data structure is utilized, where each stack element references its predecessor, and the actual content is stored in a private variable named content.
+ getSize(): int + push(Object): void + pop(): Object + empty(): boolean
+ setPrecedingEl(StackEl): void + getContent(): Object + getPrecedingEl(): StackEl top 0,1 0,1
A stack can exist in two primary states: empty and not empty Initially, the stack is empty, but when an element is added, it transitions to the not empty state Each time the push operation is performed, the stack's size increases by one, while the pop operation decreases the size by one If a pop is executed when only one element remains, the stack returns to the empty state.
State machine diagram for a stack empty entry/size=0 push/size=1 not empty pop[size==1] pop[size>1] /size push/size++
:Stack st:StackEl new(object) setPrecedingEl(top) setTop(st) push(object)
Figure 8.15 Sequence diagram for the addition of an element to the stack
The realization ofpushandpopis shown in the sequence diagrams
8.15and8.16 These diagrams are very close to implementations and reflect how the variables are set.
:Stack top:StackEl getContent() setTop(prev) pop() pop(): null getPrecedingEl() object = getContent(): object prev = getPrecedingEl(): prev pop(): object break [empty()==true]
Figure 8.16Sequence diagram for the removal of an element from the stack
To add an object to the stack, a new instance of StackEl must be created with the content attribute set to the object The existing top element of the stack then serves as the predecessor to this new instance, which subsequently becomes the new top element of the stack.
The pop operation undoes the push operation by returning the value of the current top element of the stack, while promoting its predecessor to become the new top element If the stack is empty, it returns null.
Summary
This chapter highlights the key concepts of UML while illustrating the interaction between various diagrams Such interaction facilitates a comprehensive system description without overwhelming developers with excessive information at once, allowing them to concentrate on specific queries The redundancy in the information presented across different diagrams enhances the overall consistency of the model, enabling earlier and easier detection of errors during the development process.
In the preceding chapters, we have learned about the basic concepts of object-oriented modeling using numerous language elements of UML.
We have learned to apply UML concepts to create diagrams that provide various views of complex systems, offering abstraction mechanisms that make system complexity manageable UML serves as a robust foundation for numerous applications, with the potential for extensive exploration of related topics For instance, the Systems Modeling Language (SysML) was developed from UML, extending it with specialized concepts necessary for modeling intricate physical systems.
This book will not delve deeply into all aspects of UML, but it will briefly highlight four key areas: structuring models, defining the UML language, exploring extension mechanisms, and discussing model-based software development These topics provide a glimpse into the extensive possibilities that modeling offers.
Structuring Models
Packages
Apackageallows you to group model elements, such as classes, data
Packages can contain various types, activities, and states, and may also include other packages The visual representation of a package is depicted as a rectangle with a smaller rectangle in the upper left corner, resembling an index card The larger rectangle houses the grouped elements of the package, while the smaller rectangle displays the package name If the content of the package is not pertinent, the package name can alternatively be placed within the larger rectangle Additionally, package content can be illustrated outside the larger rectangle, connected by lines that terminate in a circle with a cross adjacent to the package.
A model element may be included in a maximum of one package directly This inclusion in a package defines the namespace in which
In a namespace, each element must have a unique name, but the same name can be used for different elements across various namespaces For instance, a class named C in package P1 is distinct from a class C in package P2, thanks to the package membership that helps differentiate elements with identical names To ensure uniqueness, the package name is prepended to the element name, resulting in unique identifiers like P1::C and P2::C.
Figure 9.1Notation alternatives for package diagrams
Importing Elements/Packages
Elements within a specific package can reference and communicate with one another, provided there are no visibility restrictions or navigation limitations For instance, an element E in package P1 can be utilized in package P2 if P2 does not have an element with the same name and is included in P1, either directly or indirectly Additionally, elements from other packages can be imported or referenced using qualified names, making all imported elements visible in the importing package according to their visibility Once imported, these elements can be referenced directly, as their names are added to the package's namespace, allowing usage without qualification.
In Chapter 4, we explored class diagrams, focusing on the visibility of attributes, operations, and roles We introduced the visibility package, denoted by the symbol ˜, which indicates that these elements are only accessible within the same package.
Import relationships are represented by a dashed arrow directed away from the importer, labeled with "import." Only externally visible elements, like class C1 in the package, can be imported.
P3, which is imported by packageP1(Fig 9.2).
A package can import entire packages in this way For example, in
In Figure 9.2, the packageP1 imports packageP2, allowing all accessible elements of the imported package to be visible within the namespace of the importing package This process is managed in the same manner as any other import relationship.
For a more detailed examination of this topic, see [23].
The UML Metamodel
Critical readers will ask themselves how we know how to apply the con- cepts of the different diagrams This is described in themetamodel A
A metamodel is a model that defines a modeling language, essentially describing other models The term "meta," derived from Greek, means "about," indicating that metamodels provide insights into the structure and elements of models Just as components within a model are called model elements, the components within a metamodel are referred to as metamodel elements.
The UML metamodel, thesuperstructure[35], specifies UML in the
Class diagrams serve as a superstructure for UML diagrams, detailing the elements they contain and their applications Notably, a class diagram, being a component of UML, is defined by another class diagram, similar to how programming languages can have compilers written for them.
In C, we can create our own modeling languages using concepts from class diagrams, where classes represent language concepts such as classes, associations, and generalizations instead of real-world entities An example of a simplified modeling language, similar to a UML class diagram, is illustrated in Figure 9.3 This metamodel retains features of the UML class diagram but is significantly simplified, with most classes inheriting from the class NamedElement, which uniquely identifies all instances by name Associations are defined through a separate class, while generalizations are depicted as relationships between classes Although we could model generalizations as separate classes to specify additional properties, such as "disjoint" or "overlapping" as seen in traditional UML, our simplified metamodel does not accommodate these distinctions.
The UML syntax discussed here is known as abstract syntax, where an instance of the metamodel is represented by an object model, with associations shown as separate elements connecting other elements Abstract classes are indicated by the isAbstract flag, but this notation can be complex for users To enhance usability, UML also defines concrete syntax, which simplifies the representation of associations through direct connections between related classes, making it more intuitive for human users.
Metamodels and metamodeling encompass various critical aspects, including the essential question of how the language utilized for creating a metamodel is defined.
UML provides an infrastructure that introduces essential concepts, forming its metametamodel While the definitions could theoretically extend indefinitely, the specification remains confined to the metametalevel.
UML Extension Mechanisms
Stereotypes and Profiles
In Section 9.2, we saw that the UML metamodel itself is also a model.
The UML metamodel defines essential language elements, including class diagrams that consist of classes, associations, and generalizations Within this framework, the classes are known as meta-classes, and a unique meta-class called a stereotype allows for the extension of any metaclass by adding specific meta-attributes and constraints Importantly, the original metaclass remains unchanged when a stereotype is applied, enhancing its specificity without altering its fundamental structure.
In the simplest case, stereotypes are used to classify metaclasses with- out introducing additional meta-attributes and constraints.
A stereotype is represented as a class, with the keyword "stereotype" positioned above the name in the first compartment The second compartment typically includes meta-attributes, while constraints can be detailed either after the meta-attributes or as a note Additionally, a pictogram can be assigned to a stereotype, which is later used alongside the corresponding elements An example of a stereotype is illustrated in Figure 9.4.
The entity includes two meta-attributes: author and year, along with two specific constraints The first constraint limits the author meta-attribute to a maximum of ten characters, while the second constraint requires that the year meta-attribute must be less than 2006.
A stereotype is an extension of one or more metaclasses, represented by a solid arrow with a filled arrowhead This arrow indicates the direction of the extension, pointing from the stereotype to the metaclass.
Specification of the stereo- type “Entity” ômetaclassằ
Entity author: String[0 1] {author: length≤10} year: Integer {year