Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
69 views102 pages

OOAD

Uploaded by

samir mundari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views102 pages

OOAD

Uploaded by

samir mundari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

OOAD

Module-I:

Introduction:
BASIC CONCEPTS

Object-oriented programming aims to implement real-world entities like


inheritance, hiding, polymorphism etc. in programming. The main aim of OOP is
to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function.
OOPS concepts are as follows:

1. Class
2. Object
3. Method and method passing
4. Pillars of OOPs Abstraction, Encapsulation, Inheritance, Polymorphism

A CLASS is a user-defined blueprint or prototype from which objects are


created. It represents the set of properties or methods that are common to all
objects of one type. Using classes, you can create multiple objects with the same
behavior instead of writing their code multiple times. This includes classes for
objects occurring more than once in your code. In general, class declarations can
include these components in order:

1. Modifiers: A class can be public or have default access (Refer to this for
details).
2. Class name: The class name should begin with the initial letter
capitalized by convention.
3. Superclass (if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces (if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
5. Body: The class body is surrounded by braces, { }.

AN OBJECT is a basic unit of Object-Oriented Programming that represents real-


life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. The objects are what perform your code, they are
the part of your code visible to the viewer/user. An object mainly consists of:

1. State: It is represented by the attributes of an object. It also reflects the


properties of an object.

1
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact
with other objects.

METHOD: A method is a collection of statements that perform some specific task


and return the result to the caller. A method can perform some specific task
without returning anything. Methods allow us to reuse the code without retyping
it, which is why they are considered time savers. In Java, every method must be
part of some class, which is different from languages like C, C++, and Python.

Let us now discuss the 4 pillars of OOPs:

ABSTRACTION

Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of similar
type and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will stop
the car, but he does not know how on pressing the accelerator, the speed is
actually increasing. He does not know about the inner mechanism of the car or
the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve
100% abstraction using interfaces.

ENCAPSULATION

It is defined as the wrapping up of data under a single unit. It is the mechanism


that binds together the code and the data it manipulates. Another way to think
about encapsulation is that it is a protective shield that prevents the data from
being accessed by the code outside this shield.

• Technically, in encapsulation, the variables or the data in a class is hidden


from any other class and can be accessed only through any member
function of the class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does. So, the terms “encapsulation” and “data-
hiding” are used interchangeably.

2
• Encapsulation can be achieved by declaring all the variables in a class as
private and writing public methods in the class to set and get the values
of the variables.

INHERITANCE

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the


mechanism in Java by which one class is allowed to inherit the features (fields
and methods) of another class.

Let us discuss some frequently used important terminologies:

• Superclass: The class whose features are inherited is known as superclass


(also known as base or parent class).
• Subclass: The class that inherits the other class is known as subclass (also
known as derived or extended or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some
of the code that we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of the existing
class.

POLYMORPHISM

It refers to the ability of object-oriented programming languages to differentiate


between entities with the same name efficiently. This is done by Java with the
help of the signature and declaration of these entities.

ABSTRACTION

Data Abstraction- is the property by virtue of which only the essential details
are displayed to the user. The trivial or the non-essential units are not displayed
to the user. Ex: A car is viewed as a car rather than its individual components.

Abstract classes and Abstract methods :

1. An abstract class is a class that is declared with an abstract keyword.


2. An abstract method is a method that is declared without
implementation.
3. An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
4. A method-defined abstract must always be redefined in the subclass,
thus making overriding compulsory or making the subclass itself
abstract.

3
5. Any class that contains one or more abstract methods must also be
declared with an abstract keyword.
6. There can be no object of an abstract class. That is, an abstract class
can not be directly instantiated with the new operator.
7. An abstract class can have parameterized constructors and the default
constructor is always present in an abstract class.

Encapsulation vs Data Abstraction

1. Encapsulation is data hiding(information hiding) while Abstraction is


detailed hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon
the data, data abstraction deal with exposing the interface to the user
and hiding the details of implementation.
3. Encapsulated classes are java classes that follow data hiding and
abstraction while We can implement abstraction by using abstract
classes and interfaces.
4. Encapsulation is a procedure that takes place at the implementation
level, while abstraction is a design-level process.

Advantages of Abstraction

1. It reduces the complexity of viewing things.


2. Avoids code duplication and increases reusability.
3. Helps to increase the security of an application or program as only
essential details are provided to the user.
4. It improves the maintainability of the application.
5. It improves the modularity of the application.
6. The enhancement will become very easy because without affecting end-
users we can able to perform any type of changes in our internal
system.

ENCAPSULATION

Encapsulation is defined as the wrapping up of data under a single unit. It is the


mechanism that binds together code and the data it manipulates. Another way to
think about encapsulation is, that it is a protective shield that prevents the data
from being accessed by the code outside this shield.

• Technically in encapsulation, the variables or data of a class is hidden


from any other class and can be accessed only through any member
function of its own class in which it is declared.
• As in encapsulation, the data in a class is hidden from other classes
using the data hiding concept which is achieved by making the
members or methods of a class private, and the class is exposed to the

4
end-user or the world without providing any details behind
implementation using the abstraction concept, so it is also known as
a combination of data-hiding and abstraction.
• Encapsulation can be achieved by Declaring all the variables in the class
as private and writing public methods in the class to set and get the
values of variables.
• It is more defined with the setter and getter method.

Advantages of Encapsulation:

• Data Hiding: it is a way of restricting the access of our data members


by hiding the implementation details. Encapsulation also provides a way
for data hiding. The user will have no idea about the inner
implementation of the class. It will not be visible to the user how the
class is storing values in the variables. The user will only know that we
are passing the values to a setter method and variables are getting
initialized with that value.
• Increased Flexibility: We can make the variables of the class read-only
or write-only depending on our requirement. If we wish to make the
variables read-only then we have to omit the setter methods like
setName(), setAge(), etc. from the above program or if we wish to make
the variables write-only then we have to omit the get methods like
getName(), getAge(), etc. from the above program
• Reusability: Encapsulation also improves the re-usability and is easy to
change with new requirements.
• Testing code is easy: Encapsulated code is easy to test for unit testing.

class Area {

int length;

int breadth;

// constructor to initialize values

Area(int length, int breadth) {

this.length = length;

this.breadth = breadth;

// method to calculate area

public void getArea() {

5
int area = length * breadth;

System.out.println("Area: " + area);

class Main {

public static void main(String[] args) {

Area rectangle = new Area(2, 16);

rectangle.getArea();

}
Output
Area: 32

INFORMATION HIDING

Data hiding is a technique of hiding internal object details, i.e., data members. It
is an object-oriented programming technique. Data hiding ensures, or we can say
guarantees to restrict the data access to class members. It maintains data
integrity.

Data hiding means hiding the internal data within the class to prevent its direct
access from outside the class.

If we talk about data encapsulation so, Data encapsulation hides the private
methods and class data parts, whereas Data hiding only hides class data
components. Both data hiding and data encapsulation are essential concepts of
object-oriented programming. Encapsulation wraps up the complex data to
present a simpler view to the user, whereas Data hiding restricts the data use to
assure data security.

Data hiding also helps to reduce the system complexity to increase the robustness
by limiting the interdependencies between software components. Data hiding is
achieved by using the private access specifier.

6
Example:

We can understand data hiding with an example. Suppose we declared


an Account class with a data member balance inside it. Here, the account balance
is sensitive information. We may allow someone to check the account balance but
won't allow altering the balance attribute. So, by declaring the balance attribute
private, we can restrict the access to balance from an outside application.

Now, let's discuss the access specifiers to understand the data hiding. Access
specifiers define how the member's functions and variables can be accessed from
outside the class. So, there are three access specifiers available within a class that
are stated as follows:

Private members/methods: Functions and variables declared as private can be


accessed only within the same class, and they cannot be accessed outside the
class they are declared.

Public members/methods: Functions and variables declared under public can be


accessed from anywhere.

Protected members/methods: Functions and variables declared as protected


cannot be accessed outside the class except a child class. This specifier is
generally used in inheritance.

Now let's see an example of data hiding in C++.

Example

In this example, there is a class with a variable and two functions. Here, the
variable "num" is private so, it can be accessed only by the members of the same
class, and it can't be accessed anywhere else. Hence, it is unable to access this
variable outside the class, which is called data hiding.

(encapsulatiin)

INHERITANCE

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the


mechanism in java by which one class is allowed to inherit the features(fields
and methods) of another class.
Important terminology:

• Super Class: The class whose features are inherited is known as a


superclass(or a base class or a parent class).

7
• Sub Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass
can add its own fields and methods in addition to the superclass fields
and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.

How to use inheritance in Java

The keyword used for inheritance is extends.

Syntax :

class derived-class extends base-class


{
//methods and fields
}
Example: In the below example of inheritance, class Bicycle is a base class, class
Mountain Bike is a derived class that extends Bicycle class and class Test is a
driver class to run program.

DYNAMIC BINDING

Dynamic binding or late binding is the mechanism a computer program waits


until runtime to bind the name of a method called to an actual subroutine. It is an
alternative to early binding or static binding where this process is performed at
compile-time. Dynamic binding is more expensive computationally, but it has the
advantage of being more likely to avoid version conflicts when binding functions
of a linked library.

The ability to perform dynamic binding is a common characteristic of high-level


languages such as C++, Java, and LISP.

When type of the object is determined at run-time, it is known as dynamic


binding.

EXAMPLE

8
1. class Animal
2. {
3. void eat(){System.out.println("animal is eating...");}
4. {
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7. public static void main(String args[]){
8. Animal a=new Dog();
9. a.eat();
10. }
11. }
In the above example object type cannot be determined by the compiler,
because the instance of Dog is also an instance of Animal. So compiler
doesn't know its type, only its base type.

DYNAMIC MODELLING describes those aspect of the system that are concerned
with time and sequencing of the operations. It is used to specify and implement
the control aspect of the system. Dynamic model is represented graphically with
the help of state diagrams. It is also known as state modelling. State model
consist of multiple state diagrams, one for each class with temporal behavior
that is important to an application. State diagram relates with events and states.
Events represents external functional activity and states represents values
objects.
Events:
An event is something that happen at a particular point in particular time such
as a person press button or train 15930 departs from Amritsar. Event conveys
information from one object to another.
The events are of three types: Signal event, Change event, and Time event.
These are explained as following below.
1. Signal event :
A signal event is an particular occurrence in time. A signal is a explicit
one-way transmission of information from one object to another.A
signal event is the event of sending or receiving signal.When an object
send signal to another object it await for acknowledgement but
acknowledgement signal is the separate signal under the control of
second object, which may or may not choose to send it.The UML
notation is (<>) written inside the name at top of the box and in another
section list all the signal attributes.Eg:

9
2. Change event :
It is caused by the satisfaction of a boolean expression.The intent of the
change event is that the expression is tested continually whenever the
expression changes from false to true.The UML notation for a change
event is the keyword when followed by a parenthesized boolean
expression.
Eg:
3. when(battery power < lower limit)
when(room temperature < heating/cooling point )
4. Time event :
It is caused by occurrence of an absolute or the elapse of time
interval.The UML notation for absolute time is the keyword when
followed by a parenthesized expression involving time and for the time
interval is keyword after followed by a parenthesized expression that
evaluates time duration.
Eg:
5. when(Date = mar 2, 2005)
after(50 seconds)
State :
A state is an abstraction of attribute values and links of an object. Values and
links are combined together into a state according to their entire behavior. The
response of object according to input event is called state. A state corresponds
to the interval between two events received by an object. The state of the event
depends on the past event. So basically, state represents intervals of time. The
UML notation for the state is a round box containing an optional state name list,
list the name in boldface, center the name near the top of the box, capitalize the
first letter. Eg:

The following are the important points needs to be remember about state.
1. Ignore attributes that do not affect the behavior of object.
2. The objects in the class have finite number of possible states.
3. Each object can be in one state at a time.

10
4. ALL events are ignored in a state, except those for which behavior is
explicitly prescribed.
5. Both events and states depend upon level of abstraction.

POLYMORPHISM
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
Real-life Illustration:

A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person possesses
different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one interface and have
multiple implementations. The word “poly” means many and “morphs” means
forms, So it means many forms.

Types of polymorphism

In Java polymorphism is mainly divided into two types:


• Compile-time Polymorphism
• Runtime Polymorphism

Type 1: Compile-time polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved


by function overloading or operator overloading.

Note: But Java doesn’t support the Operator Overloading.

11
METHOD OVERLOADING:

When there are multiple functions with the same name but different parameters
then these functions are said to be overloaded. Functions can be overloaded by
change in the number of arguments or/and a change in the type of arguments.

OVERVIEW OF OOAD
In the system analysis or object-oriented analysis phase of software development,
the system requirements are determined, the classes are identified and the
relationships among classes are identified.
The three analysis techniques that are used in conjunction with each other for
object-oriented analysis are object modelling, dynamic modelling, and functional
modelling.
Object Modelling
Object modelling develops the static structure of the software system in terms of
objects. It identifies the objects, the classes into which the objects can be
grouped into and the relationships between the objects. It also identifies the main
attributes and operations that characterize each class.
The process of object modelling can be visualized in the following steps −

• Identify objects and group into classes


• Identify the relationships among classes
• Create user object model diagram
• Define user object attributes
• Define the operations that should be performed on the classes
• Review glossary

12
Dynamic Modelling
After the static behavior of the system is analyzed, its behavior with respect to
time and external changes needs to be examined. This is the purpose of dynamic
modelling.
Dynamic Modelling can be defined as “a way of describing how an individual
object responds to events, either internal events triggered by other objects, or
external events triggered by the outside world”.
The process of dynamic modelling can be visualized in the following steps −

• Identify states of each object


• Identify events and analyze the applicability of actions
• Construct dynamic model diagram, comprising of state transition
diagrams
• Express each state in terms of object attributes
• Validate the state–transition diagrams drawn
Functional Modelling
Functional Modelling is the final component of object-oriented analysis. The
functional model shows the processes that are performed within an object and
how the data changes as it moves between methods. It specifies the meaning of
the operations of object modelling and the actions of dynamic modelling. The
functional model corresponds to the data flow diagram of traditional structured
analysis.
The process of functional modelling can be visualized in the following steps −

• Identify all the inputs and outputs


• Construct data flow diagrams showing functional dependencies
• State the purpose of each function
• Identify constraints
• Specify optimization criteria
Structured Analysis vs. Object Oriented Analysis
The Structured Analysis/Structured Design (SASD) approach is the traditional
approach of software development based upon the waterfall model. The phases of
development of a system using SASD are −

• Feasibility Study
• Requirement Analysis and Specification
• System Design
• Implementation
• Post-implementation Review

13
Now, we will look at the relative advantages and disadvantages of structured
analysis approach and object-oriented analysis approach.
Advantages/Disadvantages of Object Oriented Analysis

Advantages Disadvantages

Focuses on data rather than the Functionality is restricted within


procedures as in Structured objects. This may pose a problem
Analysis. for systems which are intrinsically
procedural or computational in
nature.

The principles of encapsulation It cannot identify which objects


and data hiding help the would generate an optimal system
developer to develop systems design.
that cannot be tampered by other
parts of the system.

The principles of encapsulation The object-oriented models do not


and data hiding help the easily show the communications
developer to develop systems between the objects in the system.
that cannot be tampered by other
parts of the system.

It allows effective management All the interfaces between the


of software complexity by the objects cannot be represented in a
virtue of modularity. single diagram.

It can be upgraded from small to


large systems at a greater ease
than in systems following
structured analysis.

Advantages/Disadvantages of Structured Analysis

Advantages Disadvantages

As it follows a top-down approach in In traditional structured


contrast to bottom-up approach of analysis models, one phase
object-oriented analysis, it can be should be completed before
more easily comprehended than the next phase. This poses a
OOA. problem in design, particularly
if errors crop up or
requirements change.

14
It is based upon functionality. The The initial cost of constructing
overall purpose is identified and then the system is high, since the
functional decomposition is done for whole system needs to be
developing the software. The designed at once leaving very
emphasis not only gives a better little option to add
understanding of the system but also functionality later.
generates more complete systems.

The specifications in it are written in It does not support reusability


simple English language, and hence of code. So, the time and cost
can be more easily analyzed by non- of development is inherently
technical personnel. high.

Module-II

UNIFIED MODELLING LANGUAGE (UML):

The UML stands for Unified modeling language, is a standardized general-purpose


visual modeling language in the field of Software Engineering. It is used for
specifying, visualizing, constructing, and documenting the primary artifacts of
the software system. It helps in designing and characterizing, especially those
software systems that incorporate the concept of Object orientation. It describes
the working of both the software and hardware systems.

The UML was developed in 1994-95 by Grady Booch, Ivar Jacobson, and James
Rumbaugh at the Rational Software. In 1997, it got adopted as a standard by the
Object Management Group (OMG).

Characteristics of UML

The UML has the following features:

o It is a generalized modeling language.


o It is distinct from other programming languages like C++, Python, etc.
o It is interrelated to object-oriented analysis and design.
o It is used to visualize the workflow of the system.
o It is a pictorial language, used to generate powerful modeling artifacts.

15
UML VIEWS

There are five different views that the UML aims to visualize through different
modeling diagrams. These five views are:

1. User's View
2. Structural Views
3. Behavioral Views
4. Environmental View
5. Implementation View

1) User's view

This contains the diagrams in which the user's part of interaction with the
software is defined. No internal working of the software is defined in this model.
The diagrams contained in this view are:

• Use case Diagram

2) Structural view

In the structural view, only the structure of the model is explained. This gives an
estimate of what the software consists of. However, internal working is still not
defined in this model. The diagram that this view includes are:

• Class Diagrams
• Object Diagrams

3) Behavioral view

The behavioral view contains the diagrams which explain the behavior of the
software. These diagrams are:

• Sequence Diagram
• Collaboration Diagram
• State chart Diagram
• Activity Diagram

4) Environmental view

The environmental view contains the diagram which explains the after
deployment behavior of the software model. This diagram usually explains the
user interactions and software effects on the system. The diagrams that the
environmental model contain are:

16
• Deployment diagram

5) Implementation view

The implementation view consists of the diagrams which represent the


implementation part of the software. This view is related to the developer’s views.
This is the only view in which the internal workflow of the software is defined.
The diagram that this view contains is as follows:

• Component Diagram

The following diagram well explains the distribution of these 9 software diagrams
according to the five mentioned views:

UML DIAGRAMS

The UML diagrams are categorized into structural diagrams, behavioral


diagrams, and also interaction overview diagrams. The diagrams are
hierarchically classified in the following figure:

17
1. STRUCTURAL DIAGRAMS

Structural diagrams depict a static view or structure of a system. It is widely used


in the documentation of software architecture. It embraces class diagrams,
composite structure diagrams, component diagrams, deployment diagrams,
object diagrams, and package diagrams. It presents an outline for the system. It
stresses the elements to be present that are to be modeled.

o Class Diagram: Class diagrams are one of the most widely used diagrams. It
is the backbone of all the object-oriented software systems. It depicts the
static structure of the system. It displays the system's class, attributes, and
methods. It is helpful in recognizing the relation between different objects
as well as classes.
o Composite Structure Diagram: The composite structure diagrams show
parts within the class. It displays the relationship between the parts and
their configuration that ascertain the behavior of the class. It makes full use
of ports, parts, and connectors to portray the internal structure of a
structured classifier. It is similar to class diagrams, just the fact it
represents individual parts in a detailed manner when compared with class
diagrams.
o Object Diagram: It describes the static structure of a system at a particular
point in time. It can be used to test the accuracy of class diagrams. It
represents distinct instances of classes and the relationship between them
at a time.

18
o Component Diagram: It portrays the organization of the physical
components within the system. It is used for modeling execution details. It
determines whether the desired functional requirements have been
considered by the planned development or not, as it depicts the structural
relationships between the elements of a software system.
o Deployment Diagram: It presents the system's software and its hardware
by telling what the existing physical components are and what software
components are running on them. It produces information about system
software. It is incorporated whenever software is used, distributed, or
deployed across multiple machines with dissimilar configurations.
o Package Diagram: It is used to illustrate how the packages and their
elements are organized. It shows the dependencies between distinct
packages. It manages UML diagrams by making it easily understandable. It is
used for organizing the class and use case diagrams.

2. BEHAVIORAL DIAGRAMS:

Behavioral diagrams portray a dynamic view of a system or the behavior of a


system, which describes the functioning of the system. It includes use case
diagrams, state diagrams, and activity diagrams. It defines the interaction within
the system.

o State Machine Diagram: It is a behavioral diagram. it portrays the system's


behavior utilizing finite state transitions. It is also known as the State-
charts diagram. It models the dynamic behavior of a class in response to
external stimuli.
o Activity Diagram: It models the flow of control from one activity to the
other. With the help of an activity diagram, we can model sequential and
concurrent activities. It visually depicts the workflow as well as what causes
an event to occur.
o Use Case Diagram: It represents the functionality of a system by utilizing
actors and use cases. It encapsulates the functional requirement of a system
and its association with actors. It portrays the use case view of a system.

19
3. INTERACTION DIAGRAMS

Interaction diagrams are a subclass of behavioral diagrams that give emphasis to


object interactions and also depicts the flow between various use case elements
of a system. In simple words, it shows how objects interact with each other and
how the data flows within them. It consists of communication, interaction
overview, sequence, and timing diagrams.

o Sequence Diagram: It shows the interactions between the objects in terms


of messages exchanged over time. It delineates in what order and how the
object functions are in a system.
o Communication Diagram: It shows the interchange of sequence messages
between the objects. It focuses on objects and their relations. It describes
the static and dynamic behavior of a system.
o Timing Diagram: It is a special kind of sequence diagram used to depict the
object's behavior over a specific period of time. It governs the change in
state and object behavior by showing the time and duration constraints.
o Interaction Overview diagram: It is a mixture of activity and sequence
diagram that depicts a sequence of actions to simplify the complex
interactions into simple interactions.

USE CASE MODELLING

A use case diagram is used to represent the dynamic behavior of a system. It


encapsulates the system's functionality by incorporating use cases, actors, and
their relationships.
Purpose of Use Case Diagrams

The main purpose of a use case diagram is to portray the dynamic aspect of a
system.
1. It gathers the system's needs.
2. It depicts the external view of the system.
3. It recognizes the internal as well as external factors that influence the
system.
4. It represents the interaction between the actors.

20
Example

A use case diagram depicting the Online Shopping website is given below.

Here the Web Customer actor makes use of any online shopping website to
purchase online. The top-level uses are as follows; View Items, Make Purchase,
Checkout, Client Register. The View Items use case is utilized by the customer
who searches and view products. The Client Register use case allows the
customer to register itself with the website for availing gift vouchers, coupons, or
getting a private sale invitation. It is to be noted that the Checkout is an included
use case, which is part of Making Purchase, and it is not available by itself.

The View Items is further extended by several use cases such as; Search Items,
Browse Items, View Recommended Items, Add to Shopping Cart, Add to Wish list.
All of these extended use cases provide some functions to customers, which
allows them to search for an item. The View Items is further extended by several
use cases such as; Search Items, Browse Items, View Recommended Items, Add to
Shopping Cart, Add to Wish list. All of these extended use cases provide some
functions to customers, which allows them to search for an item.

Important tips for drawing a Use Case diagram

Following are some important tips that are to be kept in mind while drawing a use
case diagram:

1. A simple and complete use case diagram should be articulated.

21
2. A use case diagram should represent the most significant interaction among
the multiple interactions.
3. At least one module of a system should be represented by the use case
diagram.
4. If the use case diagram is large and more complex, then it should be drawn
more generalized.

ACTORS AND USE CASES

A use-case describes a sequence of actions, performed by a system that


provides value to an actor. The use-case describes the system’s behavior under
various conditions as it responds to a request from one of the stakeholders, called
the primary actor. The actor is the Who of the system, in other words he the end
user.

factoring use cases

Class diagrams

Class diagram is a static diagram. It represents the static view of an application.


Class diagram is not only used for visualizing, describing, and documenting
different aspects of a system but also for constructing executable code of the
software application.

Purpose of Class Diagrams


The purpose of class diagram is to model the static view of an application. Class
diagrams are the only diagrams which can be directly mapped with object-
oriented languages and thus widely used at the time of construction.

The purpose of the class diagram can be summarized as −


• Analysis and design of the static view of an application.
• Describe responsibilities of a system.
• Base for component and deployment diagrams.
• Forward and reverse engineering.

22
HOW TO DRAW A CLASS DIAGRAM?

• The name of the class diagram should be meaningful to describe the


aspect of the system.
• Each element and their relationships should be identified in advance.
• Responsibility (attributes and methods) of each class should be clearly
identified
• For each class, minimum number of properties should be specified, as
unnecessary properties will make the diagram complicated.
• Use notes whenever required to describe some aspect of the diagram.
At the end of the drawing it should be understandable to the
developer/coder.
• Finally, before making the final version, the diagram should be drawn
on plain paper and reworked as many times as possible to make it
correct.

Example

The following diagram is an example of an Order System of an application. It


describes a particular aspect of the entire application.
• First of all, Order and Customer are identified as the two elements of
the system. They have a one-to-
many relationship because a
customer can have multiple
orders.
• Order class is an abstract class
and it has two concrete classes
(inheritance relationship)
SpecialOrder and NormalOrder.
• The two inherited classes have all
the properties as the Order class.
In addition, they have additional
functions like dispatch () and
receive ().

Class Relations

Classes are interrelated to each other in


specific ways. In particular, relationships
in class diagrams include different types

23
of logical connections. The following are such types of logical connections that
are possible in UML:

• Association
• Directed Association
• Reflexive Association
• Multiplicity
• Aggregation
• Composition
• Inheritance/Generalization
• Realization

Association

is a broad term that encompasses just about any logical


connection or relationship between classes. For example,
passengers and airline may be linked as above.

Directed Association (with str. In digm.)

refers to a directional relationship represented by a line with an arrowhead. The


arrowhead depicts a container-contained directional flow.

Reflexive Association

This occurs when a class may have multiple functions or


responsibilities. For example, a staff member working in an airport may be a pilot,
aviation engineer, ticket dispatcher, guard, or maintenance crew member. If the
maintenance crew member is managed by the aviation engineer there could be a
managed by relationship in two instances of the same class.

Multiplicity

is the active logical association when the cardinality of a class in


relation to another is being depicted. For example, one fleet may
include multiple airplanes, while one commercial airplane may
contain zero to many passengers. The notation 0..* in the diagram means “zero to
many”.

Aggregation

refers to the formation of a particular class as a result of one class being


aggregated or built as a collection. For example, the class “library” is made up of
one or more books, among other materials. In aggregation, the contained classes
are not strongly dependent on the lifecycle of the container. In the same example,

24
books will remain so even when the library is dissolved. To show aggregation in a
diagram, draw a line from the parent class to the child class with a diamond shape
near the parent class.

To show aggregation in a diagram, draw a line from the parent class to the child
class with a diamond shape near the parent class.

Composition

The composition relationship is very similar to the aggregation relationship. with


the only difference being its key purpose of emphasizing the dependence of the
contained class to the life cycle of the container class. That is, the contained class
will be obliterated when the container class is destroyed. For example, a shoulder
bag’s side pocket will also cease to exist once the shoulder bag is destroyed.

To show a composition relationship in a UML diagram, use a directional line


connecting the two classes, with a filled diamond shape adjacent to the container
class and the directional arrow to the contained class.

Inheritance / Generalization

refers to a type of relationship wherein one associated class is a child of another


by virtue of assuming the same functionalities of the parent class. In other words,
the child class is a specific type of the parent class. To show inheritance in a UML
diagram, a solid line from the child class to the parent class is drawn using an
unfilled arrowhead.

Realization

denotes the implementation of the functionality defined in one class by another


class. To show the relationship in UML, a broken line with an unfilled solid
arrowhead is drawn from the class that defines the functionality of the class that
implements the function. In the example, the printing preferences that are set
using the printer setup interface are being implemented by the printer.

Association
Association is the semantic relationship between classes that shows how one
instance is connected or merged with others in a system.

Following are the constraints applied to the association relationship are


a. {implicit}: As the name suggests, the implicit constraints define that the
relationship is not visible, but it is based on a concept.

25
b. {ordered}: It describes that the set of entities is in a particular way at one
end in an association.
c. {changeable}: The changeable constraint ensures that the connections
between several objects within a system are added, improved, and
detached, as and when required.
d. {addOnly}: It specifies that any new connection can be added from an object
located at the other end in an association.
e. {frozen}: The frozen constraint specifies that whenever a link is added
between objects, it cannot be altered by the time it is activated over the
connection or given link.

Reflexive Association

In the reflexive associations, the links are between the objects of the same
classes. In other words, it can be said that the reflexive
association consists of the same class at both ends. An
object can also be termed as an instance.

Let's have a look at its example of a class vegetable. The


vegetable class has two objects, i.e., onion and eggplant.
According to the reflexive association's definition, the link
between the onion and eggplant exist, as they belong to the
same class, i.e., vegetable.

DIRECTED ASSOCIATION

The directed association is concerned with the direction of flow inside association
classes. The flow of association can be shown by employing a directed
association. The directed association between two classes is represented by a line
with an arrowhead, which indicates the navigation direction. The flow of
association from one class to another is always in one direction.

It can be said that there is an association between a person and the company. The
person works for the company. Here the person works for the company, and not
the company works for a person.

26
Inheritance

AGGREGATION

Aggregation is a subset of association, is a collection of different things. It


represents has a relationship. It is more specific than an association. It describes
a part-whole or part-of relationship. It is a binary association, i.e., it only involves
two classes. It is a kind of relationship in which the child is independent of its
parent.

For example:

Here we are considering a car and a wheel example. A car cannot move without a
wheel. But the wheel can be independently
used with the bike, scooter, cycle, or any
other vehicle. The wheel object can exist
without the car object, which proves to be an
aggregation relationship.

COMPOSITION

The composition is a part of aggregation, and it portrays the whole-part


relationship. It depicts dependency between a composite (parent) and its parts
(children), which means that if the composite is discarded, so will its parts get
deleted. It exists between similar objects.

As you can see from the example given below, the


composition association relationship connects the
Person class with Brain class, Heart class, and Legs class.
If the person is destroyed, the brain, heart, and legs will
also get discarded.

Inheritance,

DEPENDENCY

Dependency depicts how various things within a system are dependent on each
other. In UML, a dependency relationship is the kind of relationship in which a
client (one element) is dependent on the supplier (another element). It is used in
class diagrams, component diagrams, deployment diagrams, and use-case
diagrams, which indicates that a change to the supplier necessitates a change to
the client.

27
Types of Dependency Relationship

o <<derive>> -It is a constraint that specifies the template can be initialized


by the source at the target location utilizing given parameters.
o <<derive>> -It represents that the source object's location can be evaluated
from the target object.
o <<friend>> -It states the uniqueness of the source in the target object.
o <<instanceOf>> -It states that an instance of a target classifier is the source
object.
o <<instantiate>> -It defines the capability of the source object, creating
instances of a target object.
o <<refine>> -It states that the source object comprises of exceptional
abstraction than that of the target object.
o <<use>> -When the packages are created in UML, the use of stereotype is
used as it describes that the elements of the source package can also exist
in the target package. It specifies that the source package uses some of the
elements of the target package.
o <<substitute>> -The substitute stereotype state that the client can be
substituted at the runtime for the supplier.
o <<access>> -It is also called as private merging in which the source package
accesses the element of the target package.
o <<import>> -It specifies that target imports the source package's element
as they are defined within the target. It is also known as public merging.
o <<permit>> -It describes that the source element can access the supplier
element or whatever visibility is provided by the supplier.
o <<extend>> -It states that the behavior of the source element can be
extended by the target.

28
o <<include>> -It describes the source element, which can include the
behavior of another element at a specific location, just like a function call in
C/C++.
o <<become>> -It states that target is similar to the source with distinct roles
and values.
o <<call>> -It specifies that the target object can be invoked by the source.
o <<copy>> -It states that the target is an independent replica of a source
object.
o <<parameter>> -It describes that the supplier is a parameter of the client's
actions.
o <<send>> -The client act as an operation, which sends some unspecified
targets to the supplier.

OBJECT DIAGRAM

Object diagrams are dependent on the class diagram as they are derived from the
class diagram. It represents an instance of a class diagram. The objects help in
portraying a static view of an object-oriented system at a specific instant.

Both the object and class diagram are similar to some extent; the only difference
is that the class diagram provides an abstract view of a system. It helps in
visualizing a particular functionality of a system.

NOTATION OF AN OBJECT DIAGRAM

PURPOSE OF OBJECT DIAGRAM

The object diagram holds the same purpose as that of a


class diagram. The class diagram provides an abstract view which comprises of
classes and their relationships, whereas the object diagram represents an instance
at a particular point of time.

The object diagram is actually similar to the concrete (actual) system behavior.
The main purpose is to depict a static view of a system.

Following are the purposes enlisted below:

o It is used to perform forward and reverse engineering.

29
o It is used to understand object behavior and their relationships practically.
o It is used to get a static view of a system.
o It is used to represent an
instance of a system.

Example

How to draw an Object Diagram?


1. All the objects present in the system should be examined before start
drawing the object diagram.
2. Before creating the object diagram, the relation between the objects must be
acknowledged.
3. The association relationship among the entities must be cleared already.
4. To represent the functionality of an object, a proper meaningful name
should be assigned.
5. The objects are to be examined to understand its functionality.

Applications of Object diagrams

The following are the application areas where the object diagrams can be used.

1. To build a prototype of a system.


2. To model complex data structures.
3. To perceive the system from a practical perspective.
4. Reverse engineering.

Class Vs. Object Diagram

Serial Class Diagram Object Diagram


No.

1. It depicts the static view of a system. It portrays the real-time behavior


of a system.

30
2. Dynamic changes are not included in Dynamic changes are captured in
the class diagram. the object diagram.

3. The data values and attributes of an It incorporates data values and


instance are not involved here. attributes of an entity.

4. The object behavior is manipulated in Objects are the instances of a


the class diagram. class.

PACKAGES

INTERACTION DIAGRAMS

the interaction diagram portrays the interactions between distinct entities present
in the model. It amalgamates both the activity and sequence diagrams. The
communication is nothing but units of the behavior of a classifier that provides
context for interactions.

A set of messages that are interchanged between the entities to achieve certain
specified tasks in the system is termed as interaction. It may incorporate any
feature of the classifier of which it has access. In the interaction diagram, the
critical component is the messages and the lifeline.

In UML, the interaction overview diagram initiates the interaction between the
objects utilizing message passing. While drawing an interaction diagram, the
entire focus is to represent the relationship among different objects which are
available within the system boundary and the message exchanged by them to
communicate with each other.

The message exchanged among objects is either to pass some information or to


request some information. And based on the information, the interaction diagram
is categorized into the sequence diagram, collaboration diagram, and timing
diagram.

Notation of an Interaction Diagram

Purpose of an Interaction Diagram

The interaction diagram helps to envision the interactive


(dynamic) behavior of any system. It portrays how objects
residing in the system communicates and connects to each other. It also provides
us with a context of communication between the lifelines inside the system.

31
Following are the purpose of an interaction diagram given below:

1. To visualize the dynamic behavior of the system.


2. To envision the interaction and the message flow in the system.
3. To portray the structural aspects of the entities within the system.
4. To represent the order of the sequenced interaction in the system.
5. To visualize the real-time data and represent the architecture of an object-
oriented system.

How to draw an Interaction Diagram


1. A total no of lifeline which will take part in the communication.
2. The sequence of the message flow among several entities within the system.
3. No operators used to ease out the functionality of the diagram.
4. Several distinct messages that depict the interactions in a precise and clear
way.
5. The organization and structure of a system.
6. The order of the sequence of the flow of messages.
7. Total no of time constructs of an object.

Use of an Interaction Diagram

The interaction diagram can be used for:

1. The sequence diagram is employed to investigate a new application.


2. The interaction diagram explores and compares the use of the collaboration
diagram sequence diagram and the timing diagram.
3. The interaction diagram represents the interactive (dynamic) behavior of the
system.
4. The sequence diagram portrays the order of control flow from one element
to the other elements inside the system, whereas the collaboration diagrams
are employed to get an overview of the object architecture of the system.
5. The interaction diagram models the system as a time-ordered sequence of a
system.

32
6. The interaction diagram models the system as a time-ordered sequence of a
system.
7. The interaction diagram systemizes the structure of the interactive
elements.

SEQUENCE DIAGRAMS

The sequence diagram represents the flow of messages in the system and is also
termed as an event diagram. It helps in envisioning several dynamic scenarios. It
portrays the communication between any two lifelines as a time-ordered sequence
of events, such that these lifelines took part at the run time. In UML, the lifeline is
represented by a vertical bar, whereas the message flow is represented by a
vertical dotted line that extends across the bottom of the page. It incorporates the
iterations as well as branching.

Purpose of a Sequence Diagram


1. To model high-level interaction among active objects within a system.
2. To model interaction among objects inside a collaboration realizing a use
case.
3. It either models generic interactions or some certain instances of
interaction.

Notations of a Sequence Diagram

Lifeline

An individual participant in the sequence diagram is represented by a


lifeline. It is positioned at the top of the diagram.

ACTOR

A role played by an entity that interacts with the subject is called as an


actor. It is out of the scope of the system. It represents the role, which
involves human users and external hardware or subjects. An actor may
or may not represent a physical entity, but it purely depicts the role of
an entity. Several distinct roles can be played by an actor or vice versa.

33
Activation

It is represented by a thin rectangle on the lifeline. It describes that


time period in which an operation is performed by an element, such
that the top and the bottom of the rectangle is associated with the
initiation and the completion time, each respectively.

Messages

The messages depict the interaction between the objects and are
represented by arrows. They are in the sequential order on the lifeline. The core
of the sequence diagram is formed by messages and lifelines.

Following are types of messages enlisted below:

o Call Message: It defines a particular communication


between the lifelines of an interaction, which represents
that the target lifeline has invoked an operation.

o Return Message: It defines a particular communication


between the lifelines of interaction that represent the flow of
information from the receiver of the corresponding caller
message.

o Self Message: It describes a communication, particularly between the


lifelines of an interaction that represents a message of the same lifeline,
has been invoked.
o Create Message: It describes a communication, particularly between the
lifelines of an interaction describing that the target (lifeline) has been
instantiated.

o Destroy Message: It describes a communication,


particularly between the lifelines of an interaction that
depicts a request to destroy the lifecycle of the target

o Duration Message: It describes a communication


particularly between the lifelines of an interaction, which
portrays the time passage of the message while modeling a
system.

34
Note

A note is the capability of attaching several remarks to the element. It basically


carries useful information for the modelers.

Fragments

A fragment in a sequence diagram is a rectangular frame drawn over part of the


diagram. They represent conditional structures that affect the flow of messages.
These frames are known as combined fragments in the UML specification and the
container is known as the interaction operand.

Sequence Fragments
1. Sequence fragments have been introduced by UML 2.0, which makes it quite
easy for the creation and maintenance of an accurate sequence diagram.
2. It is represented by a box called a combined fragment, encloses a part of
interaction inside a sequence diagram.
3. The type of fragment is shown by a fragment
operator.

Types of fragments

Following are the types of fragments enlisted below;

Operator Fragment Type

alt Alternative multiple fragments: The only fragment for which the
condition is true, will execute.

opt Optional: If the supplied condition is true, only then the fragments will
execute. It is similar to alt with only one trace.

par Parallel: Parallel executes fragments.

loop Loop: Fragments are run multiple times, and the basis of interaction is
shown by the guard.

region Critical region: Only one thread can execute a fragment at once.

35
neg Negative: A worthless communication is shown by the fragment.

ref Reference: An interaction portrayed in another diagram. In this, a


frame is drawn so as to cover the lifelines involved in the
communication. The parameter and return value can be explained.

sd Sequence Diagram: It is used to surround the whole sequence diagram.

Communication diagram

In UML, a communication diagram shows the interactions between the objects or


roles associated with lifelines and the messages that pass between lifelines. In
earlier versions of UML, this diagram was called a collaboration diagram and had
a different notation.

Communication diagrams are a type of interaction diagram that you can use to
explore the dynamic behavior of a system or software application. They provide
an alternate view of the same information as sequence diagrams. In sequence
diagrams, the focus is the ordering of the messages over time; in communication
diagrams the focus is the structure of the messages that pass between the objects
in the interaction. These diagrams illustrate the flow of messages between objects
and the implied relationships between classes.

You can use communication diagrams to explore how objects in a system or


application work together. Communication diagrams can identify the following
aspects of an interaction or task:

• Objects that participate in the interaction


• Interfaces that the participating classes require
• Structural changes that an interaction requires
• Data that is passed between the objects in an interaction

Communication diagrams look similar to object diagrams, in which a lifeline


represent the objects in the interaction and arrows represent the messages that
are passed between the lifelines. Arrowheads indicate the direction of the
messages, forward or reverse, and sequence numbers indicate the order in which
the messages are passed.

The following topics describe the elements in communication diagrams:

• Lifelines in UML diagrams


In UML diagrams, such as sequence or communication diagrams, lifelines
represent the objects that participate in an interaction. For example, in a

36
banking scenario, lifelines can represent objects such as a bank system or
customer. Each instance in an interaction is represented by a lifeline.
• Message pathways in
communication diagrams
In communication diagrams, a
message pathway is a connector
between the roles or objects
represented by lifelines in the
diagram. The pathway identifies
the objects that can pass
messages in the interaction.
• Messages in UML diagrams
A message is an element in a
Unified Modeling Language (UML)
diagram that defines a specific
kind of communication between
instances in an interaction. A
message conveys information
from one instance, which is
represented by a lifeline, to another instance in an interaction.

State diagram

A state diagram is used to represent the condition of the system or part of the
system at finite instances of time. It’s a behavioral diagram and it represents
the behavior using finite state transitions. State diagrams are also referred to
as State machines and State-chart Diagrams. These terms are often used
interchangeably. So simply, a state diagram is used to model the dynamic
behavior of a class in response to time and changing external stimuli.

Uses of statechart diagram –


• We use it to state the events responsible for change in state (we do not
show what processes cause those events).
• We use it to model the dynamic behavior of the system .
• To understand the reaction of objects/classes to internal or external
stimuli.

Difference between state diagram and flowchart –


The basic purpose of a state diagram is to portray various changes in state of
the class and not the processes or commands causing the changes. However,
a flowchart on the other hand portrays the processes or commands that on
execution change the state of class or an object of the class.

37
The state diagram above shows the different states in which the verification sub-
system or class exist for a particular system.

Basic components of a statechart diagram –

1. Initial state – We use a black filled circle represent the initial state of a
System or a class.

Figure – initial state notation


2. Transition – We use a solid arrow to represent the transition or change
of control from one state to another. The arrow is labelled with the
event which causes the change in
state.

Figure – transition
3. State – We use a rounded rectangle to represent a state. A state
represents the conditions or circumstances of an object of a class at an
instant of time.

Figure – state notation


4. Fork – We use a rounded solid rectangular bar to represent a Fork
notation with incoming arrow from the parent state and
outgoing arrows towards the newly created states. We
use the fork notation to represent a state splitting into
two or more concurrent states.

Figure – a diagram using the fork notation

5. Join – We use a rounded solid rectangular bar to


represent a Join notation with incoming arrows from
the joining states and outgoing arrow towards the

38
common goal state. We use the join notation when two or more states
concurrently converge into one on the occurrence of an event or events.

Figure – a diagram using join notation

6. Self transition – We use a solid arrow pointing back to the state itself to
represent a self transition. There might be scenarios when the state of
the object does not change upon the occurrence of an event. We use self
transitions to represent such cases.

Figure – self transition notation


7. Composite state – We use a rounded rectangle to represent a composite
state also.We represent a state with internal activities using a composite
state.

Figure – a state with internal


activities
8. Final state – We use a filled circle within a circle notation to represent
the final state in a state machine diagram.

Figure – final state notation

Steps to draw a state diagram –

1. Identify the initial state and the final terminating states.


2. Identify the possible states in which the object can exist (boundary
values corresponding to different attributes guide us in identifying
different states).
3. Label the events which trigger these transitions.

Example – state diagram for an online order –

The UMl diagrams we draw depend on the


system we aim to represent. Here is just an

39
example of how an online ordering system might look like :
1. On the event of an order being received, we transit from our initial state
to Unprocessed order state.
2. The unprocessed order is then checked.
3. If the order is rejected, we transit to the Rejected Order state.
4. If the order is accepted and we have the items available we transit to
the fulfilled order state.
5. However if the items are not available we transit to the Pending Order
state.
6. After the order is fulfilled, we transit to the final state. In this example,
we merge the two states i.e. Fulfilled order and Rejected order into one
final state.

EVENTS

The event state diagram shows possible event states and describes how
transitions occur between these states based on the values in the alerts.status
Severity and Tally fields. The diagram also shows how different event types are
handled.

The event state diagram is shown below. Each event is assigned one of these
states as it passes through the Event Gateway. Each state transition corresponds
to an updated event received from the ObjectServer. The event states are shown
with an associated color as follows:

• Red indicates an active problem state.


• Green indicates an active clear state.
• White indicates that this is not an active state.

guards, composite states,

Concurrent states
A Concurrent State is partitioned into regions, which are separated by a dashed
line. Each region represents a Concurrent Substate into which you can add States.
By default, a Concurrent State is created with two concurrent substates.
Concurrency modeling is used to simplify state models, where there are separate
areas of concern. This is done by splitting a Concurrent State into partitions. It

40
should not be confused with parallel execution, described as tasks on the
concurrency diagram
Create a Concurrent State through a Modeler explorer pane or a State Diagram:
• In a Modeler pane, right-click a State Machine or Sequential State, point to New,
and then click Concurrent State.
• On a State Diagram, click the Concurrent State toolbar button, and then click the
diagram background (within the frame) or within a Sequential State.
On a Concurrent State you can create doActivities that are continuous performed
by the Concurrent State. A doActivity terminates when the Concurrent State is
complete, or when the Concurrent State is exited. A
doActivity can be an Activity, Operation or State Machine.
When used on a State Diagram, a Concurrent State's
notation is as follows.

The View Options on a State Diagram allow you to show or


hide the Name, Event Action Blocks, Do Activities and Compartment Names. By
default, all the preceding properties are shown. The view options are set through
the Composite State entry. See Composite state view options - state diagram.

history state

activity diagram, swim lanes, events, messages, object flow,

Component diagram

A component diagram is used to break down a large object-oriented system into


the smaller components, so as to make them more manageable. It models the
physical view of a system such as executables, files, libraries, etc. that resides
within the node.

Notation of a Component Diagram

a) A component b) A node

41
Purpose of a Component Diagram

The main purpose of the component diagram are enlisted below:

1. It envisions each component of a system.


2. It constructs the executable by incorporating forward and reverse
engineering.
3. It depicts the relationships and organization of components.

Why use Component Diagram?

The component diagrams have remarkable importance. It is used to depict the


functionality and behavior of all the components present in the system, unlike
other diagrams that are used to represent the architecture of the system, working
of a system, or simply the system itself.

Following are some reasons for the requirement of the component diagram:

1. It portrays the components of a system at the runtime.


2. It is helpful in testing a system.
3. It envisions the links between several connections.

AD

How to Draw a Component Diagram

The component diagram is helpful in representing the physical aspects of a


system, which are files, executables, libraries, etc. The main purpose of a
component diagram is different from that of other diagrams. It is utilized in the
implementation phase of any application.

Following are some artifacts that are needed to be identified before drawing a
component diagram:

1. What files are used inside the system?


2. What is the application of relevant libraries and artifacts?
3. What is the relationship between the artifacts?

42
Following are some points that are needed to be kept in mind after the artifacts
are identified:

1. Using a meaningful name to ascertain the component for which the diagram
is about to be drawn.
2. Before producing the required tools, a mental layout is to be made.
3. To clarify the important points, notes can be incorporated.

Example of a Component Diagram

A component diagram for an online shopping


system is given below:

Where to use Component Diagrams

The component diagram can be used for the


followings:

1. To model the components of the


system.
2. To model the schemas of a database.
3. To model the applications of an application.
4. To model the system's source code.

Deployment diagram.
Deployment diagrams are used for describing the hardware components, where
software components are deployed. Component diagrams and deployment
diagrams are closely related.
Purpose of Deployment Diagrams
UML is mainly designed to focus on the software artifacts of a system. However,
these two diagrams are special diagrams used to focus on software and hardware
components.
The purpose of deployment diagrams can be described as −
• Visualize the hardware topology of a system.
• Describe the hardware components used to deploy software
components.
• Describe the runtime processing nodes.

43
Draw a Deployment Diagram

Deployment diagram represents the deployment view of a system. It is related to


the component diagram because the components are deployed using the
deployment diagrams.
Deployment diagrams are useful for system engineers. An efficient deployment
diagram is very important as it controls the following parameters −
• Performance
• Scalability
• Maintainability
• Portability
Before drawing a deployment diagram, the following artifacts should be identified

• Nodes
• Relationships among nodes
Following is a sample deployment diagram to provide an idea of the deployment
view of order management system. Here, we have shown
nodes as −
• Monitor
• Modem
• Caching server
• Server
The application is assumed to be a web-based
application, which is deployed in a clustered environment
using server 1, server 2, and server 3. The user connects
to the application using the Internet. The control flows
from the caching server to the clustered environment.
Where to Use Deployment Diagrams
Deployment diagrams can be used −
• To model the hardware topology of a system.
• To model the embedded system.
• To model the hardware details for a client/server system.
• To model the hardware details of a distributed application.
• For Forward and Reverse engineering.

GUARDS
To model conditions we use guards in UML. They are used when we need to restrict the
flow of messages on the pretext of a condition being met. Guards play an important role

44
in letting software developers know the constraints attached to a system or a particular
process. For example: In order to be able to withdraw cash, having a balance greater than
zero is a condition that must be met as shown below. Figure –
sequence diagram using a guard

COMPOSITE STATE
We use a rounded rectangle to represent a composite state also.We represent a state with
internal activities using a composite state.

Figure – a state with internal activities

CONCURRENT STATE DIAGRAMS


In addition to states of an order that are based on the availability of the items,
there are also states that are based on payment authorization. If we look at these
states, we might see a state diagram.
Figure 8-4. Payment Authorization

45
Here we begin by doing an authorization. The "check payment" activity finishes
by signaling that the payment is approved. If the payment is OK, the given order
waits in the Authorized state until the "deliver" event occurs. Otherwise, the order
enters the Rejected state.
The Order object exhibits a combination of the behaviors shown in Figure 8-1 and
Figure 8-2. The associated states and the Cancelled state discussed earlier can be
combined on a concurrent state diagram.

Note that in Figure I left out details of the internal states.


The concurrent sections of the state diagram are places in which at any point, the
given order is in two different states, one from each diagram. When the order
leaves the concurrent states, it is in only a single state. We can see that an order
starts off in both the Checking and Authorizing states. If the "check payment"
activity of the Authorizing state completes successfully first, the order will be in
the Checking and Authorized states. If the "cancel" event occurs, the order will be
in only the Cancelled state.
Concurrent state diagrams are useful when a given object has sets of independent
behaviors. Note, however, that you should not get too many concurrent sets of
behaviours occurring in a single object. If you have several complicated

46
concurrent state diagrams for an object, you should consider splitting the object
into separate objects.

HISTORY STATES

A history state is used to remember the previous state of a state machine when it
was interrupted. The following diagram illustrates the use of history states. The
example is a state machine belonging to a washing machine.

In this state machine, when a washing machine is running, it will progress from
"Washing" through "Rinsing" to "Spinning". If there is a power cut, the washing
machine will stop running and will go to the "Power Off" state. Then when the
power is restored, the Running state is entered at the "History State" symbol
meaning that it should resume where it last left-off.

UML - ACTIVITY DIAGRAMS


Activity diagram is another important diagram in UML to describe the dynamic
aspects of the system.
Activity diagram is basically a flowchart to represent the flow from one activity to
another activity. The activity can be described as an operation of the system.
The control flow is drawn from one operation to another. This flow can be
sequential, branched, or concurrent. Activity diagrams deal with all type of flow
control by using different elements such as fork, join, etc
Purpose of Activity Diagrams
The basic purposes of activity diagrams is similar to other four diagrams. It
captures the dynamic behaviour of the system. Other four diagrams are used to

47
show the message flow from one object to another but activity diagram is used to
show message flow from one activity to another.
Activity is a particular operation of the system. Activity diagrams are not only
used for visualizing the dynamic nature of a system, but they are also used to
construct the executable system by using forward and reverse engineering
techniques. The only missing thing in the activity diagram is the message part.
It does not show any message flow from one activity to another. Activity diagram
is sometimes considered as the flowchart. Although the diagrams look like a
flowchart, they are not. It shows different flows such as parallel, branched,
concurrent, and single.
The purpose of an activity diagram can be described as −
• Draw the activity flow of a system.
• Describe the sequence from one activity to another.
• Describe the parallel, branched and concurrent flow of the system.
How to Draw an Activity Diagram?
Activity diagrams are mainly used as a flowchart that consists of activities
performed by the system. Activity diagrams are not exactly flowcharts as they
have some additional capabilities. These additional capabilities include
branching, parallel flow, swimlane, etc.
Before drawing an activity diagram, we must have a clear understanding about the
elements used in activity diagram. The main element of an activity diagram is the
activity itself. An activity is a function performed by the system. After identifying
the activities, we need to understand how they are associated with constraints
and conditions.
Before drawing an activity diagram, we should identify the following elements −
• Activities
• Association
• Conditions
• Constraints
Once the above-mentioned parameters are identified, we need to make a mental
layout of the entire flow. This mental layout is then transformed into an activity
diagram.
Following is an example of an activity diagram for order management system. In
the diagram, four activities are identified which are associated with conditions.
One important point should be clearly understood that an activity diagram cannot
be exactly matched with the code. The activity diagram is made to understand the
flow of activities and is mainly used by the business users
Following diagram is drawn with the four main activities −
• Send order by the customer

48
• Receipt of the order
• Confirm the order
• Dispatch the order
After receiving the order request, condition checks are performed to check if it is
normal or special order. After the type of order is identified, dispatch activity is
performed and that is marked as the termination of the process.

Where to Use Activity Diagrams?


The basic usage of activity diagram is similar to other four UML diagrams. The
specific usage is to model the control flow from one activity to another. This
control flow does not include messages.
Activity diagram is suitable for modeling the activity flow of the system. An
application can have multiple systems. Activity diagram also captures these
systems and describes the flow from one system to another. This specific usage is
not available in other diagrams. These systems can be database, external queues,
or any other system.
We will now look into the practical applications of the activity diagram. From the
above discussion, it is clear that an activity diagram is drawn from a very high
level. So it gives high level view of a system. This high level view is mainly for
business users or any other person who is not a technical person.
This diagram is used to model the activities which are nothing but business
requirements. The diagram has more impact on business understanding rather
than on implementation details.
Activity diagram can be used for −

49
• Modeling work flow by using activities.
• Modeling business requirements.
• High level understanding of the system's functionalities.
• Investigating business requirements at a later stage.

SWIM LANES IN ACTIVITY DIAGRAM

The Activity diagrams in Object Oriented Design are just like the flow carts that show
the sequence of steps that make up a complex process, such as an algorithm or
workflow. Activity diagram are most useful during the initial stages of the design phase.
Example:
An example of the activity diagram for “TICKET VENDING MACHINE” is as shown below:

50
The above activity diagram does not show which organisation performs a particular
activity
Swim Lanes:
Swimlanes are used to show which activities are performed by which organisation in the
activity diagram. The lanes are boundaries are drawn and the activities of a particular
organisation are drawn in the same lane as that of the organisation. Swimlanes have to be
ordered in a Logical Manner. It is suggested to have less than five swimlanes in an
activity diagram. Swimlanes are good in that they combine the activity diagram’s

depiction of logic with the interaction diagram’s depiction of responsibility.

51
The above activity diagram for “TICKET VENDING MACHINE” with the swimlanes is
shown below:

52
OBJECT FLOWS IN ACTIVITY DIAGRAMS

In Activity diagrams, there are several ways to define the flow of data between
objects.
This diagram depicts a simple Object Flow between two actions, Fill Order and
Ship Order, both accessing order information.

See UML Superstructure Specification, v2.1.1, figure 12.110, p.391.


This explicit portrayal of the data object Order, connected to the Activities by
two Object Flows, can be refined by using this format. Here, Action Pins are used
to reflect the order.

See UML Superstructure Specification, v2.1.1, figure 12.110, p.391.


This diagram is an example of multiple Object Flows exchanging data between
two actions.

See UML Superstructure Specification, v2.1.1, figure 12.111, p.391.


Selection and transformation behavior, together composing a sort of query, can
specify the nature of the Object Flow's data access. Selection behavior
determines which objects are affected by the connection. Transformation
behavior might then further specify the value of an attribute pertaining to a
selected object.
Selection and transformation behaviors can be defined by attaching a note to the
Object Flow. To do this, right-click on the Object Flow and select the 'Attach Note
or Constraint' option. A dialog lists other flows in the diagram to which you can
select to attach the note, if the behavior applies to multiple flows. To comply
with UML 2, preface the behavior with the notation «selection» or
«transformation».

53
UML COMPONENT DIAGRAM

A component diagram is used to break down a large object-oriented system into


the smaller components, so as to make them more manageable. It models the
physical view of a system such as executables, files, libraries, etc. that resides
within the node.

It visualizes the relationships as well as the organization between the components


present in the system. It helps in forming an executable system. A component is a
single unit of the system, which is replaceable and executable. The
implementation details of a component are hidden, and it necessitates an
interface to execute a function. It is like a black box whose behavior is explained
by the provided and required interfaces.

Notation of a Component Diagram

a) A component

b) A node

Purpose of a Component Diagram

Since it is a special kind of a UML diagram, it holds distinct purposes. It describes


all the individual components that are used to make the functionalities, but not
the functionalities of the system. It visualizes the physical components inside the
system. The components can be a library, packages, files, etc.

The component diagram also describes the static view of a system, which
includes the organization of components at a particular instant. The collection of
component diagrams represents a whole system.

The main purpose of the component diagram are enlisted below:

1. It envisions each component of a system.

54
2. It constructs the executable by incorporating forward and reverse
engineering.
3. It depicts the relationships and organization of components.

Why use Component Diagram?

The component diagrams have remarkable importance. It is used to depict the


functionality and behavior of all the components present in the system, unlike
other diagrams that are used to represent the architecture of the system, working
of a system, or simply the system itself.

In UML, the component diagram portrays the behavior and organization of


components at any instant of time. The system cannot be visualized by any
individual component, but it can be by the collection of components.

Following are some reasons for the requirement of the component diagram:

1. It portrays the components of a system at the runtime.


2. It is helpful in testing a system.
3. It envisions the links between several connections.

When to use a Component Diagram?

It represents various physical components of a system at runtime. It is helpful in


visualizing the structure and the organization of a system. It describes how
individual components can together form a single system. Following are some
reasons, which tells when to use component diagram:

1. To divide a single system into multiple components according to the


functionality.
2. To represent the component organization of the system.

How to Draw a Component Diagram?

The component diagram is helpful in representing the physical aspects of a


system, which are files, executables, libraries, etc. The main purpose of a
component diagram is different from that of other diagrams. It is utilized in the
implementation phase of any application.

55
Once the system is designed employing different UML diagrams, and the artifacts
are prepared, the component diagram is used to get an idea of implementation. It
plays an essential role in implementing applications efficiently.

Following are some artifacts that are needed to be identified before drawing a
component diagram:

1. What files are used inside the system?


2. What is the application of relevant libraries and artifacts?
3. What is the relationship between the artifacts?

Following are some points that are needed to be kept in mind after the artifacts
are identified:

1. Using a meaningful name to ascertain the component for which the diagram
is about to be drawn.
2. Before producing the required tools, a mental layout is to be made.
3. To clarify the important points, notes can be incorporated.

Example of a Component Diagram

A component diagram for an online shopping system is given below:

Where to use Component Diagrams?

The component diagram is a special purpose diagram, which is used to visualize


the static implementation view of a system. It represents the physical

56
components of a system, or we can say it portrays the organization of the
components inside a system. The components, such as libraries, files,
executables, etc. are first needed to be organized before the implementation.

The component diagram can be used for the followings:

1. To model the components of the system.


2. To model the schemas of a database.
3. To model the applications of an application.
4. To model the system's source code.

UML DEPLOYMENT DIAGRAM

The deployment diagram visualizes the physical hardware on which the software
will be deployed. It portrays the static deployment view of a system. It involves
the nodes and their relationships.

It ascertains how software is deployed on the hardware. It maps the software


architecture created in design to the physical system architecture, where the
software will be executed as a node. Since it involves many nodes, the
relationship is shown by utilizing communication paths.

PURPOSE OF DEPLOYMENT DIAGRAM

The main purpose of the deployment diagram is to represent how software is


installed on the hardware component. It depicts in what manner a software
interacts with hardware to perform its execution.

Both the deployment diagram and the component diagram are closely interrelated
to each other as they focus on software and hardware components. The
component diagram represents the components of a system, whereas the
deployment diagram describes how they are actually deployed on the hardware.

The deployment diagram does not focus on the logical components of the system,
but it put its attention on the hardware topology.

Following are the purposes of deployment diagram enlisted below:

1. To envision the hardware topology of the system.


2. To represent the hardware components on which the software components
are installed.

57
3. To describe the processing of nodes at the runtime.

SYMBOL AND NOTATION OF DEPLOYMENT DIAGRAM

The deployment diagram consist of the following notations:

1. A component
2. An artifact
3. An interface
4. A node

HOW TO DRAW A DEPLOYMENT DIAGRAM?

The deployment diagram portrays the deployment view of the system. It helps in
visualizing the topological view of a system. It incorporates nodes, which are
physical hardware. The nodes are used to execute the artifacts. The instances of
artifacts can be deployed on the instances of nodes.

Since it plays a critical role during the administrative process, it involves the
following parameters:

1. High performance
2. Scalability
3. Maintainability
4. Portability
5. Easily understandable

58
One of the essential elements of the deployment diagram is the nodes and
artifacts. So it is necessary to identify all of the nodes and the relationship
between them. It becomes easier to develop a deployment diagram if all of the
nodes, artifacts, and their relationship is already known.

EXAMPLE OF A DEPLOYMENT DIAGRAM

A deployment diagram for the Apple iTunes application is given below.

The iTunes setup can be downloaded from the iTunes website, and also it can be
installed on the home computer. Once the installation and the registration are
done, iTunes application can easily interconnect with the Apple iTunes store.
Users can purchase and download music, video, TV serials, etc. and cache it in the
media library.

Devices like Apple iPod Touch and Apple iPhone can update its own media library
from the computer with iTunes with the help of USB or simply by downloading
media directly from the Apple iTunes store using wireless protocols, for example;
Wi-Fi, 3G, or EDGE.

59
When to use a Deployment Diagram?

The deployment diagram is mostly employed by network engineers, system


administrators, etc. with the purpose of representing the deployment of software
on the hardware system. It envisions the interaction of the software with the
hardware to accomplish the execution. The selected hardware must be of good
quality so that the software can work more efficiently at a faster rate by
producing accurate results in no time.

The software applications are quite complex these days, as they are standalone,
distributed, web-based, etc. So, it is very necessary to design efficient software.

Deployment diagrams can be used for the followings:

1. To model the network and hardware topology of a system.


2. To model the distributed networks and systems.
3. Implement forwarding and reverse engineering processes.
4. To model the hardware details for a client/server system.
5. For modeling the embedded system.

Module 3

OOAD - OBJECT ORIENTED DESIGN


After the analysis phase, the conceptual model is developed further into an
object-oriented model using object-oriented design (OOD). In OOD, the
technology-independent concepts in the analysis model are mapped onto
implementing classes, constraints are identified, and interfaces are designed,
resulting in a model for the solution domain. In a nutshell, a detailed description
is constructed specifying how the system is to be built on concrete technologies
The stages for object–oriented design can be identified as −

• Definition of the context of the system


• Designing system architecture
• Identification of the objects in the system
• Construction of design models
• Specification of object interfaces
System Design
Object-oriented system design involves defining the context of a system followed
by designing the architecture of the system.

60
• Context − The context of a system has a static and a dynamic part. The
static context of the system is designed using a simple block diagram
of the whole system which is expanded into a hierarchy of
subsystems. The subsystem model is represented by UML packages.
The dynamic context describes how the system interacts with its
environment. It is modelled using use case diagrams.
• System Architecture − The system architecture is designed on the
basis of the context of the system in accordance with the principles of
architectural design as well as domain knowledge. Typically, a system
is partitioned into layers and each layer is decomposed to form the
subsystems.

OBJECT-ORIENTED DECOMPOSITION
Decomposition means dividing a large complex system into a hierarchy of smaller
components with lesser complexities, on the principles of divide–and–conquer.
Each major component of the system is called a subsystem. Object-oriented
decomposition identifies individual autonomous objects in a system and the
communication among these objects.
The advantages of decomposition are −
• The individual components are of lesser complexity, and so more
understandable and manageable.
• It enables division of workforce having specialized skills.
• It allows subsystems to be replaced or modified without affecting
other subsystems.
IDENTIFYING CONCURRENCY
Concurrency allows more than one objects to receive events at the same time and
more than one activity to be executed simultaneously. Concurrency is identified
and represented in the dynamic model.
To enable concurrency, each concurrent element is assigned a separate thread of
control. If the concurrency is at object level, then two concurrent objects are
assigned two different threads of control. If two operations of a single object are
concurrent in nature, then that object is split among different threads.
Concurrency is associated with the problems of data integrity, deadlock, and
starvation. So a clear strategy needs to be made whenever concurrency is
required. Besides, concurrency requires to be identified at the design stage itself,
and cannot be left for implementation stage.
IDENTIFYING PATTERNS
While designing applications, some commonly accepted solutions are adopted for
some categories of problems. These are the patterns of design. A pattern can be
defined as a documented set of building blocks that can be used in certain types
of application development problems.

61
Some commonly used design patterns are −

• Façade pattern
• Model view separation pattern
• Observer pattern
• Model view controller pattern
• Publish subscribe pattern
• Proxy pattern
CONTROLLING EVENTS
During system design, the events that may occur in the objects of the system
need to be identified and appropriately dealt with.
An event is a specification of a significant occurrence that has a location in time
and space.
There are four types of events that can be modelled, namely −
• Signal Event − A named object thrown by one object and caught by
another object.
• Call Event − A synchronous event representing dispatch of an
operation.
• Time Event − An event representing passage of time.
• Change Event − An event representing change in state.
HANDLING BOUNDARY CONDITIONS
The system design phase needs to address the initialization and the termination
of the system as a whole as well as each subsystem. The different aspects that are
documented are as follows −
• The start–up of the system, i.e., the transition of the system from non-
initialized state to steady state.
• The termination of the system, i.e., the closing of all running threads,
cleaning up of resources, and the messages to be sent.
• The initial configuration of the system and the reconfiguration of the
system when needed.
• Foreseeing failures or undesired termination of the system.
Boundary conditions are modelled using boundary use cases.
OBJECT DESIGN
After the hierarchy of subsystems has been developed, the objects in the system
are identified and their details are designed. Here, the designer details out the
strategy chosen during the system design. The emphasis shifts from application
domain concepts toward computer concepts. The objects identified during
analysis are etched out for implementation with an aim to minimize execution
time, memory consumption, and overall cost.

62
Object design includes the following phases −

• Object identification
• Object representation, i.e., construction of design models
• Classification of operations
• Algorithm design
• Design of relationships
• Implementation of control for external interactions
• Package classes and associations into modules

OBJECT IDENTIFICATION
The first step of object design is object identification. The objects identified in
the object–oriented analysis phases are grouped into classes and refined so that
they are suitable for actual implementation.
The functions of this stage are −
• Identifying and refining the classes in each subsystem or package
• Defining the links and associations between the classes
• Designing the hierarchical associations among the classes, i.e., the
generalization/specialization and inheritances
• Designing aggregations
OBJECT REPRESENTATION
Once the classes are identified, they need to be represented using object
modelling techniques. This stage essentially involves constructing UML diagrams.
There are two types of design models that need to be produced −
• Static Models − To describe the static structure of a system using
class diagrams and object diagrams.
• Dynamic Models − To describe the dynamic structure of a system and
show the interaction between classes using interaction diagrams and
state–chart diagrams.
CLASSIFICATION OF OPERATIONS
In this step, the operation to be performed on objects are defined by combining
the three models developed in the OOA phase, namely, object model, dynamic
model, and functional model. An operation specifies what is to be done and not
how it should be done.
The following tasks are performed regarding operations −
• The state transition diagram of each object in the system is developed.
• Operations are defined for the events received by the objects.
• Cases in which one event triggers other events in same or different
objects are identified.

63
• The sub–operations within the actions are identified.
• The main actions are expanded to data flow diagrams.

ALGORITHM DESIGN

The operations in the objects are defined using algorithms. An algorithm is a


stepwise procedure that solves the problem laid down in an operation. Algorithms
focus on how it is to be done.
There may be more than one algorithm corresponding to a given operation. Once
the alternative algorithms are identified, the optimal algorithm is selected for the
given problem domain. The metrics for choosing the optimal algorithm are −
• Computational Complexity − Complexity determines the efficiency of
an algorithm in terms of computation time and memory requirements.
• Flexibility − Flexibility determines whether the chosen algorithm can
be implemented suitably, without loss of appropriateness in various
environments.
• Understandability − This determines whether the chosen algorithm is
easy to understand and implement.

DESIGN OF RELATIONSHIPS

The strategy to implement the relationships needs to be chalked out during the
object design phase. The main relationships that are addressed comprise of
associations, aggregations, and inheritances.
The designer should do the following regarding associations −
• Identify whether an association is unidirectional or bidirectional.
• Analyze the path of associations and update them if necessary.
• Implement the associations as a distinct object, in case of many–to-
many relationships; or as a link to other object in case of one–to-one
or one–to-many relationships.
Regarding inheritances, the designer should do the following −
• Adjust the classes and their associations.
• Identify abstract classes.
• Make provisions so that behaviors are shared when needed.

IMPLEMENTATION OF CONTROL
The object designer may incorporate refinements in the strategy of the state–
chart model. In system design, a basic strategy for realizing the dynamic model is
made. During object design, this strategy is aptly embellished for appropriate
implementation.

64
The approaches for implementation of the dynamic model are −
• Represent State as a Location within a Program − This is the
traditional procedure-driven approach whereby the location of control
defines the program state. A finite state machine can be implemented
as a program. A transition forms an input statement, the main control
path forms the sequence of instructions, the branches form the
conditions, and the backward paths form the loops or iterations.
• State Machine Engine − This approach directly represents a state
machine through a state machine engine class. This class executes the
state machine through a set of transitions and actions provided by the
application.
• Control as Concurrent Tasks − In this approach, an object is
implemented as a task in the programming language or the operating
system. Here, an event is implemented as an inter-task call. It
preserves inherent concurrency of real objects.

PACKAGING CLASSES
In any large project, meticulous partitioning of an implementation into modules
or packages is important. During object design, classes and objects are grouped
into packages to enable multiple groups to work cooperatively on a project.
The different aspects of packaging are −
• Hiding Internal Information from Outside View − It allows a class to
be viewed as a “black box” and permits class implementation to be
changed without requiring any clients of the class to modify code.
• Coherence of Elements − An element, such as a class, an operation, or
a module, is coherent if it is organized on a consistent plan and all its
parts are intrinsically related so that they serve a common goal.
• Construction of Physical Modules − The following guidelines help
while constructing physical modules −
o Classes in a module should represent similar things or
components in the same composite object.
o Closely connected classes should be in the same module.
o Unconnected or weakly connected classes should be placed
in separate modules.
o Modules should have good cohesion, i.e., high cooperation
among its components.
o A module should have low coupling with other modules,
i.e., interaction or interdependence between modules
should be minimum.

65
DESIGN OPTIMIZATION
The analysis model captures the logical information about the system, while the
design model adds details to support efficient information access. Before a design
is implemented, it should be optimized so as to make the implementation more
efficient. The aim of optimization is to minimize the cost in terms of time, space,
and other metrics.
However, design optimization should not be excess, as ease of implementation,
maintainability, and extensibility are also important concerns. It is often seen that
a perfectly optimized design is more efficient but less readable and reusable. So
the designer must strike a balance between the two.
The various things that may be done for design optimization are −

• Add redundant associations


• Omit non-usable associations
• Optimization of algorithms
• Save derived attributes to avoid re-computation of complex
expressions
ADDITION OF REDUNDANT ASSOCIATIONS
During design optimization, it is checked if deriving new associations can reduce
access costs. Though these redundant associations may not add any information,
they may increase the efficiency of the overall model.

Omission of Non-Usable Associations


Presence of too many associations may render a system indecipherable and hence
reduce the overall efficiency of the system. So, during optimization, all non-
usable associations are removed.

Optimization of Algorithms
In object-oriented systems, optimization of data structure and algorithms are
done in a collaborative manner. Once the class design is in place, the operations
and the algorithms need to be optimized.
Optimization of algorithms is obtained by −

• Rearrangement of the order of computational tasks


• Reversal of execution order of loops from that laid down in the
functional model
• Removal of dead paths within the algorithm

66
Saving and Storing of Derived Attributes
Derived attributes are those attributes whose values are computed as a function
of other attributes (base attributes). Re-computation of the values of derived
attributes every time they are needed is a time–consuming procedure. To avoid
this, the values can be computed and stored in their computed forms.
However, this may pose update anomalies, i.e., a change in the values of base
attributes with no corresponding change in the values of the derived attributes.
To avoid this, the following steps are taken −
• With each update of the base attribute value, the derived attribute is
also re-computed.
• All the derived attributes are re-computed and updated periodically in
a group rather than after each update.

DESIGN DOCUMENTATION
Documentation is an essential part of any software development process that
records the procedure of making the software. The design decisions need to be
documented for any non–trivial software system for transmitting the design to
others.

Usage Areas
Though a secondary product, a good documentation is indispensable, particularly
in the following areas −

• In designing software that is being developed by a number of


developers
• In iterative software development strategies
• In developing subsequent versions of a software project
• For evaluating a software
• For finding conditions and areas of testing
• For maintenance of the software.
Contents
A beneficial documentation should essentially include the following contents −
• High–level system architecture − Process diagrams and module
diagrams
• Key abstractions and mechanisms − Class diagrams and object
diagrams.
• Scenarios that illustrate the behavior of the main aspects −
Behavioural diagrams
Features

67
The features of a good documentation are −
• Concise and at the same time, unambiguous, consistent, and complete
• Traceable to the system’s requirement specifications
• Well-structured
• Diagrammatic instead of descriptive

MODULE 3-

DOMAIN MODELING-

Domain modeling- Is understood as abstract modeling. a site model could be an


illustration of the ideas or objects shown within the drawback domain. It
additionally captures the apparent relationships among these objects. samples of
such abstract objects area unit the Book, Book Register, member register, Library
Member, etc. The counselled strategy is to quickly produce a rough abstract
model wherever the stress is finding the apparent ideas expressed within the
needs whereas deferring an in-depth investigation. Later throughout the event
method, the abstract model is incrementally refined and extended. The 3 sorts of
objects are known throughout domain analysis. The objects known throughout
domain analysis are classified into 3 types:

-Boundary objects
-Controller objects
-Entity objects

The boundary and controller objects are consistently known from the employment case
diagram whereas the identification of entity objects needs to apply. So, the crux of the
domain modeling activity is to spot the entity models

The different styles of objects known throughout domain analysis and the area of their
relationship unit as follows:

The boundary objects area unit those with that the actors move. These embrace screens,
menus, forms, dialogs, etc. The boundary objects area unit is chiefly answerable for user
interaction. Therefore, they ordinarily don’t embrace any process logic. However, they
will be answerable for confirming inputs, formatting, outputs, etc. The boundary objects
were earlier known as because of the interface objects. However, the term interface
category is getting used for Java, COM/DCOM, and UML with completely different means.
A recommendation for the initial identification of the boundary categories is to outline
one boundary category per actor/use case try.

Entity objects: These ordinarily hold info like information tables and files that require
to outlast use case execution, e.g. Book, BookRegister, LibraryMember, etc. several of the
entity objects area unit “dumb servers”. they’re ordinarily answerable for storing

68
information, winning information, and performing some elementary styles of operation
that don’t amendment usually.
Controller objects: The controller objects coordinate the activities of a collection of
entity objects and interface with the boundary objects to produce the general behavior of
the system. The responsibilities appointed to a controller object area unit are closely
associated with the belief of a particular use case. The controller objects effectively
decouple the boundary and entity objects from each other creating a system tolerant to
changes in the computer program and process logic.
The controller objects embody most of the logic committed to the employment case
realization (this logic might amendment time to time). A typical interaction of a controller
object with boundary and entity objects is shown below(figure) Normally, every use case
is complete victimization of one controller object. However, some use cases are complete
while not victimization any controller object, i.e. through boundary and entity objects

solely. This is often true to be used cases that win just some easy manipulation of the
hold on info.
For example, let’s take into account the “query book availability” use case of the Library
data system (LIS). Realization of the employment case involves solely matching the given
book name against the books offered within the catalog. additional complicated use
cases might need quite one controller object to understand the employment case. a fancy
use case will have many controller objects like group action manager, resource arranger,
and error handler. there’s another state of affairs wherever a use case will have quite one
controller object. generally, the employment cases need the controller object to transit
through a variety of states. In such cases, one controller object may need to be created
for every execution of the employment case.

MODULE 4

SOLID PRINCIPLE IN PROGRAMMING:

In software development, Object-Oriented Design plays a crucial role when it


comes to writing flexible, scalable, maintainable, and reusable code. There are so

69
many benefits of using OOD but every developer should also have the knowledge
of the SOLID principle for good object-oriented design in programming. The
SOLID principle was introduced by Robert C. Martin, also known as Uncle
Bob and it is a coding standard in programming. This principle is an acronym of
the five principles which is given below…

Single Responsibility Principle (SRP)

Open/Closed Principle (OCP)

Liskov’s Substitution Principle (LSP)

Interface Segregation Principle (ISP)

Dependency Inversion Principle (DIP)

The SOLID principle helps in reducing tight coupling. Tight coupling means a
group of classes are highly dependent on one another which you should avoid in
your code. Opposite of tight coupling is loose coupling and your code is
considered as a good code when it has loosely-coupled classes. Loosely coupled
classes minimize changes in your code, helps in making code more reusable,
maintainable, flexible and stable. Now let’s discuss one by one these principles…

1. SINGLE RESPONSIBILITY PRINCIPLE: This principle states that “a class should


have only one reason to change” which means every class should have a single
responsibility or single job or single purpose. Take the example of developing
software. The task is divided into different members doing different things as
front-end designers do design, the tester does testing and backend developer
takes care of backend development part then we can say that everyone has a
single job or responsibility.
Most of the time it happens that when programmers have to add features or new
behavior they implement everything into the existing class which is completely
wrong. It makes their code lengthy, complex and consumes time when later
something needs to be modified. Use layers in your application and break God
classes into smaller classes or modules.

2. OPEN/CLOSED PRINCIPLE: This principle states that “software entities (classes,


modules, functions, etc.) should be open for extension, but closed for
modification” which means you should be able to extend a class behavior, without
modifying it.
Suppose developer A needs to release an update for a library or framework and
developer B wants some modification or add some feature on that then developer
B is allowed to extend the existing class created by developer A but developer B is

70
not supposed to modify the class directly. Using this principle separates the
existing code from the modified code so it provides better stability,
maintainability and minimizes changes as in your code.

3. LISKOV’S SUBSTITUTION PRINCIPLE: The principle was introduced by Barbara


Liskov in 1987 and according to this principle “Derived or child classes must be
substitutable for their base or parent classes“. This principle ensures that any
class that is the child of a parent class should be usable in place of its parent
without any unexpected behavior.
You can understand it in a way that a farmer’s son should inherit farming skills
from his father and should be able to replace his father if needed. If the son wants
to become a farmer then he can replace his father but if he wants to become a
cricketer then definitely the son can’t replace his father even though they both
belong to the same family hierarchy.
One of the classic examples of this principle is a rectangle having four sides. A
rectangle’s height can be any value and width can be any value. A square is a
rectangle with equal width and height. So we can say that we can extend the
properties of the rectangle class into square class. In order to do that you need to
swap the child (square) class with parent (rectangle) class to fit the definition of a
square having four equal sides but a derived class does not affect the behavior of
the parent class so if you will do that it will violate the Liskov Substitution
Principle. Check the link Liskov Substitution Principle for better understanding.

4. INTERFACE SEGREGATION PRINCIPLE: This principle is the first principle that


applies to Interfaces instead of classes in SOLID and it is similar to the single
responsibility principle. It states that “do not force any client to implement an
interface which is irrelevant to them“. Here your main goal is to focus on avoiding
fat interface and give preference to many small client-specific interfaces. You
should prefer many client interfaces rather than one general interface and each
interface should have a specific responsibility.
Suppose if you enter a restaurant and you are pure vegetarian. The waiter in that
restaurant gave you the menu card which includes vegetarian items, non-
vegetarian items, drinks, and sweets. In this case, as a customer, you should have
a menu card which includes only vegetarian items, not everything which you
don’t eat in your food. Here the menu should be different for different types of
customers. The common or general menu card for everyone can be divided into
multiple cards instead of just one. Using this principle helps in reducing the side
effects and frequency of required changes.

5.DEPENDENCY INVERSION PRINCIPLE: Before we discuss this topic keep in mind


that Dependency Inversion and Dependency Injection both are different concepts.
Most of the people get confused about it and consider both are the same. Now two
key points are here to keep in mind about this principle

71
High-level modules/classes should not depend on low-level modules/classes. Both
should depend upon abstractions.

Abstractions should not depend upon details. Details should depend upon
abstractions.

The above lines simply state that if a high module or class will be dependent
more on low-level modules or class then your code would have tight coupling and
if you will try to make a change in one class it can break another class which is
risky at the production level. So always try to make classes loosely coupled as
much as you can and you can achieve this through abstraction. The main motive
of this principle is decoupling the dependencies so if class A changes the class B
doesn’t need to care or know about the changes.
You can consider the real-life example of a TV remote battery. Your remote needs
a battery but it’s not dependent on the battery brand. You can use any XYZ brand
that you want and it will work. So we can say that the TV remote is loosely
coupled with the brand name. Dependency Inversion makes your code more
reusable.

Martin’s Package metrics


In 1994 Robert “Uncle Bob” Martin proposed a group of object-oriented metrics that are
popular until now. Those metrics, unlike other object-oriented ones don’t represent the full
set of attributes to assess individual object-oriented design, they only focus on the
relationship between packages in the project.
The level of detail of Martin’s metrics is still lower than the one of CK’s metrics.

Martin’s metrics include:

• Efferent Coupling (Ce)

• Afferent Coupling (Ca)

• Instability (I)

• Abstractness (A)

• Normalized Distance from Main Sequence (D)

72
Efferent Coupling (Ce)

This metric is used to measure interrelationships between classes. As defined, it is a number


of classes in a given package, which depends on the classes in other packages. It enables us
to measure the vulnerability of the package to changes in packages on which it depends.

Pic. 1 – Outgoing dependencies

In the pic.1 it can be seen that class A has outgoing dependencies to 3 other classes, that is
why metric Ce for this class is 3.

The high value of the metric Ce> 20 indicates instability of a package, change in any of the
numerous external classes can cause the need for changes to the package. Preferred values
for the metric Ce are in the range of 0 to 20, higher values cause problems with care and
development of code.

Afferent Coupling (Ca)

This metric is an addition to metric Ce and is used to measure another type of dependencies
between packages, i.e. incoming dependencies. It enables us to measure the sensitivity of
remaining packages to changes in the analysed package.

Pic. 2 – Incoming dependencies

in the pic.2 it can be seen that class A has only 1 incoming dependency (from class X), that is
why the value for metrics Ca equals 1.

73
High values of metric Ca usually suggest high component stability. This is due to the fact that
the class depends on many other classes. Therefore, it can’t be modified significantly
because, in this case, the probability of spreading such changes increases.

Preferred values for the metric Ca are in the range of 0 to 500.

Instability (I)

This metric is used to measure the relative susceptibility of class to changes. According to the
definition instability is the ration of outgoing dependencies to all package dependencies and
it accepts value from 0 to 1.

The metric is defined according to the formula:

Where: Ce – outgoing dependencies, Ca – incoming dependencies

Pic. 3 – Instability

In the pic.3 it can be seen that class A has 3 outgoing and 1 incoming dependencies, therefore
according to the formula value of metric I will equal 0,75.

On the basis of value of metric I we can distinguish two types of components:

74
• The ones having many outgoing dependencies and not many of incoming ones (value I
is close to 1), which are rather unstable due to the possibility of easy changes to these
packages;

• The ones having many incoming dependencies and not many of outgoing ones (value I
is close to 0), therefore they are rather more difficult in modifying due to their greater
responsibility.

Preferred values for the metric I should fall within the ranges of 0 to 0.3 or 0.7 to 1. Packages
should be very stable or unstable, therefore we should avoid packages of intermediate
stability.

Abstractness (A)

This metric is used to measure the degree of abstraction of the package and is somewhat
similar to the instability. Regarding the definition, abstractness is the number of abstract
classes in the package to the number of all classes.

The metric is defined according to the formula:

Where: T abstract – number of abstract classes in a package, T concrete – number of concrete classes in a
package

Preferred values for the metric A should take extreme values close to 0 or 1. Packages that are
stable (metric I close to 0), which means they are dependent at a very low level on other

75
packages, should also be abstract (metric A close to 1). In turn, the very unstable packages
(metric I close to 1) should consist of concrete classes (A metric close to 0).

Additionally, it is worth mentioning that combining abstractness and stability enabled Martin
to formulate thesis about the existence of main sequence (Pic. 4).

Pic. 4 – Main sequence

In the optimal case, the instability of the class is compensated by its abstractness, there is an
equation I + A = 1. Classes that were well designed should group themselves around this
graph end points along the main sequence.

Normalized Distance from Main Sequence (D)

This metric is used to measure the balance between stability and abstractness and is
calculated using the following formula:

Where: A- abstractness, I – instability

The value of metric D may be interpreted in the following way; if we put a given class on a
graph of the main sequence (Pic. 5) its distance from the main sequence will be proportional
to the value of D.

76
Pic. 5 – Normalized distance from Main Sequence

The value of the metric D should be as low as possible so that the components were located
close to the main sequence. In addition, the two extremely unfavourable cases are considered:

• A = 0 and I = 0, a package is extremely stable and concrete, the situation is undesirable


because the package is very stiff and can’t be extended;

• A = 1 and I = 1, rather impossible situation because a completely abstract package


must have some connection to the outside, so that the instance that implements the
functionality defined in abstract classes contained in this package could be created.

Summary

Using Martin’s metrics we can easily assess the relationships between the packages in the
project and determine whether it is necessary to carry out the changes so as to avoid any
possible problems in the future. All metrics discussed in this article can be measured for
projects in .NET using NDepend tool.

CK metrics

The Chidamber & Kemerer metrics suite originally consists of 6 metrics calculated
for each class: WMC, DIT, NOC, CBO, RFC and LCOM1.

77
WMC Weighted Methods Per Class

Despite its long name, WMC is simply the method count for a class.

WMC = number of methods defined in class

Keep WMC down. A high WMC has been found to lead to more faults. Classes with
many methods are likely to be more more application specific, limiting the
possibility of reuse. WMC is a predictor of how much time and effort is required
to develop and maintain the class. A large number of methods also means a
greater potential impact on derived classes, since the derived classes inherit
(some of) the methods of the base class. Search for high WMC values to spot
classes that could be restructured into several smaller classes

DIT Depth of Inheritance Tree


DIT = maximum inheritance path from the class to the root class

The deeper a class is in the hierarchy, the more methods and variables it is likely
to inherit, making it more complex. Deep trees as such indicate greater design
complexity. Inheritance is a tool to manage complexity, really, not to not increase
it. As a positive factor, deep trees promote reuse because of method inheritance.

NOC Number of Children


NOC = number of immediate sub-classes of a class

NOC equals the number of immediate child classes derived from a base class. In Visual Basic .NET
one uses the Inherits statement to derive sub-classes. In classic Visual Basic inheritance is not
available and thus NOC is always zero.

A high NOC, a large number of child classes, can indicate several things:

• High reuse of base class. Inheritance is a form of reuse.


• Base class may require more testing.
• Improper abstraction of the parent class.
• Misuse of sub-classing. In such a case, it may be necessary to group related classes and
introduce another level of inheritance.

CBO Coupling between Object Classes


CBO = number of classes to which a class is coupled

Two classes are coupled when methods declared in one class use methods or instance variables
defined by the other class. The uses relationship can go either way: both uses and used-by
relationships are taken into account, but only once.

78
RFC and RFC´ Response for a Class

The response set of a class is a set of methods that can potentially be executed in response to a
message received by an object of that class. RFC is simply the number of methods in the set.

RFC = M + R (First-step measure)


RFC’ = M + R’ (Full measure)
M = number of methods in the class
R = number of remote methods directly called by methods of the class
R’ = number of remote methods called, recursively through the entire call tree

A given method is counted only once in R (and R’) even if it is executed by several methods M.

LCOM1 Lack of Cohesion of Methods

The 6th metric in the Chidamber & Kemerer metrics suite is LCOM (or LOCOM), the lack of
cohesion of methods. This metric has received a great deal of critique and several alternatives
have been developed. In Project Metrics we call the original Chidamber & Kemerer metric LCOM1
to distinguish it from the alternatives.

MODULE 5-

Design Pattern - Overview


Design patterns represent the best practices used by experienced object-oriented
software developers. Design patterns are solutions to general problems that
software developers faced during software development. These solutions were
obtained by trial and error by numerous software developers over quite a
substantial period of time.
WHAT IS GANG OF FOUR (GOF)?
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John
Vlissides published a book titled Design Patterns - Elements of Reusable Object-
Oriented Software which initiated the concept of Design Pattern in Software
development.
These authors are collectively known as Gang of Four (GOF). According to these
authors design patterns are primarily based on the following principles of object
orientated design.
• Program to an interface not an implementation
• Favor object composition over inheritance
Usage of Design Pattern
Design Patterns have two main usages in software development.

Common platform for developers


79
Design patterns provide a standard terminology and are specific to particular
scenario. For example, a singleton design pattern signifies use of single object so
all developers familiar with single design pattern will make use of single object
and they can tell each other that program is following a singleton pattern.

Best Practices
Design patterns have been evolved over a long period of time and they provide
best solutions to certain problems faced during software development. Learning
these patterns helps unexperienced developers to learn software design in an
easy and faster way.
Types of Design Patterns
As per the design pattern reference book Design Patterns - Elements of Reusable
Object-Oriented Software , there are 23 design patterns which can be classified
in three categories: Creational, Structural and Behavioral patterns. We'll also
discuss another category of design pattern: J2EE design patterns.

S.N. Pattern & Description

1 Creational Patterns
These design patterns provide a way to create objects while hiding
the creation logic, rather than instantiating objects directly using
new operator. This gives program more flexibility in deciding which
objects need to be created for a given use case.

2 Structural Patterns
These design patterns concern class and object composition.
Concept of inheritance is used to compose interfaces and define
ways to compose objects to obtain new functionalities.

3 Behavioral Patterns
These design patterns are specifically concerned with
communication between objects.

4 J2EE Patterns
These design patterns are specifically concerned with the
presentation tier. These patterns are identified by Sun Java Center.

Software Engineering | Architectural Design


The software needs the architectural design to represents the design of software. IEEE
defines architectural design as “the process of defining a collection of hardware and
software components and their interfaces to establish the framework for the
development of a computer system.” The software that is built for computer-based
systems can exhibit one of these many architectural styles.
Each style will describe a system category that consists of :

80
-
A set of components(eg: a database, computational modules) that will
perform a function required by the system.
- The set of connectors will help in coordination, communication, and
cooperation between the components.
- Conditions that how components can be integrated to form the system.
- Semantic models that help the designer to understand the overall properties
of the system.
- The use of architectural styles is to establish a structure for all the
components of the system.
TAXONOMY OF ARCHITECTURAL STYLES:

DATA CENTERED ARCHITECTURES:


The use of architectural styles is to establish a structure for all the components of the
system.
Taxonomy of architectural styles:
1. Data centered architecture :
- A data store will reside at the center of this architecture and is accessed
frequently by the other components that update, add, delete or modify the
data present within the store.
- The figure illustrates a typical data centered style. The client software access
a central repository. Variation of this approach are used to transform the
repository into a blackboard when data related to client or data of interest
for the client change the notifications to client software.
- This data-centered architecture will promote integrability. This means that
the existing components can be changed and new client components can be
added to the architecture without the permission or concern of other clients.
- Data can be passed among clients using blackboard mechanism.
Advantage of Data centered architecture
Advantage of Data centered Architecture
- Repository of data is independent of clients
- Client work independent of each other
- It may be simple to add additional clients.
- Modification can be very easy

Data centered architecture


Data flow architectures:
1. Data flow architectures:

81
- This kind of architecture is used when input data to be transformed into
output data through a series of computational manipulative components.
- The figure represents pipe-and-filter architecture since it uses both pipe and
filter and it has a set of components called filters connected by pipes.
- Pipes are used to transmit data from one component to the next.
- Each filter will work independently and is designed to take data input of a
certain form and produces data output to the next filter of a specified form.
The filters don’t require any knowledge of the working of neighboring
filters.
- If the data flow degenerates into a single line of transforms, then it is termed
as batch sequential. This structure accepts the batch of data and then
applies a series of sequential components to transform it.
Advantage of Data Flow architecture
Advantages of DataFlow Architecture:
- It encourages upkeep, repurposing, and modification.
- With this design, concurrent execution is supported.
Disadvantage of Data Flow architecture
Disadvantages of DataFlow Architecture:
- It frequently degenerates to batch sequential system
- Data flow architecture does not allow applications that require greater user
engagement.
- It is not easy to coordinate two different but related streams

Data Flow architecture


1. CALL AND RETURN ARCHITECTURES: is used to create a program that is easy to
scale and modify. Many sub-styles exist within this category. Two of them are
explained below.
- REMOTE PROCEDURE CALL ARCHITECTURE- This components is used to
present in a main program or sub program architecture distributed among
multiple computers on a network.
- MAIN PROGRAM OR SUB PROGRAM ARCHITECTURE: The main program
structure decomposes into number of subprograms or function into a
control hierarchy. Main program contains number of subprograms that can

82
invoke other components.

1. OBJECT ORIENTED ARCHITECTURE: The components of a


system encapsulate data and the operations that must be
applied to manipulate the data. The coordination and
communication between the components are established via the
message passing.
Characteristics of Object Oriented architecture
CHARACTERISTICS OF OBJECT ORIENTED ARCHITECTURE
- Object protect the system’s integrity.
- An object is unaware of the depiction of other items.
Advantage of Object Orientedarchitecture
Advantages of Object Oriented Architecture:
- It enables the designer to separate a challenge into a collection of
autonomous objects.
- Other objects are aware of the implementation details of the object,
allowing changes to be made without having an impact on other
objects.ered architecture:

2. LAYERED ARCHITECTURE:
- A number of different layers are defined with each layer performing a
well-defined set of operations. Each layer will do some operations that
becomes closer to machine instruction set progressively.
- At the outer layer, components will receive the user interface
operations and at the inner layers, components will perform the
operating system interfacing(communication and coordination with
OS)
- Intermediate layers to utility services and application software
functions.
- One common example of this architectural style is OSI-ISO (Open
Systems Interconnection-International Organisation for
Standardisation) communication system.

83
• GRASP

General Responsibility Assignment Software Patterns (or
Principles), abbreviated
• GRASP, consists of guidelines for assigning responsibility to
classes and objects in object-oriented design.

• The different patterns and principles used in GRASP are:
Information Expert, Creator, Controller, Low Coupling, High
Cohesion, Polymorphism, Pure Fabrication, Indirection, Protected
Variations. All these patterns answer some software problem,
and in almost every case these problems are common to almost
every software development project. These techniques have not
been invented to create new ways of working but to better
document and standardize old, tried-and-tested programming
principles in object oriented design.

• It has been said that "the critical design tool for software
development is a mind well educated in design principles. It is
not the UML or any other technology". Thus, GRASP is really a
mental toolset, a learning aid to help in the design of object
oriented software.

Creator
Creation of objects is one of the most common activities in an
object-oriented system. Which class is responsible for creating
objects is a fundamental property of the relationship between
objects of particular classes.

In general, a class B should be responsible for creating instances


of class A if one, or preferably more, of the following apply:

Instances of B contains or compositely aggregates instances of A


Instances of B record instances of A
Instances of B closely use instances of A

84
Instances of B have the initializing information for instances of A
and pass it on creation.

INFORMATION EXPERT

Information Expert is a principle used to determine where to


delegate responsibilities. These responsibilities include methods,
computed fields and so on.

Using the principle of Information Expert a general approach to


assigning responsibilities is to look at a given responsibility,
determine the information needed to fulfill it, and then determine
where that information is stored. Information Expert will lead to
placing the responsibility on the class with the most information
required to fulfill it.

LOW COUPLING

Low Coupling is an evaluative pattern, which dictates how to assign


responsibilities to support:

low dependency between classes;


low impact in a class of changes in other classes;
high reuse potential

CONTROLLER

The Controller pattern assigns the responsibility of dealing with


system events to a non-UI class that represent the overall system or
a use case scenario. A Controller object is a non-user interface
object responsible for receiving or handling a system event. A use
case controller should be used to deal with all system events of a
use case, and may be used for more than one use case (for instance,
for use cases Create User and Delete User, one can have one
UserController, instead of two separate use case controllers).

It is defined as the first object beyond the UI layer that receives


and coordinates ("controls") a system operation. The controller
should delegate to other objects the work that needs to be done; it
85
coordinates or controls the activity. It should not do much work
itself. The GRASP Controller can be thought of as being a part of the
Application/Service layer (assuming that the application has made
an explicit distinction between the App/Service layer and the
Domain layer) in an object-oriented system with common layers.

High Cohesion
High Cohesion is an evaluative pattern that attempts to keep objects
appropriately focused, manageable and understandable. High
cohesion is generally used in support of Low Coupling.

High cohesion means that the responsibilities of a given element


are strongly related and highly focused. Breaking programs into
classes and subsystems is an example of activities that increase
the cohesive properties of a system. Alternatively, low cohesion
is a situation in which a given element has too many unrelated
responsibilities.

Elements with low cohesion often suffer from being hard to


comprehend, hard to reuse, hard to maintain and adverse to
change.

Polymorphism

According to Polymorphism, responsibility of defining the


variation of behaviors based on type is assigned to the types for
which this variation happens. This is achieved using
polymorphic operations.

Pure Fabrication

A pure fabrication is a class that does not represent a concept in


the problem domain, specially made up to achieve low coupling,
high cohesion, and the reuse potential thereof derived (when a
solution presented by the Information Expert pattern does not).
This kind of class is called "Service" in Domain-driven design.

Indirection
86
The Indirection pattern supports low coupling (and reuse
potential) between two elements by assigning the responsibility
of mediation between them to an intermediate object. An
example of this is the introduction of a controller component for
mediation between data (model) and its representation (view) in
the Model-view-controller pattern.

Protected Variations

The Protected Variations pattern protects elements from the


variations on other elements (objects, systems, subsystems) by
wrapping the focus of instability with an interface and using
polymorphism to create various implementations of this
interface.

VISIBILITY

Creational Design Patterns

In software engineering, creational design patterns are design


patterns that deal with object creation mechanisms, trying to
create objects in a manner suitable to the situation. The basic
form of object creation could result in design problems or added
complexity to the design.
Creational design patterns solve this problem by somehow
controlling this object creation. In object-oriented design, there
is a notation of visibility for attributes and operations. UML
identifies four types of visibility: public, protected, private, and
package.

The UML specification does not require attributes and operations


visibility to be displayed on the class diagram, but it does
require that it be defined for each attribute or operation.

To display visibility on the class diagram, you place the visibility


mark in front of the attribute's or operation's name. Though UML
specifies four visibility types, an actual programming language

87
may add additional visibilities, or it may not support the UML-
defined visibilities

Mark Visibility type

+ Public

# Protected

- Private

~ Package

A BankAccount class that shows the visibility of its attributes


and operations

Visibility - the ability of one object to “see” or have a reference


to another object.

Visibility is required for one object to message another.

8. APPLYING GOF DESIGN PATTERNS:

Design patterns represent common software problems and the


solutions to those problems in a formal manner. They were
inspired by a book written by architect Christopher Alexander.
Patterns were introduced in the software world by another book:
"Design Patterns: Elements of Reusable Object-Oriented
Software", by Erich Gamma, Richard Helm, Ralph Johnson, and
John Vlissides. These people were nicknamed the "Gang of Four"

88
for some mysterious reason. The Gang of Four describes 23
design patterns.

With patterns you don't have to reinvent the wheel and get proven
solutions for frequently encountered problems. Many books and
articles have been written on this subject. This means that design
patterns are becoming common knowledge, which leads to better
communication. To summarize design patterns save time, energy
while making your life easier.

Singleton

The singleton pattern deals with situations where only one instance of
a class must be created. Take the case of a system administrator or
superuser. This person has the right to do everything in a computer
system. In addition we will also have classes representing normal
users. Therefore we must ensure that these classes have no access to
the super user constructor. The solution to this problem in C++ and
Java is to declare the superuser constructor private.

The super user class itself has a private static attribute sysadmin,
which is initialised using the class constructor. Now we get an
instance of the super user class with a public static method that
returns sysadmin. Here is the class diagram:

Factory Method

The Factory Method pattern deals with situations where at


runtime one of several similar classes must be created. Visualise
this as a factory that produces objects. In a toy factory for
instance we have the abstract concept of toy.

Every time we get a request for a new toy a decision must be


made - what kind of a toy to manufacture. Similarly to the
89
Singleton pattern the Factory Method pattern utilises a public
static accessor method. In our example the abstract Toyfactory
class will have a getInstance() method, which is inherited by its
non abstract subclasses.

Adapter

Sometimes it will have two classes that can in principle work well
together, but they can't interface with each other for some
reason. This kind of problem occurs when travelling abroad and
you carry an electric shaver with you.

Although it will work perfectly when you are at home. There can
be problems in a foreign country, because of a different standard
voltage. The solution is to use an adapter. Let's turn our
attention back to the software domain. Here we will have an
interface which defines new methods for example getElectricity2.

An adapter class will wrap around the Shaver class. The adapter
class will implement the interface with the new method.

90
Proxy

The Proxy pattern deals with situations where you have a


complex object or it takes a long time to create the object. The
solution to this problem is to replace the complex object with a
simple 'stub' object that has the same interface.

The stub acts as a body double. This is the strategy used by the
Java Remote Method Invocation API. The reason to use the proxy
pattern in this case is that the object is on a remote server
causing network overhead. Other reasons to use the proxy can be
restricted access (Java applets for example) or time consuming
calculations.

Decorator

The Decorator is usually a subclass, that is a body double for its


superclass or another class with identical interface. The goal of

91
the Decorator pattern is to add or improve the capabilities of the
super class.

Composite

The composite is often encountered in GUI packages like for


instance the Java Abstract Windwing Toolkit (AWT) or Microsoft
Foundation (MFC) classes. All objects in this pattern have a
common abstract superclass that descibes basic object conduct.
The base class in the MFC hierarchy is CObject. It provides
functions for debugging and serialization. All the MFC classes
even the most basic ones inherit these facilities.

Observer and MVC

An application with Model - View - Controller setup usually uses


the Observer Pattern. In a Java webserver environment the model
will be represented by Java classes encompassing the business
logic, the view is represented by Java Server Pages which display

92
HTML in the client's browser and we will have a Servlets as
Controllers.

The observer pattern strategy is to have view components take


subscriptions for their model. This ensures that they will get
notified if the model changes.

Template

In the good old days before OOP writing functions was the
recommended thing to do. A sort algorithm would be implement
by half dozen of functions, one sort function for integers, one
sort function for floating points, one sort function for doubles
etc.

These functions are so similar that nobody in their right mind


will type them letter by letter. Instead a programmer will write a
template and copy the template several times. After that it's just
a matter of writing down datatypes as appropriate. Thanks to
OOP and the Template Design Pattern less code is required for
this task.

Define an abstract Template class let's call it SortTemplate and it


will have methods sort, compare and process (performs one
cycle of the algorithm). Then we define classes for each
datatype. These classes are subclasses of SortTemplate and
implement the compare and process methods.

93
Strategy

The Strategy Design Pattern makes it possible chooses an


implementation of an algorithm at run time. The implementation
classes implement the same interface. In the case of the Java
AWT Layout classes, the common interface is Layout Manager.

Summary

Design patterns are a hot research item. New patterns are


emerging every day. In the future design patterns will be
integrated in development tools. The main advantages of design
patterns:

1. Provide proven solutions

2. Simplify complex problems


94
3. Improve communication

Classification and list

Design patterns were originally grouped into the categories:


creational patterns, structural patterns, and behavioral patterns,
and described using the concepts of delegation, aggregation, and
consultation.
For further background on object-oriented design, see coupling
and cohesion, inheritance, interface, and polymorphism. Another
classification has also introduced the notion of architectural
design pattern that may be applied at the architecture level of
the software such as the Model-View-Controller pattern.

Creational Design Patterns

In software engineering, creational design patterns are design


patterns that deal with object creation mechanisms, trying to create
objects in a manner suitable to the situation.

The basic form of object creation could result in design problems or


added complexity to the design. Creational design patterns solve this
problem by somehow controlling this object creation

What is Gang Of Four?


The Gang Of Four are the authors of the Book “Design Patterns: Elements of
Reusable Object-Oriented Software”.

It’s an important book describing twenty-three Object-Oriented Design


Patterns & various development techniques. The four authors are:

1. Erich Gamma

2. Ralph Johnson

95
3. John Vlissides

4. Richard Helm

Overview
I am not gonna describe complete book here but a small picture to
develop your interest in reading this book.

For better understanding, Gang Of Four described each design pattern


with a UML diagram by taking real-world examples with coding.

They categorized all design patterns into three categories.

1. Creational Patterns

2. Structural Patterns

3. Behavioral Patterns

#1) Creational Patterns


The first design pattern is the creational pattern. It provides ways to
instantiate single objects or groups of related objects. There are five such
patterns:

• Abstract Factory: Provide an interface for creating families of


related or dependent objects without specifying their concrete
classes.

• Builder: Separate the construction of a complex object from its


representation so that the same construction process can create
different representations.

96
• Factory Method: Define an interface for creating an object, but
let subclasses decide which class to instantiate. Factory Method
lets a class defer instantiation to subclasses.

• Prototype: Specify the kinds of objects to create using a


prototypical instance, and create new objects by copying this
prototype.

• Singleton: Ensure a class only has one instance, and provide a


global point of access to it.

#2) Structural Patterns


The second type of design pattern is the structural pattern. It provides a
manner to define relationships between classes or objects.

• Adapter: Convert the interface of a class into another interface


clients expect. Adapter lets classes work together that couldn’t
otherwise because of incompatible interfaces.

• Bridge: Decouple an abstraction from its implementation so that


the two can vary independently.

• Composite: Compose objects into tree structures to represent


part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.

• Decorator: Attach additional responsibilities to an object


dynamically. Decorators provide a flexible alternative to
subclassing for extending functionality.

97
• Facade: Provide a unified interface to a set of interfaces in a
subsystem. A facade defines a higher-level interface that makes
the subsystem easier to use.

• Flyweight: Use sharing to support large numbers of fine-grained


objects efficiently

• Proxy: Provide a surrogate or placeholder for another object to


control access to it.

#3) Behavioral Patterns


The final type of design pattern is the behavioral pattern. It defines
manners of communication between classes and objects.

• Chain Of Responsibility: Avoid coupling the sender of a request


to its receiver by giving more than one object a chance to handle
the request. Chain the receiving objects and pass the request
along the chain until an object handles it.

• Command: Encapsulate a request as an object, thereby letting


you parameterize clients with different requests, queue, or log
requests, and support undoable operations.

• Interpreter: Given a language, define a representation for its


grammar along with an interpreter that uses the representation
to interpret sentences in the language.

• Iterator: Provide a way to access the elements of an aggregate


object sequentially without exposing its underlying
representation.

98
• Mediator: Define an object that encapsulates how a set of
objects interact. Mediator promotes loose coupling by keeping
objects from referring to each other explicitly, and it lets you
vary their interaction independently.

• Memento: Without violating encapsulation, capture and


externalize an object’s internal state so that the object can be
restored to this state later.

• Observer: Define a one-to-many dependency between objects so


that when one object changes state, all its dependents are
notified and updated automatically.

• State: Allow an object to alter its behavior when its internal state
changes. The object will appear to change its class

• Strategy: Define a family of algorithms, encapsulate each one,


and make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.

• Template Method: Define the skeleton of an algorithm in an


operation, deferring some steps to subclasses. Template Method
lets subclasses redefine certain steps of an algorithm without
changing the algorithm’s structure.

• Visitor: Represent an operation to be performed on the elements


of an object structure. Visitor lets you define a new operation
without changing the classes of the elements on which it
operates.

99
CASE support

Computer aided software engineering (CASE) is the implementation of


computer facilitated tools and methods in software development. CASE is used
to ensure a high-quality and defect-free software. CASE ensures a check-pointed
and disciplined approach and helps designers, developers, testers, managers
and others to see the project milestones during development.
CASE can also help as a warehouse for documents related to projects, like
business plans, requirements and design specifications. One of the major
advantages of using CASE is the delivery of the final product, which is more
likely to meet real-world requirements as it ensures that customers remain part
of the process.
CASE illustrates a wide set of labor-saving tools that are used in software
development. It generates a framework for organizing projects and to be helpful
in enhancing productivity. There was more interest in the concept of CASE tools
years ago, but less so today, as the tools have morphed into different functions,
often in reaction to software developer needs. The concept of CASE also received
a heavy dose of criticism after its release.
CASE Tools:
The essential idea of CASE tools is that in-built programs can help to analyze
developing systems in order to enhance quality and provide better outcomes.
Throughout the 1990, CASE tool became part of the software lexicon, and big
companies like IBM were using these kinds of tools to help create software.
Various tools are incorporated in CASE and are called CASE tools, which are used
to support different stages and milestones in a software development life cycle.
Types of CASE Tools:

1. Diagramming Tools:
It helps in diagrammatic and graphical representations of the data and
system processes. It represents system elements, control flow and data
flow among different software components and system structure in a
pictorial form.
For example, Flow Chart Maker tool for making state-of-the-art
flowcharts.

2. Computer Display and Report Generators:


It helps in understanding the data requirements and the relationships
involved.

3. Analysis Tools:
It focuses on inconsistent, incorrect specifications involved in the
diagram and data flow. It helps in collecting requirements,

100
automatically check for any irregularity, imprecision in the diagrams,
data redundancies or erroneous omissions.
For example,
• (i) Accept 360, Accompa, CaseComplete for requirement
analysis.

• (ii) Visible Analyst for total analysis.

4. Central Repository:
It provides the single point of storage for data diagrams, reports and
documents related to project management.

5. Documentation Generators:
It helps in generating user and technical documentation as per
standards. It creates documents for technical users and end users.
For example, Doxygen, DrExplain, Adobe RoboHelp for documentation.

6. Code Generators:
It aids in the auto generation of code, including definitions, with the
help of the designs, documents and diagrams.

Advantages of the CASE approach:

• As special emphasis is placed on redesign as well as testing, the


servicing cost of a product over its expected lifetime is considerably
reduced.

• The overall quality of the product is improved as an organized


approach is undertaken during the process of development.

• Chances to meet real-world requirements are more likely and easier


with a computer-aided software engineering approach.

• CASE indirectly provides an organization with a competitive advantage


by helping ensure the development of high-quality products.

Disadvantages of the CASE approach:


• Cost: Using case tool is a very costly. Mostly firms engaged in software
development on a small scale do not invest in CASE tools because they
think that the benefit of CASE are justifiable only in the development of
large systems.

101
• Learning Curve: In most cases, programmers productivity may fall in
the initial phase of implementation , because user need time to learn
the technology. Many consultants offer training and on-site services
that can be important to accelerate the learning curve and to the
development and use of the CASE tools.
• Tool Mix: It is important to build an appropriate selection tool mix to
urge cost advantage CASE integration and data integration across all
platforms is extremely important.

102

You might also like