Software Engineering - I - CS504 Handouts PDF
Software Engineering - I - CS504 Handouts PDF
Lecture No. 1
Introduction to Software Engineering
1.1 Introduction
Software engineering is an interesting subject. In order to understand this subject we will
need to look at a number of examples and case studies. And we will need to see how we
can develop good software and how it could be improved in different scenarios? Before
we move on to software engineering we need to understand what software actually is.
What is Software?
When we write a program for computer we named it as software. But software is not just
a program; many things other than the program are also included in software.
So the software is not just the code written in Cobol, Java, Fortran or C++. It also
includes the data and all the documentation related to the program.
Why is it important?
Undoubtedly software is playing a vital role in all the field of life these days. We can see
many software applications being operated around us in our daily routine.
Some of the major areas in which software has played an important role are identified as
under.
_____________________________________________________________________ 1
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
calculations and data analysis. The accuracy of these analyses is also very important
in scientific applications. This process has become very easy and accurate by the use
of software. For example software systems are becoming more involved in
bioinformatics and the process of DNA decoding is only possible by the use of
software systems. Similarly many astronomical observations are being recorded and
analyzed by the software systems these days.
Games: We see many computer games these days that interests people of all ages. All
these games are drive through software systems.
Embedded systems: We see many kinds of gadgets being employed in our daily used
things, like small microcontrollers used in our cars, televisions, microwave ovens etc.
All these systems are controlled through the software.
Similarly in many other fields like education, office automation, Internet applications etc,
software is being used. Due to its central importance and massive use in many fields it is
contributing a lot in terms of economic activity started by the software products. Billions
and trillions of dollars are being invested in this field throughout the world every year.
Engineering
Before moving on to software engineering lets first discuss something about engineering
itself. If you survey some of the dictionaries then you will find the following definition of
engineering.
There are many engineering fields like electrical, mechanical and civil engineering. All
these branches of engineering are based on physics. Physics itself is not engineering but
the use of physics in making buildings, electronic devices and machines is engineering.
When we use physics in constructing buildings then it is called civil engineering. When
we use physics in making machines like engines or cars then it is called mechanical
engineering. And when we apply the knowledge of physics in developing electronic
devices then the process is called electrical engineering. The relation of computer science
with software engineering is similar as the relation of physics with the electrical,
mechanical or civil engineering or for that matter the relation of any basic science with
any engineering field. So in this context we can define software engineering as:
”This is the process of utilizing our knowledge of computer science in effective
production of software systems.”
_____________________________________________________________________ 2
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
mechanical or electrical engineering. Lets look at some of the non-software systems like
TV, Car or an Electric Bulb. The car may be malfunctioned due to some problem in
engine while driving. Similarly an electric bulb may be fused while glowing and a TV
could be dysfunctional while working.
So the major thing that distinguishes a software system from other systems is that;
_____________________________________________________________________ 3
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
they are making a new system altogether. In other words they are making changes in their
systems in many different dimensions. But in non-software systems these kind of changes
are not that much frequent. One of the major reasons of increased bugs in software
systems is this high frequency of change. You can well imagine that if a car
manufacturing company manufacture cars in the similar way then how long these cars
will remain useful, how much effort they have to put to design these cars, how much time
they will require to mature the design, and how much time they would be needing to start
production of such cars. If they try to cut-short that time, meaning that if they try to
release cars after every six-months or a year without proper testing and that release has a
fundamental change then that kind of cars will also have lots of bugs and will not be
road-worthy.
Therefore one of the major reasons of complexity in software is due to its basic nature
that the software passes through a constant process of evolution. The name of the game is
change and evolution all the times in all the dimensions. This change has the direct
impact on software in the form of defects. Therefore software engineers also have to
deals with the challenge of managing this process of change and evolution.
Let’s imagine a person who use to live in a village and who have constructed a hut for
him to live. Definitely he should have face some problems in the beginning but was
managed to build a hurt for him. Now if you ask him to construct another hut, he may be
able to construct one more easily and in a better way. This new hut may be better than the
first one and he may construct it in a relatively less time. But if you ask him to construct
concrete and iron houses then he may not be able to handle it. Since he made a hut and he
know how to make a place to live so you may expect from him to build concrete and iron
buildings. If this is the case then you should all agree that the building constructed by that
person will not have a stable structure or he may not even be able to build one.
In early 60s software had suffered from the similar kind of problem to which we call
Software Crisis. Techniques that were used to develop small software were not applicable
for large software systems. This thing resulted in the following consequences.
_____________________________________________________________________ 4
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In most of the cases that software which was tried to be build using those old tools
and techniques were not complete.
Most of the times it was delivered too late.
Most of the projects were over-budgeted.
And in most of the case systems build using these techniques were not reliable –
meaning that they were not be able to do what they were expected to do.
As a result of these problems a conference were held in 1960 in which the term software
crisis was introduced. And the major issue discussed was that the development of
software is in crisis and we have not been able to handle its complexities. And the term of
Software Engineering was also coined in the same conference. People have said that, we
should use engineering principles in developing software in the same way as we use these
principles in developing cars, buildings, electronic devices etc. Software engineering is
the result of software crisis when people realized that it is not possible to construct
complex software using the techniques applicable in 1960s. An important result of this
thing was that people had realized that just coding is not enough.
Before explaining this definition lets first look at another definition of Software
Engineering given by Ian Somerville.
“All aspects of software production’ Software engineering is not just concerned with the
technical processes of software development but also with activities such as software
project management and with the development of tools, methods and theories to support
software production”.
These definitions make it clear that Software Engineering is not just about writing code.
_____________________________________________________________________ 5
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Software Engineering is the set of processes and tools to develop software. Software
Engineering is the combination of all the tools, techniques, and processes that used in
software production. Therefore Software Engineering encompasses all those things that
are used in software production like:
Programming Language
Programming Language Design
Software Design Techniques
Tools
Testing
Maintenance
Development etc.
So all those thing that are related to software are also related to software engineering.
Some of you might have thought that how programming language design could be related
to software engineering. If you look more closely at the software engineering definitions
described above then you will definitely see that software engineering is related to all
those things that are helpful in software development. So is the case with programming
language design. Programming language design is one of the major successes in last fifty
years. The design of Ada language was considered as the considerable effort in software
engineering.
Well-Engineered Software
Let’s talk something about what is well-engineered software. Well-engineered software is
one that has the following characteristics.
It is reliable
It has good user-interface
It has acceptable performance
It is of good quality
It is cost-effective
Every company can build software with unlimited resources but well-engineered software
is one that conforms to all characteristics listed above.
Software has very close relationship with economics. Whenever we talk about
engineering systems we always first analyze whether this is economically feasible or not.
Therefore you have to engineer all the activities of software development while keeping
its economical feasibility intact.
_____________________________________________________________________ 6
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The major challenges for a software engineer is that he has to build software within
limited time and budget in a cost-effective way and with good quality
But most of the times software engineers ends up in conflict among all these goals. It is
also a big challenge for a software engineer to resolve all these conflicts.
These requirements may be conflicting. For example, there may be tension among the
following:
A Software engineer is required to analyze these conflicting entities and tries to strike a
balance.
In some software the efficiency is more important and desirable. For example if we talk
about a cruise missile or a nuclear reactor controller that are droved by the software
systems then performance and reliability is far more important than the cost-effectiveness
and user-friendliness. In these cases if your software does not react within a certain
amount of time then it may result in the disaster like Chernobyl accident.
_____________________________________________________________________ 7
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The law of diminishing act describes the same phenomenon. Similar is the case with
software engineering. Whenever you perform any task like improving the efficiency of
the system, try to improve its quality or user friendliness then all these things involve an
element of cost. If the quality of your system is not acceptable then with the investment
of little money it could be improved to a higher degree. But after reaching at a certain
level of quality the return on investment on the system’s quality will become reduced.
Meaning that the return on investment on quality of software will be less than the effort
or money we invest. Therefore, in most of the cases, after reaching at a reasonable level
of quality we do not try to improve the quality of software any further. This phenomenon
is shown in the figure below.
cost
benefit
Software Background
Caper Jones a renounced practitioner and researcher in the filed of Software Engineering,
had made immense research in software team productivity, software quality, software
cost factors and other fields relate to software engineering. He made a company named
Software Productivity Research in which they analyzed many projects and published the
results in the form of books. Let’s look at the summary of these results.
He divided software related activities into about twenty-five different categories listed in
the table below. They have analyzed around 10000 software projects to come up with
_____________________________________________________________________ 8
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
such a categorization. But here to cut down the discussion we will only describe nine of
them that are listed below.
Project Management
Requirement Engineering
Design
Coding
Testing
Software Quality Assurance
Software Configuration Management
Software Integration and
Rest of the activities
One thing to note here is that you cannot say that anyone of these activities is dominant
among others in terms of effort putted into it. Here the point that we want to emphasize is
that, though coding is very important but it is not more than 13-14% of the whole effort
of software development.
Fred Brook is a renowned software engineer; he wrote a great book related to software
engineering named “A Mythical Man Month”. He combined all his articles in this book.
Here we will discuss one of his articles named “No Silver Bullet” which he included in
the book.
So, according to Fred Brook, in the eye of an unsophisticated manager software is like a
giant. Sometimes it reveals as an unscheduled delay and sometimes it shows up in the
form of cost overrun. To kill this giant the managers look for magical solutions. But
_____________________________________________________________________ 9
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
unfortunately magic is not a reality. We do not have any magic to defeat this giant. There
is only one solution and that is to follow a disciplined approach to build software. We can
defeat the giant named software by using disciplined and engineered approach towards
software development.
1.6 Summary
Today we have discussed the following things related to software engineering.
What is software engineering?
Why is it important?
What is software crisis?
How software engineering derived from software crisis.
What is the importance of engineering principles in developing software?
What is balancing act and how apply in software engineering?
What is law of diminishing returns?
And what are the major activities involved in the development of software.
_____________________________________________________________________ 10
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 02
We have seen in our previous discussion that software engineering is nothing but a
disciplined approach to develop software. Now we will look at some of the activities
involved in the course of software development. The activities involved in software
development can broadly be divided into two major categories first is construction and
second is management. The construction activities are those that are directly related to the
construction or development of the software. While the management activities are those
that complement the process of construction in order to perform construction activities
smoothly and effectively. A greater detail of the activities involved in the construction
and management categories is presented below.
Construction
The construction activities are those that directly related to the development of software,
e.g. gathering the requirements of the software, develop design, implement and test the
software etc. Some of the major construction activities are listed below.
Requirement Gathering
Design Development
Coding
Testing
Management
Management activities are kind of umbrella activities that are used to smoothly and
successfully perform the construction activities e.g. project planning, software quality
assurance etc. Some of the major management activities are listed below.
Project Planning and Management
Configuration Management
Software Quality Assurance
Installation and Training
As we have said earlier that management activities are kind of umbrella activities that
surround the construction activities so that the construction process may proceed
smoothly. This fact is empathized in the figure 1. The figure shows that construction is
surrounded by management activities. That is, all construction activities are governed by
certain processes and rules. These processes and rules are related to the management of
the construction activities and not the construction itself.
_____________________________________________________________________ 11
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
• Requirements
• Design
• Coding
• Testing
• Maintenance
etc.
Quality Focus: As we have said earlier, the given framework is based on the
organizational commitment to quality. The quality focus demands that processes be
defined for rational and timely development of software. And quality should be
emphasized while executing these processes.
Processes: The processes are set of key process areas (KPAs) for effectively manage and
deliver quality software in a cost effective manner. The processes define the tasks to be
performed and the order in which they are to be performed. Every task has some
deliverables and every deliverable should be delivered at a particular milestone.
Methods: Methods provide the technical “how-to’s” to carryout these tasks. There could
be more than one technique to perform a task and different techniques could be used in
different situations.
_____________________________________________________________________ 12
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Method T
O
Task Set Process O
L
Quality Focus S
Problem Definition: In this stage we determine what is the problem against which we are
going to develop software. Here we try to completely comprehend the issues and
requirements of the software system to build.
Technical Development: In this stage we try to find the solution of the problem on
technical grounds and base our actual implementation on it. This is the stage where a new
system is actually developed that solves the problem defined in the first stage.
Solution Integration: If there are already developed system(s) available with which our
new system has to interact then those systems should also be the part of our new system.
All those existing system(s) integrate with our new system at this stage.
Status Quo: After going through the previous three stages successfully, when we actually
deployed the new system at the user site then that situation is called status quo. But once
we get new requirements then we need to change the status quo.
After getting new requirements we perform all the steps in the software development
loop again. The software developed through this process has the property that this could
be evolved and integrated easily with the existing systems.
_____________________________________________________________________ 13
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Problem
Definition
Technical
Status Quo
Development
Solution
Integration
Software Construction
Here once again look at the construction activities of the software from a different
perspective. This section provides with a sequence of questions that have to answer in
different stages of software development.
Vision: Here we determine why are we doing this thing and what are our business
objectives that we want to achieve.
Definition: Here we actually realize or automate the vision developed in first phase. Here
we determine what are the activities and things involved.
Development: Here we determine, what should be the design of the system, how will it
be implemented and how to test it.
_____________________________________________________________________ 14
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Maintenance
Correction, adaptation, enhancement
For most large, long lifetime software systems, maintenance cost normally exceeds
development cost by factors ranging from 2 to 3.
Boehm (1975) quotes a pathological case where the development cost of an avionics
system was $30 per line of code but the maintenance cost was $4000 per instruction
2.5 Summary
Software development is a multi-activity process. It is not simply coding.
Software construction and management
Software Engineering Framework
Software development loop
Software engineering phases
Importance of Maintenance
_____________________________________________________________________ 15
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 03
Requirement Engineering
3.1 Requirement Engineering
We recall from our previous discussion that software development is not simply coding –
it is a multi-activity process. The process of software construction encompasses and
includes answers to the following questions:
These questions force us to look at the software development process from different
angles and require different tools and techniques to be adopted at different stages and
phases of the software development life cycle. Hence we can divide the whole process in
4 distinct phases namely vision, definition, development, and maintenance. Each one of
these stages has a different focus of activity. During the vision phases, the focus is on
why do we want to have this system; during definition phase the focus shifts from why to
what needs to be built to fulfill the previously outlined vision; during development the
definition is realized into design and implementation of the system; and finally during
maintenance all the changes and enhancements to keep the system up and running and
adapt to the new environment and needs are carried out.
Requirement engineering mainly deals with the definition phase of the system.
Requirement engineering is the name of the process when the system services and
constraints are established. It is the starting point of the development process with the
focus of activity on what and not how.
Jones defines software requirements as a statement of needs by a user that triggers the
development of a program or system.
_____________________________________________________________________ 16
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Alan Davis defines software requirements as a user need or necessary feature, function,
or attribute of a system that can be sensed from a position external to that system.
As can be seen, these definitions slightly differ from one another but essentially say the
same thing: a software requirement is a document that describes all the services provided
by the system along with the constraints under which it must operate.
Fred Brooks in his classical book on software engineering and project management “The
Mythical Man Month” emphasizes the importance of requirement engineering and writes:
“The hardest single part of building a software system is deciding precisely what to
build. No other part of the conceptual work is as difficult as establishing the
detailed technical requirements, including all the interfaces to people, to
machines, and to other software systems. No other part of the work so cripples the
system if done wrong. No other part is more difficult to rectify later.”
Let us try to understand this with the help of an analogy of a house. If we are at an
advanced stage of building a house, adding a new room or changing the dimensions of
some of the rooms is going to be very difficult and costly. On the other hand if this need
is identified when the maps are being drawn, one can fix it at the cost of redrawing the
map only. In the case of a software development, we experience the exact same
phenomenon - if a problem is identified and fixed at a later stage in the software
development process, it will cost much more than if it was fixed at and earlier stage.
_____________________________________________________________________ 17
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This following graph shows the relative cost of fixing problem at the various stages of
software development.
Boehm (1981) has reported that correcting an error after development costs 68 times
more. Other studies suggest that it can be as high as 200 times. Since cost is directly
related with the success or failure of projects, it is clear from all this discussion that
having sound requirements is the most critical success factor for any project.
Once these requirements have been finalized, the construction process starts. During this
phase the software engineer starts designing and coding the software. Once again, the
requirement document serves as the base reference document for these activities. It can
be clearly seen that other activities such as user documentation and testing of the system
would also need this document for their own deliverables.
On the other hand, the project manager would need this document to monitor and track
the progress of the project and if needed, change the project scope by modifying this
document through the change control process.
_____________________________________________________________________ 18
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The following diagram depicts this central role of the software requirement document in
the entire development process.
Lecture #4
3.4 Some Risks from Inadequate Requirement Process
From the above discussion, it should be clear that the requirements play the most
significant role in the software development process and the success and failure of a
system depends to a large extent upon the quality of the requirement documents.
Following is a list of some of the risks of adopting an inadequate requirement process:
It basically means identifying and adding new requirements to the list at some
advanced stages of the software development process. The following figure shows the
_____________________________________________________________________ 19
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
requirement differently. Ambiguity arises from the use of natural language. Because
of the imprecise nature of the language, different readers interpret the statements
differently. As an example, consider the following Urdu Phrase: “Rooko mut jane
doo”. Now, depending upon where a reader places the comma in this statement, two
after “Rooko”, the sentence will become “Rooko, mut jane doo”, meaning “don’t let
him go”. On the other hand if the comma id placed after “mut”, the sentence will
become “Rooko mut, jane doo”, meaning “let him go”. Ambiguous requirements
_____________________________________________________________________ 20
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The operator identity consists of the operator name and password; the password
consists of six digits. It should be displayed on the security VDU and deposited in the
login file when an operator logs into the system.
in the second sentence and what should be displayed on the VDU. Does it refer to the
and in fact are not important for the end-user but the developer adds them anyway
thinking that they would add value to the product. Since these features are outside the
initial scope of the product, adding them will result in schedule and budget overruns.
As an example, let us look at the following requirement. The requirement was stated
as: “We need a flow control and source control engineering tool.” Based upon this
requirement, system was built. It worked perfectly and had all the functionality
needed for source control engineering tool and one could draw all kinds of maps and
drawings. The system however could not be used because there was there was no
print functionality.
Let us now look at the following set of requirement statements for another system:
The system should maintain the hourly level of reservoir from depth sensor
situated in the reservoir. The values should be stored for the past six months.
AVERAGE: Average command displays the average water level for a particular
sensor between two times.
_____________________________________________________________________ 21
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This is another case of minimal requirements – it does not state how the system
should respond if we try to calculate the average water level beyond the past six
months.
1. Business Requirements:
These are used to state the high-level business objective of the organization or
customer requesting the system or product. They are used to document main system
features and functionalities without going into their nitty-gritty details. They are
captured in a document describing the project vision and scope.
2. User Requirements:
User requirements add further detail to the business requirements. They are called
user requirements because they are written from a user’s perspective and the focus of
user requirement describe tasks the user must be able to accomplish in order to fulfill
the above stated business requirements. They are captured in the requirement
definition document.
3. Functional Requirements:
The next level of detail comes in the form of what is called functional requirements.
They bring-in the system’s view and define from the system’s perspective the
software functionality the developers must build into the product to enable users to
accomplish their tasks stated in the user requirements - thereby satisfying the business
requirements.
4. Non-Functional Requirements
In the last section we defined a software requirement as a document that describes all
the services provided by the system along with the constraints under which it must
operate. That is, the requirement document should not only describe the functionality
needed and provided by the system, but it must also specify the constraints under
which it must operate. Constraints are restrictions that are placed on the choices
available to the developer for design and construction of the software product. These
_____________________________________________________________________ 22
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
While writing these requirements, it must always be kept in mind that all functional
requirements must derive from user requirements, which must themselves be aligned with
business requirements. It must also be remembered that during the requirement
engineering process we are in the definition phase of the software development where the
focus is on what and not how. Therefore, requirements must not include design or
implementation details and the focus should always remain on what to build and not how
to build.
Let us now look at an example to understand the difference between these different types
of requirements.
Let us assume that we have a word-processing system that does not have a spell checker.
In order to be able to sell the product, it is determined that it must have a spell checker.
Hence the business requirement could be stated as: user will be able to correct spelling
errors in a document efficiently. Hence, the Spell checker will be included as a feature in the
product.
In the next step we need to describe what tasks must be included to accomplish the
above-mentioned business requirement. The resulting user requirement could be as
follows: finding spelling errors in the document and decide whether to replace each
misspelled word with the one chosen from a list of suggested words. It is important to
note that this requirement is written from a user’s perspective.
After documenting the user’s perspective in the form of user requirements, the system’s
perspective: what is the functionality provided by the system and how will it help the user
to accomplish these tasks. Viewed from this angle, the functional requirement for the
same user requirement could be written as follows: the spell checker will find and highlight
misspelled words. It will then display a dialog box with suggested replacements. The user will be allowed
to select from the list of suggested replacements. Upon selection it will replace the misspelled word with
the selected word. It will also allow the user to make global replacements.
_____________________________________________________________________ 23
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Finally, a non-functional requirement of the system could require that it must be integrated into the
existing word-processor that runs on windows platform.
Stakeholders
As mentioned earlier, in order to develop a good requirement document, it is imperative
to involve all kinds of user in the requirement engineering process. The first step in
fulfillment of this need is the identification of all the stakeholders in the system.
Stakeholders are different people who would be interested in the software. It is important
to recognize that management carries a lot of weight, but they usually are not the actual
users of the system. We need to understand that it is the actual user who will eventually
use the system and hence accept or reject the product. Therefore, ignoring the needs of
any user class may result in the system failure.
A requirement engineer should be cognizant of the fact that stakeholders have a tendency
to state requirements in very general and vague terms. Some times they trivialize things.
Different stakeholders have different requirements – sometimes even conflicting. On top
of that internal politics may influence requirements.
The following diagram shows the role of different stakeholders in the setting the system
requirements.
_____________________________________________________________________ 24
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________ 25
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Necessary -Each requirement should document something that the customer really
need or something that is required for conformance to an external system requirement
or standard.
Verifiable – User should be able to devise a small number of tests or use other
verification approaches, such as inspection or demonstration, to determine whether
the requirement was properly implemented.
Let us try to understand this with the help of some examples. The following set of
These requirements conflicted with one another because the code generated by the
Ada compiler was of a large footprint that could not fit into the micro-controller
memory.
Following is another set of (functional) requirements that conflicted with one another:
_____________________________________________________________________ 26
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
System should only monitor and log temperatures below -200 C and above 4000 C.
In this case the two requirements clearly conflict with each other in stating what
Traceable - One should be able to link each requirement to its origin and to the
design elements, source code, and test cases that implement and verify the correct
implementation of the requirement.
Lecture No. 5
Relationship of Several components of Software
Requirements
The following figure depicts the relationship between different documents produced
during the requirement engineering phase.
_____________________________________________________________________ 27
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Business Requirements
Business requirements collected from multiple sources might conflict. For example,
consider a kiosk product with embedded software that will be sold to retail stores and
used by the store’s customers. The kiosk developer’s business objectives include the
following:
The developer might want to establish a high-tech and exciting new direction for
customers, while the retailer wants a simple solution and the customer wants convenience
and features. The tension among these three parties with their different goals, constraints,
_____________________________________________________________________ 28
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
and cost factors can lead to conflicting business requirements, which must be resolved
before the kiosk’s software requirements are detailed.
You can also use the business requirements to set implementation priorities for use cases
and their associated functional requirements. For example, a business requirement to
generate maximum revenue from the kiosk would imply the early implementation of
features directly associated with selling more products or services to the customer, rather
than glitzy features that appeal to only a subset of customers.
_____________________________________________________________________ 29
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The vision statement should reflect a balanced view that will satisfy the need of diverse
customers. It can be somewhat idealistic but should be grounded in the realities of
existing or anticipated customer markets, enterprise architectures, organizational strategic
directions, and resource limitations.
The chemical tracking system will allow scientists to request containers of chemicals to
be supplied by chemical stockroom or by vendors. The location of every chemical
container within the company, the quantity of the material remaining in it, and the
complete history of each container’s location and usage will be known by the system at
all times. The company will save 25% on chemical costs by fully exploiting chemicals
already available within the company, by disposing of fewer partially used or expired
containers, and by using a standard chemical purchasing process. The chemical tracking
system will also generate all reports required to comply with federal and state
government regulations that require the reporting of chemical usage, storage, and
disposal.
Scope
Project scope defines the concept and range of the proposed solution, and limitations
identify certain capabilities that the product will not include. Clarifying the scope and
limitations helps to establish realistic stakeholder’s expectations. Sometimes customers
request features that are too expansive or do not lie within the intended project scope.
Propose requirements that are out of scope must be rejected, unless they are so beneficial
that the scope should be enlarged to accommodate them (with accompanying changes in
budget, schedule, and staff). Keep a record of these requirements and why they were
rejected, as they have a way of reappearing.
The major features that will be included in the initial release of the project should be
summarized. Describe the quality characteristics that will enable the product to provide
the intended benefits to its various customer communities.
Requirements need to be prioritized and a release schedule should be made.
_____________________________________________________________________ 30
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________ 31
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
It has been mentioned earlier on, excellent software products are the result of a well-
executed design based on excellent requirements and high quality requirements result
from effective communication and coordination between developers and customers. That
is, good customer-developer relationship and effective communication between these two
entities is a must for a successful software project. In order to build this relationship and
capture the requirements properly, it is essential for the requirement engineer to learn
about the business that is to be automated.
One tool used to organize and structure the requirements is such a fashion is called use
case modeling.
A use case model has two components, use cases and actors.
In a use case model, boundaries of the system are defined by functionality that is handled
by the system. Each use case specifies a complete functionality from its initiation by an
actor until it has performed the requested functionality. An actor is an entity that has an
interest in interacting with the system. An actor can be a human or some other device or
system.
A use case model represents a use case view of the system – how the system is going to
be used. In this case system is treated as a black box and it only depicts the external
interface of the system. From an end-user’s perspective it and describes the functional
requirements of the system. To a developer, it gives a clear and consistent description of
what the system should do. This model is used and elaborated throughout the
_____________________________________________________________________ 32
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
development process. As an aid to the tester, it provides a basis for performing system
tests to verify the system. It also provides the ability to trace functional requirements into
actual classes and operations in the system and hence helps in identifying any gaps.
Lecture No. 6
Use Diagram for a Library System
As an example, consider the following use case diagram for a library management
system. In this diagram, there are four actors namely Book Borrower, Librarian, Browser,
and Journal Borrower. In addition to these actors, there are 8 use cases. These use cases
are represented by ovals and are enclosed within the system boundary, which is
represented by a rectangle. It is important to note that every use case must always deliver
some value to the actor.
With the help of this diagram, it can be clearly seen that a Book Borrower can reserve a
book, borrow a book, return a book, or extend loan of a book. Similarly, functions
performed by other users can also be examined easily.
_____________________________________________________________________ 33
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
concurrent and a use case model will evolve slowly from these activities. This activity
stops when no new use cases or actors are discovered. At the end, the model is validated.
Let is try to understand these two concepts with the help of the following diagrams. In the
case of the first diagram, the Delete Information use case is using two already existing
use cases namely Record Transaction and Cancel Transaction. The direction of the arrow
determines which one is the user and which use case is being used.
_____________________________________________________________________ 34
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The second diagram demonstrates the concept of reuse by extending already existing use
cases. In this case Place Conference Call use case is a specialization of Place Phone Call
use case. Similarly, Receive Additional Call is defined by extending Receive Phone Call.
It may be noted here that, in this case, the arrow goes from the new use case that is being
created (derived use case) towards the use case that is being extended (the base use case).
This diagram also demonstrates that many different actors can use one use case.
Additionally, the actors defined for the base use case are also defined by default for the
derived use case.
The concept of reusability can also be used in the case of actors. In this case, new classes
of actors may be created by inheriting from the old classes of actors.
Credit Card
Validation System
Perform Card
Transaction
Reconcile
Transactions
Individual Corporate
Manage
Customer Customer Sponsoring
Customer Acct
Financial
Institution
Extended User
In this case two new classes, Individual Customer and Corporate Customer, are being
created by extending Customer. In this case, all the use cases available to Customer
would also be available to these two new actors.
_____________________________________________________________________ 35
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
After the derivation of the use case model, each use is elaborated by adding detail of
interaction between the user and the software system. An elaborated use case has the
following components:
s >> Record
use Transaction
<<
Delete
Information
<<
use
User s >> Cancel
Transaction
Priority: 3
Actors: User
Summary: Deleting information allows the user to permanently remove information from
the system. Deleting information is only possible when the information has not been used
in the system.
Preconditions: Information was previously saved to the system and a user needs to
permanently delete the information.
_____________________________________________________________________ 36
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Extends: None
Exceptions:
1. The system will not allow a user to delete information that is being used in the
system.
2. The system will not allow a user to delete another user that has subordinates.
Assumptions:
1. Deleting information covers a permanent deletion of an entire set of data such as a
commission plan, user, group etc. Deleting a portion of an entire set constitutes
modifying the set of data.
2. Deleted information is not retained in the system.
3. A user can only delete information that has not been used in the system.
3.11 Alternative Ways of Documenting the Use Case
Many people and organizations prefer to document the steps of interaction between the
use and the system in two separate columns as shown below.
_____________________________________________________________________ 37
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
2. The user selects the set of 3. The system responds by asking the user
information that he/she would like to to confirm deleting the information.
delete and directs the system to
delete the information. - Exception 1,
2
4. The user confirms deletion. 5. A system responds by deleting the
information and notifying the user
that the information was deleted
from the system.
Delete Information
Initiate Deletion
[Delete Allowed]
[Cancel Delete]
[Confirm Delete]
_____________________________________________________________________ 38
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Use cases alone are not sufficient. There are kinds of requirements (mostly non-
functional) that need to be understood. Since use cases provide a user’s perspective, they
describe the system as a black box and hide the internal details from the users. Hence, in
a use case, domain (business) rules as well as legal issues are not documented.
The non-functional requirements are also not documented in the use cases. As examples
of those, consider the following requirements.
Usability
o Color blind people should not have any difficulty in using the system – color
coding should take care of common forms of color blindness.
Reliability
o The system needs to support 7 x 24 operation
Performance
o Authorization should be completed within 1 minute 90% of the time.
o Average authorization confirmation time should not exceed 30 seconds.
Portability
o The system should run on Windows 98 and above as well as Sun Solaris 7.0
and above.
Access
o System should be accessible over the internet – hidden requirement – security
Lecture No. 7
3.14 Source and sink analysis
Once requirements are documented using any of these analysis models, an independent
verification is needed to verify completeness and consistency of requirements captured
through these models. The process of verifying requirements involves careful analysis of
sources as well as the sinks of information.
Source
A stakeholder describes requirements (needs, constraints) to be included as system
functionality. These can be processes that generate certain information that the system
may have to process or maintain. Sources of requirements are the origins from where the
corresponding business process is initiated. By this concept, one has to trace from a
requirement back to its origins to see who is involved in its initiation. Be it a person, an
organization or an external entity that initiate some action and system responds back by
completing that action.
Sink
_____________________________________________________________________ 39
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Sink is the consumer of certain information. It is that entity which provides a logical end
to a business process. Thus, ‘sinks of requirements’ is a concept that helps in identifying
persons, organizations or external systems that gets certain functionality from the system.
These are logical ends of requirements, or where all the requirements are consumed. For
example, we may consider a user of a software application that retrieves a report from the
system. In this case, user when reviews the report, becomes the sink of that report. Thus
when analyzing the sink of the requirement of implementing a report, the analyst would
naturally point towards the user who would get that report.
In source and sink analysis the analyst determines all the sources of requirements and
where do these requirements consume (sinks). Now evaluate a report which displays
certain information, the source of this report is the data (and who enters it) that is input to
be retrieved later in the form of the report. Similarly, whoever needs this report become
the sink of the report.
In a similar manner, at times we gather data in our application that is not used anywhere.
So the question really is what to do with that kind of unused data or the missing
requirement. Is it really redundant or is something really missing from these
requirements? How to figure it out?
For example, we are having certain inputs (sources) to a process against which we do not
know about the corresponding outputs (sinks). Such inputs are redundant if there is found
no corresponding outputs. Thus these inputs can be removed as redundant. If we probe
out corresponding outputs, which could not be recorded initially, that mean these inputs
were not redundant rather a few (output related) requirements were missing that we
discovered during the sink analysis.
A stakeholder may have required the development team to develop certain report for his
use. It means we are sure of its use (sink) but not about its sources, from where the
required information will be provided? Who will input that information and using what
mechanism?
A requirement statement that describe the report but do not list down its sources, will be
an incomplete statement and the software engineer who is involved in validating such
requirements, should identify all the sources against sinks or vice versa to determine
complete end-to-end requirements.
_____________________________________________________________________ 40
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Process Models
Domain Models
During requirements analysis phase, different models are developed to express
requirements of the system. Though it is difficult to draw a line between these models as
they complement each other, they differ in the manner information is expressed in these
models. Most of these models are pictorial and contain explanation to the diagrams.
Some of these models are discussed in the following subsections.
Understanding the business domain
It must always be kept in mind that the first step in delivering a system is establishing
what needs to be driven. That is, clear understanding of the problem domain is imperative
in successful delivery of a software solution. A software developer has to develop an
understanding of the business problem he is trying to solve. Unless he develops this
understanding, it is really difficult, if not impossible, to develop the right solution. But at
least if he collects both ends (sources, sinks) involved in different processes of the
business system, the corresponding requirements will be complete and yield a better
understanding of the problem domain. A software engineer works on domains that may
not correspond to his field of specialization (computer science, software engineering). He
may be involved in the development of an embedded application that automates the
control pad of a microwave machine or a decision support application for a stock
exchange broker. As the underlying systems for which these software applications are
being developed are not software systems, the software engineer cannot be expected to
know about these domains. So, how should he get all the required knowledge about these
systems? As without acquiring this knowledge, he may not be able to write down
complete and unambiguous requirements which are acceptable to users as well.
An important difference between software and another engineering discipline is that the
software engineer has to work on problems that do not directly relate to software
engineering. Whereas, an electrical engineer will work on electrical domain problems, a
civil engineer will work on civil engineering problems and so on. So, software engineer
has to learn user vocabulary and terms which they use in their routine operations. To
overcome this problem, a number of domain gathering techniques are used. These
techniques help in extracting requirements from systems which are not known to a
software engineer. Using these techniques the requirements gathering and validation
process becomes convenient and manageable for a software engineer.
System models are techniques used to understand user needs and software engineer use
these techniques in order to understand business domain. Software engineers develop
diagrams to model different business processes. System models include the following
User business processes
User activities for conducting the business processes
Processes that need to be automated
Processes which are not to be automated
Business process model
The first model that we will look at is called the process model. This model provides a
high-level pictorial view of the business process. This model can be used as a
starting point in giving the basic orientation to the reader of the document.
Following is an example of a hospital registration system which deals with two types
of patients.
As opposed to flow charts, there are parallel activities in this diagram which are further
elaborated by specifying their major activities. The process described in this diagram is as
follows
A patient may come to visit In Patient Department (IPD) or output patient
department (OPD)
System determines if he is a company patient or a private patient.
For a company patient, system verifies him.
For an OPD patient, system will issue a chit to the patient and inform him about
his number and the consultant to whom he has to consult and he will have to wait
for his turn.
After verifying an IPD patient, system will create a visit and allocate him a room
or a bed etc. If system cannot allocate this, then it will inform the patient.
Otherwise the patient is checked in and his information is maintained in the
system.
_____________________________________________________________________ 42
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
System displays information about the expenses of the required service to the
patient so that he is informed of his expected expenditure.
Some advance payment is also received against the required service and this
amount is adjusted in the final settlement.
All this information is supplied to cash office that eventually deals with payments,
etc.
Upon receiving the cash, for OPD patient, a chit will be issued. For IPD patient,
an admission form will be filled and this information will be maintained in the
system. A receipt will be issued to the patient.
For credit transaction, corresponding voucher will be prepared.
So the model depicts process before the start of the treatment.
A patient may ask to change his service on event of an unsatisfied response from
the hospital staff or any other reason. System may cancel his record and pay his
amount back.
Similarly, a doctor may ask a patient to change his status from OPD to IPD.
In a business process diagram, following points are important and should be noted
It does not describe the automated system
It only reflects the existing process of the user to help software engineer/analyst in
understanding business domain.
It may contain information on processes that need not be automated.
_____________________________________________________________________ 43
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No.8
State Transition Diagrams
State transition diagrams (STDs) are another technique to document domain knowledge.
In many cases, information flows from one place to the other and at each place certain
action is taken on that piece of information before it moves to the next place. A file in an
office is a typical office is example of such system. In this case, different people make
comments and add information to that file and it moves from one table to the other this
movement is controlled by a pre-defined set of rules which define under what condition
the file moves from place A to place B and so on. We can easily document these set of
rules with the help of state transition diagrams.
Following is an example of a use of STD to document the life cycle of a trouble ticket
(this example has been taken from ITU-X.790 document).
At the time of a trouble, a network may have been inter-working with another network to
provide a service, and the problem or malfunction may be due to the other network.
Therefore it may be necessary to exchange trouble management information between
management systems across interfaces which may be client to service provider or service
provider to service provider interfaces and may represent inter-jurisdictional as well as
intra-jurisdictional boundaries. In addition to exchanging information on trouble that has
already been detected, advance information on service inaccessibility may also need to be
exchanged. Thus, a service provider may need to inform a customer of future service
inaccessibility (because of planned maintenance, for example).
_____________________________________________________________________ 44
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Queued
A trouble report is in a queued state when it has been instantiated but the trouble
resolution process has not yet been initiated. A trouble report which is in the queued state
may be cancelled by the manager. The agent on receiving such a request will attempt to
close the trouble report.
Open/active
The trouble report becomes “open/active” when appropriate actions to resolve the trouble
are initiated.
An “open/active” trouble report may be “referred” to another Hand-off Person, or
“transferred” to another Responsible Person for further processing. The state however
remains unchanged as “open/active”. A trouble report in the open/active state may be
cancelled by the manager. The agent on receiving such a request will attempt to close the
trouble report.
Deferred
This state indicates that corrective action to resolve the trouble has been postponed. This
can occur when the faulty resource is inaccessible for a period and repair activity cannot
proceed. A deferred Telecommunications Trouble Report may become “open/active”
again, or move directly to the “closed” state if it is cancelled for some reason. A trouble
report in the deferred state may be cancelled by the manager. The agent on receiving such
a request will attempt to close the trouble report.
Cleared
A trouble report is moved by the agent to the “cleared” state when it determines that the
trouble has been resolved. If the manager needs to verify that the trouble has been
resolved, verification may optionally be awaited by the agent prior to closure of the
trouble report.
Closed
This state indicates that the trouble resolution process is complete. Upon closure, the
trouble report attributes are captured in a historical event generated at trouble report
closure which may then be stored in a log of trouble history records, for future reference.
The trouble report may then be eliminated at the agent’s convenience. However, the
agent may be required to maintain such records for a period of time as per business
agreements.
Disabled
A “disabled” value is exhibited when a trouble report’s information cannot be updated
due to local conditions. In the “disabled” condition only read operations can be
performed.
The following figure shows the STD for a trouble ticket. This diagram depicts the
movement of a trouble ticket from one state to the other, thus making it easy to
understand.
_____________________________________________________________________ 45
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Cancel
Open/Active
Release Re-open
Defer Clear
Cancel Close
Closed
Delete
(Explicit or Scheduled)
_____________________________________________________________________ 46
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
It is difficult to understand these definitions and one has to read them a number of times
to understand what is the difference between EI, EO, and EQ and in which case a
function would be classified as EI, EO, or EQ.
This table simply says that a function can alter the behaviour of the system, it can
maintain one or more ILFs, and/or it can present information to the user. The next step is
to determine whether it is EI, EO, or EQ. For that we have to determine what is the
primary intent (PI) of the function and in addition to this primary intent, what else does it
_____________________________________________________________________ 47
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
do. Identification of EQ is simple - in this case the only thing a function does is present
information to the user, which is also it’s primary intent. If it alters the behaviour of the
system or maintains and ILF then it can either be an EI or and EO but not an EQ. On the
other hand if the primary intent of the function is to present information to the user but at
the same time it also performs any of the first two operations, it is an EO. Finally, if the
primary intent of the function is either to alter the behaviour of the system of maintain
one or more ILFs, then it is an EI.
Hence by putting and organizing the information in the form of a table, we have not only
made it simple to understand the definition but also given an holistic picture which was
not easily visible otherwise.
Let us look at another example. This time the information is taken from the Income Tax
Ordinance of Pakistan 2001. Consider the following statement that describes the income
tax rates applicable to people with different brackets:
If the taxable income is less than Rs. 60,000, there will be no income tax. If the income
exceeds Rs. 60,000 but is less than Rs. 150,000 then income tax will be charged at the
rate of 7.5% for income exceeding Rs. 60,000. If the income exceeds Rs. 150,000 but
does not exceed Rs. 300,000 then the income tax will be computed at 12.5% of the
amount exceeding Rs. 150,000 plus Rs. 6,750. If the income exceeds Rs. 300,000 but
does not exceed Rs. 400,000 then the income tax will be computed at 20% of the amount
exceeding Rs. 300,000 plus Rs. 25,500. If the income exceeds Rs. 400,000 by does not
exceed Rs. 700,000 then the income tax will be computed at 25% of the amount
exceeding Rs. 400,000 plus Rs. 45,500. If the income exceeds Rs. 700,000 then the
income tax will be computed at 35% of the amount exceeding Rs. 700,000 plus Rs.
120,500.
The same information can be organized in the form of a table, making it more readable
and easier to use.
Income Tax
Less than Rs. 60,000 0%
Between Rs. 60,000 and Rs. 7.5% of (Income - 60,000)
150,000
Between Rs. 150,000 and Rs. 12.5% of (Income - 150,000) +
300,000 6,750
Between Rs. 300,000 and Rs. 20% of (Income - 300,000) +
400,000 25,500
Between Rs. 400,000 and Rs. 25% of (Income - 400,000) +
700,000 45,500
Greater than Rs. 700,000 35% of (Income - 700,000) +
120,500
Once the information has been organized in the tabular form, in many cases it can be
simply stored and mapped onto an array or a database table and the programming of this
_____________________________________________________________________ 48
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
kind of a rule is simply reduced to a table or dictionary lookup. This reduces the
complexity of the domain and hence reduces the over all effort for designing, coding,
testing, and maintaining the system.
Process
External Agent
External systems which are outside the boundary of this system. These are represented
using the squares
External
Agent
Data Store
Where data is being stored for later retrieval.
Provides input to the process
Outputs of the processes may be going into these data stores.
_____________________________________________________________________ 49
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Data Store
Data Flow
Where the data is flowing.
Represents the movement of the data in a data flow diagram.
_____________________________________________________________________ 50
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Other
Reconcile Deposit income
Account funds into an
Monthly Acct Sources
Balance Account
stmt
Bank
Accounts
Account Employer
Transactions
Withdraw Pay
funds from an a
Account Bill
Bank
Creditor
Processes
1. Reconcile account balance
2. Deposit funds into an account
3. Pay a bill
4. Withdraw funds from an account
External agents
1. Bank
2. Creditor
3. Employer
4. Other income sources
Data stores
1. Monthly Account statement
2. Bank accounts
3. Account transactions
Description:
First we shall discuss ‘withdraw funds from an account’ process. In this process,
information about the accounts and account transactions is retrieved (from the data
stores) and bank releases the funds. After this, it sends this information to ‘reconcile
account balance’ process which prepares a monthly account statement. In this statement,
information regarding bank accounts and account transactions are described. Next is the
‘pay a bill’ process through which a creditor pays his dues and the corresponding
accounts are updated against the cash transaction. A receipt is issued back to the creditor.
The fourth process is ‘deposits funds in an account’ in which an employer deposits
salaries of his employees and the salary information is deposited in the corresponding
_____________________________________________________________________ 51
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
bank accounts of the employees. Similarly, income received through other income
sources is also received and deposited in the corresponding bank accounts.
_____________________________________________________________________ 52
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 9
analyst to know each bit of all the processes of the system from the very beginning.
Keeping the complexity of systems in view, data flow modeling technique has suggested
disseminating information of a system in more then just one levels of abstraction. What
are these levels, please see below for a discussion
Context Level Data Flow Diagram
In a top-down system analysis, an analyst is required to develop high level view of the
system at first. In data flow modeling, this high-level view is the Context level data flow
diagram. In this diagram, system’s context is clarified such that all the external agents or
entities with which the system interacts are captured. It captures the details of what
information flows between the system and these external entities, and what outputs are
generated against inputs from these external agents and so on. So, the analyst probes out
all the external agents that may involve persons, organizations or other systems who
directly interacts with this system and their specific involvement in the system. At this
level, systems internal details are not exposed, as we want to see system behavior as a
black box.
Detailed Data Flow diagrams
Once context of a system has been captured using context level diagram, the analyst
would expand his activities and start digging out system’s internal details. Therefore, the
same context level diagram is further expanded to include all major processes of the
system that make up system functionality. So, instead of portraying system as a black box
entity, the analyst would add processes that deal with the external agents and produces
certain outputs. This is level one of a data flow model.
In level two of data flow model, instead of refining the previous levels further, we take
one process from the level one diagram and expands it in a level two diagram. Hence, a
level one diagram that depict the whole system, may be expanded to more then one level
two diagrams each of which describes exactly one process in detail which were listed in
level one diagram as simply an oval (process or transform).
This process may continue to any level of details as the analyst can conveniently
captures. Where diagram at a specific level is a refinement of one of the processes listed
in a previous level. By adding levels of abstraction to a data flow diagram, it becomes
natural for a software engineer or a requirement analyst to readily express his knowledge
about the system in an appropriate level of data flow model that corresponds only to a
specific set of functionality.
It should be noted here that the number of external agents and their inputs to the system
and the outputs that the system would return to them, should remain the same throughout
different levels of a data flow model. It should be considered a mistake if context level
diagram contains three external agents, which are providing two inputs each, and getting
one output in return but at level one, we add one more external agent or input or the
outputs. This would make level one model inconsistent with the context level diagram.
This is true for any level of data flow model. For instance, at level two the number of
external agents, inputs and outputs shown in (all of level two) diagrams should match
exactly with the external agents, inputs and outputs shown in level one diagram.
Therefore, disseminating information at an appropriate level of abstraction with the
additional check of inter-level consistency makes data flow modeling a very powerful
domain-modeling tool. After this discussion, we shall give the reader an example in
_____________________________________________________________________ 54
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
which a system is modeled using data flow modeling technique where three levels of
abstraction have been developed.
Patient Monitoring System – A Data Flow Modeling
Example
Context Diagram
Following is the 0-level or the context level data flow diagram of the Patient Monitoring
System. In this data flow diagram, three external entities (users) are interacting with the
centralized system. Point to note here is that in this context level diagram, only one
process or transform takes place that is the Patient Monitoring System itself. A patient’s
vital signs are transmitted to this system which may invoke a warning message to the
nurse if these signs fall into the critical range. Nurse may request for a report, which the
patient monitoring system retrieves from the patient log, and return it to the nurse again.
In this manner the 0-level data flow diagram describes the context of this system.
Report
Patient Nurse
Warning
Vital signs Patient
Message
Monitoring
Request for System
Report
Log data
_____________________________________________________________________ 55
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Central
Warning Message Monitoring
Nurse
Report Report
Generator
Log data
Request for Patient Log
Nurse Report
Level 1 data flow diagram is the refinement of the context (0-level) data flow diagram.
All the external entities are the same (Nurse, and Patient), however, the process of
‘Patient Monitoring System’ is further elaborated by the three processes Local
Monitoring, Report Generator, and Central Monitoring. The Local Monitoring process
transforms vital signs that it receives from Patient entity into Patient data and passes this
information to Central Monitoring process. Central Monitoring process retrieves vital
signs bounds and compares Patient data and it may generate Warning message if the
Patient data goes out of normal Vital signs bounds. A nurse may request for a report, in
response the Report Generator process retrieves Log data from Patient Log, generates the
report and displays it back to the nurse.
It should be noted here that this level 1 diagram is a further refinement of level 0 diagram
such that the underlying system is the same but processes which were hidden in level 0
are represented in this diagram.
A further refinement of this model is also possible if we expand any of these three
processes to capture further details. For example, the Local Monitoring process may
further be expanded to capture detailed activities involved in the monitoring process.
Following is level 2 diagram of Central Monitoring process.
Central Monitoring System – Level 2 Data Flow
Diagram
_____________________________________________________________________ 56
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Pulse
Patient bounds
Patient Unpack
data Signs Temperature
Vital signs
Blood pressure Evaluate bounds
Bounds
Violation
Blood pressure, Format
temp, and pulse
Produce Violation
Patient
Warning
Warning Clock Date time Data
message
Messag Formatted
e patient data
In the above level 2 data flow diagram, Patient’s data is sent to the Unpack Signs process
which unpacks it and send Pulse, Temperature, and Blood pressure to the Evaluate
Bounds Violation process. This process retrieves Vital signs bounds information,
compares it with unpacked patient data and sends a violation sign to the Produce Warning
Message process upon an out of bound result of the comparison. The patient data is sent
to Format Patient Data process that generates the formatted patient data to be maintained
against patient profile. In this manner we elaborated the patient monitoring system up to
three levels describing different details at each level. In a similar manner, other two
processes in level 1 DFD could also be expanded in their respective level two diagrams in
order to describe their functionality in more detail.
By going through this example, the reader would have learnt how data flow modeling
technique helps in understanding domain of a system at different levels of abstractions. In
the following sub-section, we shall describe common mistakes that the people do while
preparing data flow diagrams.
_____________________________________________________________________ 57
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Generate an
Employee Bank Statement Employee
Bank stmt
Existing Employee
Accounts Address Membership
Application
Member Create a
Employees Employee
Accounts
Status new member
Account
New Account
status Frozen
Freeze Accounts
Account
Member Receivable
Account Notification
Department
_____________________________________________________________________ 58
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
needed is an account number and the time period for which the statement is required. If
we analyze the inputs given to this process, we can observe that both of these inputs
cannot help in generating the account statement. Therefore, these inputs are irrelevant to
the output being generated by this process.
In the above mentioned example, it is evident that by applying the source and sink
analysis we determined all the missing inputs and outputs to the processes of this
diagram.
In the following subsection, we shall describe actions which are not only mistakes but
illegal too for the data flow diagrams.
Illegal Data Flows
Directly Communicating External Agents
Following diagram depicts a scenario in which one external entity is directly
communicating with another external entity. This form of communication is illegal to be
shown in a data flow diagram.
B1 B2
There must be an intermediate process which should transform data received from one
external entity and then send the transformed data to the other external entity. As we have
already described that data flow diagrams should be used to depict processes that
transform or process data. Simple data movement from one entity to another should not
be described using data flow diagrams.
A process is
needed to
B1 exchange data B2
between
external agents
_____________________________________________________________________ 59
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
B1 Data
Store
Therefore, a process should be inserted between the interacting entities (external agent,
data store) that should store information received from the external agent after processing
it.
A process is
B1 needed to Data
update a Store
data store
B1 Data
Store
_____________________________________________________________________ 60
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
A process is
B1 needed to Data
use a data Store
store
Copying data to a data store
In the following diagram, a data store is shown copying data directly to another data
store. This is again illegal as there is not any intermediate process/data transform
mentioned.
Data Data
Store Store
So, the correct method is again to use a data transform/process between the two data
stores. It should retrieve data from one data store and after transforming that data, store it
into another data store.
A process is
needed to
Data Data
Store copy data from Store
onr data store
to another
_____________________________________________________________________ 61
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 10
Prototyping and GUI Design
GUI Sketches
Adding user interface details in the SRS is controversial. The opponents of this argue that
by adding GUI details to the SRS document, focus shifts from what to how – GUI is
definitely part of the solution. On the other hand many people think that, it is still what
not how and hence it should be made part of the SRS document. By adding the GUIs in
the FS, requirements can be solidified with respect to scenario contents. It is my personal
experience that the client appreciates more the contents of the SRS document if our SRS
document contains the GUI details than if we don’t have them there. This document is
also going to be used as the base line for design, user manual, and test planning among
other things. Presence of the UI details imply that these activities can start right after SRS
is accepted and signed-off. Emergence of rapid GUI drafting tools has made the task a lot
simpler than it used to be. Exploring potential user interfaces can be of help in refining
the requirements and making the user-system interaction more tangible to both the user
and the developer. User displays can help in project planning and estimation. A user
interface might highlight weaknesses in addressing some of the non-functional
requirements (such as usability), which are otherwise very hard to fix later on. If you
cannot freeze the RS until UI is complete, requirement development process takes a
longer time. However, we need to be very careful when we use GUIs to the SRS
document. It is a very common mistake to use UI layouts as substitute of defining the
functional requirements. We must remember that these are supplementary information
and cannot replace other components of the SRS document. Any change in the
requirements entails a change in the UI. If the requirements are not stable, this can mean
a lot of rework.
Motivation for GUI
System users often judge a system by its interface rather than its functionality
A poorly designed interface can cause a user to make catastrophic errors
Poor user interface design is the reason why so many software systems are never
used
Pitfalls of using GUIs in Functional Specifications
UIs distract from business process understanding (what) to interfacing details
(how)
Unstable requirements cause frequent modifications in UIs
An extra work to be done at the requirement level each time a GUI change has to
be incorporated
_____________________________________________________________________ 62
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The following GUI implements the delete component use case that we discussed in use
case section. The GUI displays a drop down list box that contains a list of component
types. The top of the list entry is ‘None’ where the user can click on the arrow and select
the component type whose component he wants to delete.
The next GUI implements the scenario when user has clicked over the arrow and a few
component types are populated in the list. User then selects a component type ‘Plan
Type’. Corresponding plans are populated and displayed in the list box at the right side of
the GUI.
_____________________________________________________________________ 63
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Following GUI depicts the scenario when user selects a particular plan ‘Plan 3’ and clicks
on the ‘Delete’ button. Now assume that ‘Plan 3’ is currently being used. So, the
application displays a dialog box to the user informing him that he cannot deletes this
plan as it is in use.
The next GUI, another dialog box is shown in which user is getting another message from
the system. It says that Plan 3 is not in his hierarchy.
_____________________________________________________________________ 64
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The user then selects ‘Plan 2’ and deletes it. System confirms the user and upon
confirmation, deletes ‘Plan 2’.
After deleting ‘Plan 2’, it displays the message that Plan 2 has been permanently deleted.
Whereas, ‘Plan 2’ is still visible in the list.
_____________________________________________________________________ 65
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
However, it should be noted that, all the above GUIs presented two major mistakes about
the GUIs. First, if a plan is currently in use, it should not have been displayed in the list at
the right. Secondly, instead of displaying two messages separately in two dialog boxes, it
would have been appropriate to combine them in one message.
The following GUI displays what this GUI should have displayed ideally. As, user can
only delete plans 1 and 2, therefore, only these plans should have displayed to him.
_____________________________________________________________________ 66
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In the above example, it is evident that if requirements are partially generated a number
of changes have to be made and sometimes the frequency of these changes rise so much
that it takes all of the requirements and design time just in finalizing GUIs.
_____________________________________________________________________ 67
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Prototype
Prototyping is yet another technique that can be used to reduce customer dissatisfaction at
the requirement stage. The idea is to capture user’s vision of the product and get early
feedback from user to ensure that the development team understands requirements. This
is used when there is uncertainty regarding requirements. Sometimes, even the customer
does not know what he/she actually needs. This happens when there is no manual
solution.
A prototype is not the real product. It is rather just a real looking mock-up of what would
be eventually delivered and might not do anything useful. However, the presence of a
prototype makes a new product tangible. It brings use cases to life and closes gaps in
your understanding of the requirements. From a user’s perspective, it is easier to play
with a prototype and try it out than to read SRS.
_____________________________________________________________________ 68
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 11
Software Design
6.1 Introduction
Recalling our discussion of software construction process, once the requirements of a
software system have been established, we proceed to design that system. During the
design phase, the focus shifts from what to how. That is, at this stage we try to answer the
question of how to build the system. The objective of the design process is to analyze and
understand the system in detail so that features and constituent components of at least one
feasible solution are identified and documented. The design activity provides a roadmap
to progressively transform the requirements through a number on stages into the final
product by describing the structure of the system to be implemented.
It includes modeling of the data structures and entities, the physical and logical
partitioning of the system into components, and the interfaces between different
components of the system as well as interfaces to the outside world. Sometimes design of
algorithms is also included in this activity.
A complex system that works is invariably found to have evolved from a simple system
that worked. The structure of a system also plays a very important role. It is likely that
we understand only those systems that have hierarchical structure and where intra-
component linkages are generally stronger than inter component linkages. To manage the
complexity of the system we need to apply the principles of separation of concern,
modularity, and abstraction. This leads to designs that are easy to understand and hence
easy to maintain.
Separation of concern, modularity, and abstraction are different but related principles.
A complex system may be divided into smaller pieces of lesser complexity called
modules. This is the classic divide-and-conquer philosophy – if you cannot solve a
complex problem, try to break it into smaller problems that you can solve separately and
then integrate them together in a systematic fashion to solve the original problem. One
major advantage of modularity is that it allows the designer to apply the principle of
separation of concern on individual modules.
_____________________________________________________________________ 69
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Software design is not a sequential process. Design of a software system evolves through
a number of iterations. The design process usually involves developing a number of
different models, looking at the system from different angles and describing the system at
various levels of abstraction. Like the various different models used during requirement
engineering domain models, these models complement each other. As stated earlier,
software design provides a road map for implementation by clearly describing how the
software system is to be realized.
Software design process revolves around decomposing of the system into smaller and
simpler units and then systematically integrates these units to achieve the desired results.
Two fundamental strategies have been used to that end. These are functional or structured
design and object oriented design.
In the functional design, the structure of the system revolves around functions. The entire
system is abstracted as a function that provides the desired functionality (for example, the
main function of a C program). This main function is decomposed into smaller functions
and it delegates its responsibilities to these smaller functions and makes calls to these
functions to attain the desired goal. Each of these smaller functions is decomposed into
even smaller functions if needed. The process continues till the functions are defined at a
level of granularity where these functions can be implemented easily. In this design
approach, the system state, that is the data maintained by the system, is centralized and is
shared by these functions.
The object-oriented design takes a different approach. In this case the system is
decomposed into a set of objects that cooperate and coordinate with each other to
implement the desired functionality. In this case the system state is decentralized and
each object is held responsible for maintaining its own state. That is, the responsibility of
marinating the system state is distributed and this responsibility is delegated to individual
objects. The communication and coordination among objects is achieved through
message passing where one object requests the other object if it needs any services from
that object.
_____________________________________________________________________ 70
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The object-oriented approach has gained popularity over the structured design approach
during the last decade or so because, in general, it yields a design that is more
maintainable than the design produced by the functional approach.
A software design can be looked at from different angles and different parameters can be
used to measure and analyze its quality. These parameters include efficiency,
compactness, reusability, and maintainability. A good design from one angle may not
seem to be suitable when looked from a different perspective. For example, a design that
yields efficient and compact code may not be very easy to maintain. In order to establish
whether a particular design is good or not, we therefore have to look at the project and
application requirements. For example, if we need to design an embedded system for the
control of a nuclear reactor or a cruise missile, we would probably require a system that
is very efficient and maintainability would be of secondary concern. On the other hand, in
the case of an ordinary business system, we would have a reversal in priorities.
Maintainable Design
Since, in general, maintenance contributes towards a major share of the overall software
cost, the objective of the design activity, in most cases, is to produce a system that is easy
to maintain. A maintainable design is the one in which cost of system change is minimal
and is flexible enough so that it can be easily adapted to modify exiting functionality and
add new functionality.
Lecture No. 12
6.3 Coupling and Cohesion
Strong cohesion implies that all parts of a component should have a close logical
relationship with each other. That means, in the case some kind of change is required in
the software, all the related pieces are found at one place. Hence, once again, the scope is
limited to that component itself.
_____________________________________________________________________ 71
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
A component should implement a single concept or a single logical entity. All the parts of
a component should be related to each other and should be necessary for implementing
that component. If a component includes parts that are not related to its functionality,
then the component is said to have low cohesion.
Coupling and cohesion are contrasting concepts but are indirectly related to each other.
Cohesion is an internal property of a module whereas coupling is its relationship with
other modules. Cohesion describes the intra-component linkages while couple shows the
inter-component linkages. Coupling measures the interdependence of two modules while
cohesion measures the independence of a module. If modules are more independent, they
will be less dependent upon others. Therefore, a highly cohesive system also implies less
coupling.
A good example of a system with a very high cohesion and very less (almost nil)
coupling is the electric subsystem of a house that is made up of electrical appliances and
wires. Since each one of the appliances has a clearly definable function that is completely
encapsulated within the appliance. That means that an appliance does not depend upon
any other appliance for its function. Therefore, each appliance is a highly cohesive unit.
Since there are no linkages between different appliances, they are not coupled. Let us
now assume that we have added a new centralized control unit in the system to control
different appliances such as lights, air conditioning, and heating, according to certain
settings. Since this control unit is dependent upon the appliances, the overall system has
more coupling than the first one.
Modules with high cohesion and low coupling can be treated and analyzed as black
boxes. This approach therefore allows us to analyze these boxes independent of other
modules by applying the principle of separation of concern.
This diagram depicts two systems, one with high coupling and the other one with low
coupling. The lines depict linkages between different components. In the case of highly
coupled system, module boundaries are not well defined, as everything seems to be
connected with everything else. On the other hand, in the system with low coupling
_____________________________________________________________________ 72
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
modules can be identified easily. In this case intra component linkages are stronger while
inter component linkages are weak.
_____________________________________________________________________ 73
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Example of Coupling
The modules that interact with each other through message passing have low coupling
while those who interact with each other through variables that maintain information
about the state have high coupling. The following diagram shows examples of two such
systems.
Module A
A's Data
Module C
A
High Coupling
C's
A's Data
Low Coupling
In order to understand this concept, let us consider the following example. In this
example, we have a class vector in which the data members have been put in the public
part.
class vector {
public:
float x;
float y;
vector (float x, float y);
float getX();
float getY();
float getMagnitude();
float getAngle();
};
Now let us assume that we want to write a function to calculate dot product of two
vectors. We write the following function.
_____________________________________________________________________ 74
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Since the data members are public, one could be enticed to use these members directly
(presumably saving some function calls overhead) and rewrite the same function as
follows:
So far, there does not seem to be any issue. But the scenario changes as soon as there are
changes in the class implementation. Now let us assume that for some reason the class
designer changes the implementation and data structure and decides to stores the angle
and magnitude instead of the x and y components of the vector. The new class looks like
as follows:
class vector {
public:
float magnitude;
float angle;
vector (float x, float y);
vector (float magnitude, float angle);
float getX();
float getY();
float getMagnitude();
float getAngle();
};
Now we see the difference in the two implementations of the dot product function written
by the user of this class. In the first case, as the dot product function is dependent upon
the public interface of the vector class, there will be no change while in the second case
the function will have to be rewritten. This is because in the first case the system was
loosely coupled while in the second case there was more dependency on the internal
structure of the vector class and hence there was more coupling.
_____________________________________________________________________ 75
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Example of Cohesion
As mentioned earlier, strong cohesion implies that all parts of a component should have a
close logical relationship with each other. That means, in case some kind of change is
required in the software, all the related pieces are found at one place.
A class will be cohesive if most of the methods defined in a class use most of the data
members most of the time. If we find different subsets of data within the same class being
manipulated by separate groups of functions then the class is not cohesive and should be
broken down as shown below.
Class X1
f1 f1
f2 f2
f3
f4
Class X2
f3
f4
_____________________________________________________________________ 76
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
class order {
public:
int getOrderID();
date getOrderDate();
float getTotalPrice();
int getCustometId();
string getCustomerName();
string getCustometAddress();
int getCustometPhone();
The Order class shown above represents an Order entity that contains the attributes and
behavior of a specific order. It is easy to see that this contains information about the order
as well as the customer which is a distinct entity. Hence it is not a cohesive class and
must be broken down into two separate classes as shown. In this case each on of these is
a more cohesive class.
_____________________________________________________________________ 77
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
class order {
public:
int getOrderID();
date getOrderDate();
float getTotalPrice();
int getCustometId();
class customer {
public:
int getCustometId();
string getCustomerName();
string getCustometAddress();
int getCustometPhone();
int getCustomerFax();
_____________________________________________________________________ 78
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Engineers of all fields, including computer science, have been practicing abstraction for
mastering complexity. Consider the following example.
This function can be rewritten by abstracting out some of the logical steps into auxiliary
functions. The new code is as follows.
_____________________________________________________________________ 79
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In this function we have abstracted out two logical steps performed in this functions.
These functions are finding the index of the minimum value in the given range in an array
and swapping the minimum value with the value at the ith index in the array. It is easy to
see that the resultant new function is easier to understand than the previous version of the
selection sort function. In the process, as a by-product, we have created two auxiliary
function mentioned above, which are general in nature and hence can be used elsewhere
as well. Principle of abstraction thus generates reusable self-contained components.
Let us now try to understand the difference between object-oriented and function oriented
(or action oriented) approach.
_____________________________________________________________________ 80
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Functions
Data
In this diagram, the ovals depict the function while rectangles/squares depict data. Since a
function contains dynamic information while data contains only static information, if the
function and data are managed separately, the required data components can be found by
scanning a function but the functions that use a particular data cannot be found by just
looking at the data. That is, the function knows about the data it needs to use but the data
do not know about the functions using it. That means it is easy to make a change in a
function since we would know which data components would be affected by this change.
On the other hand, changing a data structure would be more difficult because it would not
be easy to find all the functions that are using this data and hence also need to be
modified.
Object oriented approach solves this problem by putting the relevant data and
functionality together at one place. Hence, in case of a change, the effected components
can be identified easily and the effect of change is localized. Therefore, maintenance
becomes relatively easy as compared to function-oriented approach. This is made
possible because the data is not shared in this case. Anyone needing any information
contained in there would request the encapsulating object by sending it a message
through the interface provided by the object. In this case we create highly cohesive
objects by keeping the related data and function at one place and spinning-off non-related
information into other classes. This can be elaborated with the help of the following
diagram.
_____________________________________________________________________ 81
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
1 2
Let us assume that the circles represent sets of functions and rectangles represent data
that these function use to carry out their operation. In the object-oriented design, the data
areas that are common among different sets of functions would be spun-off into their own
classes and the user function would use these data through their interfaces only. This is
shown in the following diagram.
6 2 10
1
4
7
8 9
_____________________________________________________________________ 82
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 13
Object Oriented Analysis and Design
A complex system that works is invariably found to have evolved from a simple system
that worked. The structure of a system also plays a very important role. It is likely that
we understand only those systems which have hierarchical structure and where intra-
component linkages are generally stronger than inter component linkages. That leads to
loose coupling, high cohesion and ultimately more maintainability which are the basic
design considerations. Instead of being a collection of loosely bound data structures and
functions, an object-oriented software system consists of objects which are, generally,
hierarchical, highly cohesive, and loosely coupled.
Some of the key advantages which make the object-oriented technology significantly
attractive than other technologies include:
Clarity and understandability of the system, as object-oriented approach is closer to
the working of human cognition.
Reusability of code resulting from low inter-dependence among objects, and
provision of generalization and specialization through inheritance.
Reduced effort in maintenance and enhancement, resulting from inheritance,
encapsulation, low coupling, and high cohesion.
_____________________________________________________________________ 83
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Functions
Data
In this diagram, the ovals depict the function while rectangles/squares depict data. Since a
function contains dynamic information while data contains only static information, if the
function and data are managed separately, the required data components can be found by
scanning a function but the functions that use a particular data cannot be found by just
looking at the data. That is, the function knows about the data it needs to use but the data
do not know about the functions using it. That means, it is easy to make a change in a
function since we would know which data components would be affected by this change.
On the other hand, changing a data structure would be difficult because it would not be
easy to find all the functions that are using this data and hence also need to be modified.
In the case of OO design since data and function are put together in one class, hence, in
case of a change, the effected components can be identified easily and the effect of
change is localized. Therefore, maintenance becomes relatively easy as compared to
function-oriented approach.
_____________________________________________________________________ 84
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The state of an object encompasses all of the properties of the object and their current
values. A property is an inherent or distinctive characteristic. Properties are usually static.
All properties have some value. The state of an object is encapsulated within the object.
Behavior is how an object acts and reacts in terms of its state changes and message
passing. The behavior of an object is completely defined by its actions. A message is
some action that one object performs upon another in order to elicit a reaction. The
operations that clients may perform upon an object are called methods.
The structure and behavior of similar objects are defined in their common class. A class
represents an abstraction - the essence or the template of an object. A class specifies an
interface ( the outside view - the public part) and defines an implementation ( the inside
view - the private part). The interface primarily consists of the declaration of all the
operations applicable to instances of this class. The implementation of a class primarily
consists of the implementation of all the operations defined in the interface of the class
Classification
The most important and critical stage in the OOA and OOD is the appropriate
classification of objects into groups and classes. Proper classification requires looking at
the problem from different angles and with an open mind. When looked at from different
perspectives and analyzed with different set of characteristics, same object can be
classified into different categories. Let us try to understand this with the help of an
example.
Responsibility-Driven
Data-Driven carry things, communicate,
head, tail, body, leg maintain its living system
Behavior-Driven
walk, run, eat
_____________________________________________________________________ 85
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In an association relationship, when object A “uses” object B, then A may send messages
to B. The relationship defines visibility among objects.
The aggregation relationship defines part-of structure among objects. When object A is
part of the state of object B, A is said to be contained by B. There are some tradeoffs
between aggregation and association relationships. Aggregation reduces the number of
objects that must be visible at the level of enclosing objects and may lead to undesirable
tighter coupling among objects.
_____________________________________________________________________ 86
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________ 87
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In other words, in case of aggregation, the whole owns its parts and the part becomes a
private property of the whole. For all practical purposes, any other object does not even
need to know about its existence. On the other hand, an associated object may be shared
among many different objects. That is, many different object may hold reference to the
same object simultaneously.
Database persistence
From a database perspective, when an object is persisted or stored in the database, all of
its components (all parts of the whole) must also be persisted in their entirety along with
the “whole” for future reference while only a reference to the associated object may be
stored in the database. Note that a normalized database would also enforce the above
restriction.
Lecture No. 14
1) Static Model
a) Identify classes (i.e. attributes and methods are defined)
b) Specify class hierarchy
c) Identify object-to-object relationships
d) Model the object behavior
2) Dynamic Model
a) Scenario Diagrams
_____________________________________________________________________ 88
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Classes Objects
methods algorithms
relationships messaging
behavior control
Translating the analysis model into a design model during object design
_____________________________________________________________________ 89
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Once all the model components have been identified, we will eliminate the redundant or
irrelevant components by again analyzing the text and the context of the problem.
Let’s now try to understand this with the help of an example:
Problem Statement:
A simple cash register has a display, an electronic wire with a plug, and a numeric
keypad, which has keys for subtotal, tax, and total. This cash storage device has a total
key, which triggers the release on the drawer. The numeric buttons simply place a
number on the display screen, the subtotal displays the current total, the tax key computes
the tax, and the total key adds the subtotal to the tax.
Nouns (initial)
_____________________________________________________________________ 90
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Total Tax
We now analyze the identified nouns and try to establish whether they would be stand-
alone classes in our domain or not. Outcome of this analysis is shown below.
Register
Display
Wire Irrelevant
Plug Irrelevant
Keypad
Keys
Devices Vague
Release Irrelevant
Drawer
Buttons Redundant
Screen Redundant
Number Attribute
Total Attribute
Tax Attribute
0-9 Key
Value Attribute
Money
Subtotal Key
Tax Key
Total Key
We will continue with technique to identify all the constituent components of the model
and derive our object-oriented design.
_____________________________________________________________________ 91
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 15
The Notation
Many different notations are used for documenting the object oriented design. Most
popular of these include, Rumbaugh, Booch, and Coad, and UML(Unified Modeling
Language). We will be using UML to document our design. Although the notation is very
comprehensive and detailed, but the key features of this notation are presented in the
following diagram.
_____________________________________________________________________ 92
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 16
Derivation of the Object Model – The Coad Methodology
An object model of a system captures the static structure of a system by showing the
objects in the systems, their relationships, their attributes, and their services. To stream
line the derivation of the object model, Peter Coad has divided the process into 5
activities, each being further subdivided into a number of steps. Following is the
description of these activities.
Select actors
Actors are people and organizations that take part in the system under consideration.
Examples of actors are: person, organization (agency, company, corporation, foundation).
Note that we are talking about actors and not their “roles”. e.g. a customer is a role that a
person plays, so if we have a customer in our problem domain, we will also add a person
as actor in the model.
Select Participants
A participant is a role that each actor plays in the system under consideration. Examples
of participants are: agent, applicant, buyer, cashier, clerk, customer, dealer, distributor,
donor, employee, investor, member, officer, owner, policy holder, recipient, student,
supervisor, supplier, teacher, worker. It may be noted that the same person may play
different roles at different times in the system. That means that if we model this behavior
using Generalization-Specialization instead of Actor-Participant, we may end up with
multiple inheritance.
Select Places
Places are where things come to rest or places that contain other objects. Examples of
places are: airport, assembly-line, bank, city, clinic, country, depot, garage, hanger,
hospital, plant, region, sales outlet, service center, shelf, station, store, warehouse, zone.
Select Transactions
Transactions are the “events” that must be remembered through time. These are entries
that must be maintained in a historical record or log which may be used to answer
questions or perform assessments. These transactions usually come from a window
(GUI), some object which monitors for significant event and logs that information, or a
another system that interacts with the system under consideration and logs some
_____________________________________________________________________ 93
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
While selecting objects, the following considerations should be kept in mind for a simpler
(and better) object model.
1. Every object that you put in your object model should have some responsibility or
role to play in the problem domain. You need to know each object, its attributes, and
services. If there is no way to know about the object, remove it from the object
model.
2. Avoid having controller objects because controllers usually end up with functionality
that’s better done by other objects themselves, making the message passing more
complicated, and resulting in higher coupling. Use delegation instead. Note the
difference between controlling and delegation; a controller wants to do every thing by
himself (doesn’t trust anyone), while a good manager delegates responsibility (and
takes credit).
3. In large systems several objects are likely to have similar or even identical
responsibilities. Look for such objects and seek a common name to simplify the
object model.
4. Use meaningful class names, names that describe objects in that class. Try to use
names from the domain vocabulary to avoid confusion.
Lecture No. 17
Identify Structures
A structure is a manner of organization which expresses a semantically strong
organization within the problem domain. There are two type of structures:
_____________________________________________________________________ 94
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
For each object include the attributes that come to mind when you first think about the
object. The criteria for the inclusion of an attribute is that it should be included if the
system needs to know its value and it cannot get it any other way. Don not add an
attribute for an association or aggregation. Examples of attributes are: number, name,
address, date, time, operational state, phone, status, threshold, type, etc. In particular,
consider the following attributes for different types of objects.
Like object selection, there are a number of issues that every designer must be aware of
while defining attributes of an object. These are:
1. An attribute that varies over time, e.g., price of an item, should be replaced by an
additional class with an effective date and value.
2. An attribute that may have a number of values should be replaced by a new class and
an object connection.
3. Replace “yes/no” type attributes with “status” type attributes for flexibility.
4. If there are classes with common attributes and generalization-specialization makes
good sense, then add a generalization class and factor out the commonality.
_____________________________________________________________________ 95
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Software objects do things that the system is responsible to do with regard to that object.
By putting the services with the attributes they work on results in lower coupling and
stronger cohesion, and increased likelihood of reuse. The basic principle is to keep data
and action together for lower coupling and better cohesion. The basic services, done by
all (such as get, set, create, initialize), are not shown in the object model. While
establishing the services for an object, the following fundamental questions should be
asked:
_____________________________________________________________________ 96
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
While establishing services of certain specific types of objects, the following should be
considered:
1. For an actor, consider: calculate for me, rate me, is <value>, rank participants,
calculate over participants.
2. For a participant, consider: calculate for me, rate me, is <value>, rank transactions,
calculate over transactions.
3. For a place, consider: calculate for me, rate me, is <value>, rank transactions,
calculate over contents, calculate over container line items.
4. For a Transaction, consider: calculate for me, rate me, is <value>, how many, how
much, rank transaction line items, rank subsequent transactions, calculate over
transaction line items, calculate over subsequent transactions.
5. For a line item, consider: calculate for me, rate me.
6. For an item, consider: calculate for me, rate me, is <value>, how many, how much,
rank, calculate over specific items.
Lecture No. 18
CASE STUDY: Connie’s Convenience Store - A point of
Sale System
The System
Identify the purpose of the system
develop an overall purpose statement in 25 words or less. Why this system?
Why now?
Keep the overall goal, the critical success factor, always before you.
“To support, to help, to facilitate, ...”
_____________________________________________________________________ 97
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
balance the cash in the drawer with the amount recorded by the point-of-sale
system.
Why ?
speed up checkout time
reduce the number of pricing errors
reduce the labour required to ticket the item with a price, originally and when
prices change.
Summary
to help each cashier work more effectively during checkout, to keep good records
of each sale, and to store more efficient store operations.
_____________________________________________________________________ 98
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
SELECTING OBJECTS
Select Actors
the actor is:
person
Select Participants
the Participants are:
cashier
head cashier
customer
Select Places
The places are:
store
shelf
Shelf
The system does not keep track of the shelves.
Select Transactions
Significant Transactions are:
sale
every sale is a collection of sale line items
return
payment
session
_____________________________________________________________________ 99
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
item
register
cash drawer
Tax Category (Descriptive things)
Session
Is it important? It is important in order to evaluate a cashier’s performance.
Kinds of sales:
- sales, returns
- only different is that the amount is positive or negative. Is there any other
difference?
Prices:
- regular price, and promotional (sales) price
Payment:
- cash, check, and charge are kind of payments
_____________________________________________________________________100
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Payment Price
Object Hierarchy
Stote Sale
Cash Drawer
Whole-Part Structures
Establishing Responsibilities
Who I Know - Rules of Thumb
an actor knows about its participants
person knows about cashier
a transaction knows about its participants
a session knows about its register and cashier
A transaction contains its transaction line items
sale contains its sales line items
_____________________________________________________________________101
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Payment Sales
Association Relationships
Define Attributes, Services, and Links - What I know, What I do, and Who I
know?
Actors:
person
Attributes: name, address, phone
Services:
Participants:
cashier
Attributes: number, password, authorization level, current session
Services: isAuthorized, assess Performance
Places:
store
Attributes: name
Services: get item for UPC, get cashier for number
_____________________________________________________________________102
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Tangible things:
item
Attributes: number, description, UPCs, prices, taxable
attributes with repeating names - create new objects
UPC, Price (specialization - promotional price)
Services: get price for a date, how much for quantity
Who I Know? UPC, Price, tax category, sale line item
register
Attributes: number
Services: how much over interval, how many over interval
Who I know? store, session, cash drawer (part of register)
cash drawer
Attributes: balance, position (open, close), operational state
Services: open
Who I know? register
Tax Category
Attributes: category, rate, effective date
Services: just the basic services - get, add, set - don’t show
Who I know? items?
Transactions:
sale
Attributes: date and time
Services: calculate subtotal, calculate total, calculate discount,
calculate
tax, commit
Who I Know? session, payment, SLIs
return
Attributes: return price, reason code, sale date, sale price
_____________________________________________________________________103
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Services:
Who I Know?
Services:
who I know: sale
Cheque Charge
session
Attributes: start date, end date, start time, end time
Services: how much money collected over interval, how many sales
_____________________________________________________________________104
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Promotional Price
Person Sale
Authorized
Return Line Item Cash Payment
Payment
Cheque Charge
_____________________________________________________________________105
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
UML provides two different mechanisms to document the dynamic behaviour of the
system. These are sequence diagrams which provide a time-based view and
Collaboration Diagrams which provide an organization-based view of the system’s
dynamics.
The Notation
Following diagram illustrates the notation used for drawing sequence diagrams.
Lifeline Message
CS504-Software Engineering – I VU
The boxes denote objects (or classes), the solid lines depict messages being sent from one
object to the other in the direction of the arrow, and the dotted lines are called life-lines of
objects. The life line represents the object’s life during interaction. We will discuss this in
more detail later.
These concepts are further elaborated with the help of the following sequence diagram.
X-Axis (objects)
member: :Book
book:Book
LibraryMember Copy
borrow(book)
Life Object
ok = mayBorrow()
Y-Axis (time)
Line
message
[ok] borrow(member)
Activation
setTaken(member) box
condition
As shown above, in a sequence diagram, objects (and classes) are arranged on the X-Axis
(horizontally) while time is shown on the Y-Axis (vertically). The boxes on the life-line
are called activation boxes and show for how long a particular message will be active,
from its start to finish. We can also show if a particular condition needs to occur before a
message is invoked simply by putting the condition in a box before the message. For
example, object member:LibraryMember sends a message to object book:book if the
value of ok is true.
An interaction between two objects is performed as a message sent from one object to
another. It is most often implemented by a simple operation call. It can however be an
_____________________________________________________________________107
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
actual message sent through some communication mechanism, either over the network or
internally on a computer.
If object obj1 sends a message to another object obj2 an association must exist between
those two objects. There has to be some kind of structural dependency. It can either be
that obj2 is in the global scope of obj1, or obj2 is in the local scope of obj1 (method
argument), or obj1 and obj2 are the same object.
A message is represented by an arrow between the life lines of two objects. Self calls are
also allowed. These are the messages that an object sends to itself. This notation allows
self calls. In the above example, object member:LibraryMember sends itself the
mayBorrow message. A message is labeled at minimum with the message name.
Arguments and control information (conditions, iteration) may also be included. It is
preferred to use a brief textual description whenever an actor is the source or the target of
a message.
The time required by the receiver object to process the message is denoted by an
activation-box.
Lecture No. 19
Message Types
Sequence diagrams can depict many different types of messages. These are: synchronous
or simple, asynchronous, create, and destroy. The following diagram shows the notation
and types of arrows used for these different message types.
Synchronous
Asynchronous
<<create>>
Create
<<destroy>>
Destroy
Synchronous Messages
Synchronous messages are “call events” and are denoted by the full arrow. They
represent nested flow of control which is typically implemented as an operation call. In
case of a synchronous message, the caller waits for the called routine to complete its
_____________________________________________________________________108
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
operation before moving forward. That is, the routine that handles the message is
completed before the caller resumes execution. Return values can also be optionally
indicated using a dashed arrow with a label indicating the return value. This concept is
illustrated with the help of the following diagram.
:A :B
doYouUnderstand()
return
Caller
yes (optional)
Blocked
Don’t model a return value when it is obvious what is being returned, e.g.
getTotal()
Model a return value only when you need to refer to it elsewhere, e.g. as a
parameter passed in another message.
Prefer modeling return values as part of a method invocation, e.g.
ok = isValid()
Asynchronous messages
Asynchronous messages are “signals,” denoted by a half arrow. They do not block the
caller. That is, the caller does not wait for the called routine to finish its operation for
continuing its own sequence of activities. This occurs in multi-threaded or multi-
processing applications where different execution threads may pass information to one
another by sending asynchronous messages to each other. Asynchronous messages
typically perform the following actions:
Create a new thread
Create a new object
Communicate with a thread that is already running
2 : process
3 : add course
CS504-Software Engineering – I VU
:A :B
<<destroy>>
_____________________________________________________________________110
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Collaboration diagrams
Collaboration diagrams can also be used to depict the dynamic behaviour of a system.
They show how objects interact with respect to organizational units (boundaries!).
Since a boundary shapes communication between system and outside world e.g. user
interface or other system, collaboration diagrams can be used to show this aspect of the
system. The sequence of messages determined by numbering such as 1, 2, 3, 4, … This
shows which operation calls which other operation.
Collaboration diagrams have basically two types of components: objects and messages.
Objects exchange messages among each-other. Collaboration diagrams can also show
synchronous, asynchronous, create, and destroy message using the same notation as used
in sequence diagrams. Messages are numbered and can have loops
: ProfessorCourseManager
_____________________________________________________________________111
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Sequence diagrams are best to see the flow of time. On the other hand, static object
connections are best represented by collaboration diagrams. Sequence of messages is
more difficult to understand in collaboration diagrams than in the case of sequence
diagrams. On the other hand, object organization with control flow is best seen through
collaboration diagrams. It may be noted that complex control is difficult to express
anyway but collaboration diagrams can become very complex very quickly .
You may also recall our earlier discussion of coupling and cohesion. It can be easy to see
that OO design yield more cohesive and loosely coupled systems.
The issue of centralized versus distributed control can be illustrated with the help of the
following example.
Desired des
Temp ired
T emp
( )
Actual actualTemp() Heat Flow
Furnace
Temp Regulator
t()
ePr esen
n
Occupancy anyo
In this case, the room is not encapsulated as one entity and three different objects namely
Desired Temp, Actual Temp, and Occupancy maintain necessary information about a
room. In this case the Heat Flow Regulator has to communicate with three different
objects.
_____________________________________________________________________112
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
If we encapsulate the three objects into one Room object as shown below, then the Heat
Flow Regulator will need to communicate with one object, hence the overall coupling of
the system will be reduced.
Room
Desired
Temp desiredTemp()
Occupancy
This happened because in the first case intelligence is distributed while in the second case
it is encapsulated. However, the control is still centralized as the Heat Flow Regulator has
the control logic that first analyses the values from different queries and then makes a
decision about turning the furnace on of off. We can improve the situation even further
by delegating this responsibility to the Room object as shown below.
Room
Desired
Temp
Occupancy
By doing that we reduce coupling even further because now we have made Room more
cohesive by putting the function with the related data and have thus reduced the number
and types of messages being sent from the regulator to the room.
That is, we can reduce the coupling of a system by minimizing the number of messages
in the protocol of a class. The problem with large public interfaces is that you can never
find what you are looking for…smaller public interfaces make a class easier to
understand and modify. This can be further elaborated with the help of the following
example. Suppose we have two functions defined for setting the desired temperature in
the room:
_____________________________________________________________________113
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
SetMinimumValue(int aValue)
SetMaximimumValue(int aValue)
We can reduce the total number of messages in the protocol of this class by consolidation
these as shown below, hence reducing the overall complexity of the protocol.
It is however important to use these kinds of heuristics judiciously and care must be taken
so that the scope of the function does not go beyond providing one single operation.
_____________________________________________________________________114
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The design process for identifying the sub-systems making up a system and the
framework for sub-system control and communication is architectural design. The output
of this design process is a description of the software architecture.
The study of software architecture is in large part a study of software structure that began
in 1968 when Edsger Dijkstra pointed out that it pays to be concerned with how software
is partitioned and structured, as opposed to simply programming so as to produce a
correct result. Dijkstra was writing about an operating system, and first put forth the
notion of a layered structure, in which programs were grouped into layers, and programs
in one layer could only communicate with programs in adjoining layers. Dijkstra pointed
out the elegant conceptual integrity exhibited by such an organization, with the resulting
gains in development and maintenance ease.
David Parnas pressed this line of observation with his contributions concerning
information-hiding modules, software structures, and program families.
A program family is a set of programs (not all of which necessarily have been or will
ever be constructed) for which it is profitable or useful to consider as a group. This
avoids ambiguous concepts such as "similar functionality" that sometimes arise when
describing domains. For example, software engineering environments and video games
are not usually considered to be in the same domain, although they might be considered
members of the same program family in a discussion about tools that help build graphical
user interfaces, which both happen to use.1
Parnas argued that early design decisions should be ones that will most likely remain
constant across members of the program family that one may reasonably expect to
_____________________________________________________________________115
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
produce. In the context of this discussion, an early design decision is the adoption of a
particular architecture. Late design decisions should represent trivially-changeable
decisions, such as the values of compile-time or even load-time constants.
All of the work in the field of software architecture may be seen as evolving towards a
paradigm of software development based on principles of architecture, and for exactly the
same reasons given by Dijkstra and Parnas: Structure is important, and getting the
structure right carries benefits.
Before talking about the software architecture in detail, let us first look at a few of its
definitions.
According to UML 1.3, a system is a collection of connected units that are organized to
accomplish a specific purpose. A system can be described by one or more models,
possibly from different viewpoints. IEEE Std. 610.12-1990 defines a system as a
collection of components organized to accomplish a specific function or set of functions.
That is, a system is defined as an organized set of connected components to accomplish
the specified tasks.
Let us now look at some of the software architecture definitions from some of the most
influential writers and groups in the field.
UML 1.3:
_____________________________________________________________________116
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Garlan and Perry, guest editorial to the IEEE Transactions on Software Engineering, April
1995:
IEEE Glossary
One can thus conclude from these definitions that an architectural design is an early stage
of the system design process. It represents the link between specification and design
processes. It provides an overall abstract view of the solution of a problem by identifying
the critical issues and explicitly documenting the design choices made under the specified
constraints as its primary goal is to define the non-functional requirements of a system
and define the environment. It is often carried out in parallel with some specification
_____________________________________________________________________117
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
activities and It includes the high-level design of modular components, their relationships
and organization, and provides a foundation that one can build on to solve a problem.
If a project has not achieved a system architecture, including its rationale, the
project should not proceed to full-scale system development. Specifying the
architecture as a deliverable enables its use throughout the development and
maintenance process.
_____________________________________________________________________118
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Not only does architecture prescribe the structure of the system being developed,
but it also engraves that structure on the structure of the development project. The
normal method of dividing up the labor in a large system is to assign different
portions of the system to different groups to construct. This is called the work
breakdown structure of a system. Because the system architecture includes the
highest level decomposition of the system, it is typically used as the basis for the
work breakdown structure. Specifically, the module structure is most often the
basis for work assignments. The work breakdown structure, in turn, dictates units
of planning, scheduling, and budget, as well as inter-team communications
channels, configuration control and file system organization, integration and test
plans and procedures. Teams communicate with each other in terms of the
interface specifications to the major components. The maintenance activity, when
launched, will also reflect the software structure, with teams formed to maintain
specific structural components.
Thus, once the architecture’s module structure has been agreed on, it becomes
almost impossible for managerial and business reasons to modify it. This is one
argument (among many) for carrying out extensive analysis before freezing the
software architecture for a large system.
Is it possible to tell that the appropriate architectural decisions have been made
(i.e., if the system will exhibit its required quality attributes) without waiting until
the system is developed and deployed? If the answer were “no,” choosing an
architecture would be a hopeless task: random architecture selection would
perform as well as any other method. Fortunately, it is possible to make quality
predictions about a system based solely on an evaluation of its architecture.
_____________________________________________________________________119
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
(or a family of closely related architectures) that will serve all envisioned
members of the product line by making design decisions that apply across the
family early and by making other decisions that apply only to individual members
late. The architecture defines what is fixed for all members of the family and
what is variable.
A family-wide design solution may not be optimal for all systems derived from it,
but the quality gained and labor savings realized through architectural-level reuse
may compensate for the loss of optimality in particular areas. On the other hand,
reusing a family-wide design reduces the risk that a derived system might have an
inappropriate architecture. Using a standard design reduces both risk and
development costs, at the risk of non-optimality.
Performance
– Performance can be enhanced by localising operations to minimise sub-
system communication. That is, try to have self-contained modules as
much as possible so that inter-module communication is minimized.
Security
– Security can be improved by using a layered architecture with critical
assets put in inner layers.
Safety
– Safety-critical components should be isolated
Availability
– Availability can be ensured by building redundancy in the system and
having redundant components in the architecture.
Maintainability
– Maintainability is directly related with simplicity. Therefore,
maintainability can be increased by using fine-grain, self-contained
components.
Just like any other design activity, design of software architecture is a creative and
iterative process. This involves performing a number of activities, not necessarily in any
particular order or sequence. These include system structuring, control modeling, and
modular decomposition. These are elaborated in the following paragraphs.
System structuring
_____________________________________________________________________120
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Control modelling
Modular decomposition
During this activity, the identified sub-systems are decomposed into modules.
This design process is further elaborated in the following section where architectural
views are discussed.
_____________________________________________________________________121
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
That is, a software architecture is a set of elements which have a certain form. These
elements are further divided into three categories. These are: data elements, processing
elements, and connecting elements. The data elements contain the information that is
used and transformed in the system; the processing elements process the data elements
and specify the transformation functions, and connecting elements connect different
pieces of architecture together. These can themselves be data or processing elements.
Krutchen proposed that the software architecture model should be composed of multiple
views as a software architecture deals with abstraction, with decomposition and
composition, with style and esthetics as well as requirements from different stake holders.
His architectural model is known as Krutchen’s 4+1 architectural view model. As
evident, this model proposes the development of 5 main views namely the logical view,
the process view, the physical view, the development view, and the use case view. The
logical view is the object model of the design, the process view captures the concurrency
and synchronization aspects of the design, the physical view documents the mapping(s)
of the software onto the hardware and reflects its distributed aspect, the development
view describes the static organization of the software in its development environment,
and the use case view uses selected use cases or scenarios to validate that the architecture
supports the required functionality.
End-user Programmers
Functionality Software management
Use Case View
_____________________________________________________________________122
Process ViewVirtual University
© Copyright Deployment View
of Pakistan
System integrators System engineering
Performance System topology
Scalability Delivery, installation
Throughput Communication
CS504-Software Engineering – I VU
This model has been slightly modified by Clements et. al. and is shown in the following
diagram.
Functional Develop-
Code
ment
Scenarios
Concurrency Physical
Clement’s modified version of Krutchen’s 4+1 Architectural View Model
In this model, the architecture is again prepared and analyzed from 5 different
perspectives. The 4 main views are Functional View, the Concurrency View, the Physical
View, and the Development View. Code view in not present in the original Krutchen
model and is basically an extension of the development view.
The Functional View comprises of various different functions provided by the system,
key system abstraction, and the domain elements. It connects different dependencies and
data flows into a single view. This view can be used by the domain engineers, product-
line engineers, as well as the end users of the system. It can be used for understanding the
functionality provided by the system, modifiability of the system, reusability, tool
support, and allocation of work.
The Development View documents the different files and directories in the system and
users of this view include the development and the configuration management staff as
well as the project managers. The major uses of this view include maintenance, testing,
configuration management, and version control.
The components of the Code View include classes, objects, procedures, functions,
subsystems, layers, and modules. It documents the calling as well as the containing
hierarchy of different components of the system. Its primary users are the programmers
and designers of the system. The primary intent of developing this view is to use it for
maintenance and portability.
_____________________________________________________________________123
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Concurrency View intends to document different parallel processes and threads in the
system. Its main focus is on event synchronization and parallel data flows. It is used
primarily by integrators, performance engineers, and testers. The main purpose of
building this view is to identify ways and means to improve performance by highlighting
possible opportunities for parallelism.
The Physical View depicts the physical organization of this system and how this system
will be physically deployed. This includes different processors, sensors, and storage
devices used by the system. This view connects various network elements and
communication devices. The primary users of this system include hardware and system
engineers. The view is developed with an intention to document and analyze system
delivery and installation mechanism. The view is also used in understanding and
analyzing issues pertaining to system performance, availability, scalability, and security.
Finally, there are Scenarios. Scenarios are basically use cases which describe the
sequences of responsibilities and change cases which are changes to the system. As stated
earlier, the first objective of developing a system is to fulfill the functional requirements
setout for the system. These functional requirements are written in the form of use cases.
Therefore, scenarios are used to understand and validate the system. Their secondary
purpose is to communicate the design to the other users of the system. Scenarios tie all
the view together into an integrated system. They are also used to understand the
dynamic behavior of the system and understand the limits of design.
_____________________________________________________________________124
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Views are an engineering tool to help achieve desired system qualities. Each view
provides an engineering handle on certain quality attributes. In some systems, distinct
views collapse into one (e.g., the concurrency and physical views may be the same for
small systems.). Views are also used as documentation vehicle for current development
and future development. Users of views include both managers and customers. For these
reasons views must be annotated to support analysis. This annotation can be achieved
with the help of scenarios and design rationale.
Structures can also be used to document how the current system was developed and how
future development should occur. This information is needed by managers and
customers.
Although one often thinks about a system’s structure in terms of functionality, there are
other system properties in addition to functionality (such as physical distribution, process
communication, and synchronization) that must be reasoned about at an architectural
level. Each structure provides a method for reasoning about some of the relevant quality
attributes. The uses structure, for instance, must be engineered (not merely recorded) to
build a system that can easily be extended or contracted. The calls structure is engineered
to reduce bottlenecks. The module structure is engineered to produce modifiable systems,
and so on. Each structure provides a different view into the system and a different
leverage point for design to achieve desired qualities in the system.
Hierarchical Views
Every view is potentially hierarchical, e.g. functional view could contain sub-functions.
Similarly development view contains directories which contain files. Code view would
have modules and systems that contain sub-modules and sub-systems respectively.
Concurrency view contains processes that are further subdivided into threads. Finally,
physical view clusters contain computers which contain processors.
Architectural views are related to each other in complicated ways. One has to choose the
views that are useful to the system being built and to the achievement of qualities that are
important for that particular application. The architectural views should be hierarchical
(where needed) and should contain enough annotated information to support desired
analyses.
Architectural styles
_____________________________________________________________________125
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
(1) a set of components (e.g., a database, computational modules) that perform a function
required by a system,
(2) a set of connectors that enable “communication, coordination and cooperation”
among components,
(3) constraints that define how components can be integrated to form the system, and
semantic models that enable a designer to understand the overall properties of a system
by analyzing the known properties of its constituent parts.
Lecture No. 24
Architectural design may be based upon a certain pattern of model. These different
patterns are also called architectural styles. These styles have different characteristics and
attributes and can be useful to solve problems related to a particular situation of
requirement. Among the many styles, the most commonly practiced are the following:
Data-centered architectures
Client Server Architecture and its variations
Layered architectures
Reference Architecture
In any system, sub-systems need to exchange information and data. This may be done in
two ways:
1. Shared data is held in a central database or repository and may be accessed by all sub-
systems
2. Each sub-system maintains its own database and passes data explicitly to other sub-
systems
_____________________________________________________________________126
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
When large amounts of data are to be shared, the repository model of sharing is most
commonly used. This model has been extensively used in the main-frame based
Client Client
Software Software
Client Client
Software Software
Advantages
Repository model is an efficient way to share large amounts of data. In this case
sub-systems need not be concerned with how data is produced Centralised
management e.g. backup, security, etc. This model also provides a global view of
the system and the sharing model is published as the repository schema.
Disadvantages
Client server model tries to distribute data and processing. This is a shift from main-
frame based applications where both the data management and the processing of data
used to be typically carried out by the same main-frame computer. In those applications,
the user interface used to be a provided through a “dumb” terminal which did not have
much processing power. With the availability of the cheaper but power machines, it was
possible to shift some load from the back-end computer to other smaller machines.
The client-server model is a distributed system model which shows how data and
processing is distributed across a range of components. In this model, the application is
modeled as a set of services that are provided by servers and a set of clients that use these
services. The system is organized as a set of stand-alone servers which provide specific
services such as printing, data management, etc. and a set of clients which call on these
_____________________________________________________________________127
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
services. These clients and servers are connected through a network which allows clients
to access servers. Clients and servers are logical processes (not always physical
machines). Clients know the servers but the servers do not need to know all the clients
and the mapping of processes to processors is not always 1:1.
C1 C2 Server
Client
C7 S1 S2 C3
S3 S4 C4
C6 C5
_____________________________________________________________________128
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Client-server characteristics
Advantages
The main advantage of the client-server architecture is that it makes effective
use of networked systems. Instead of building the system with very expensive
large computers and hardware devices, cheaper hardware may be used to gain
performance and scalability. In addition, adding new servers or upgrading
existing servers becomes easier. Finally, distribution of data is straightforward
in this case.
Disadvantages
The main disadvantage of this model is that there is no standard way of
sharing data, so sub-systems may use different data organisation. Hence data
interchange may be inefficient. From a management point of view, each
server needs attention and hence there is redundant management in each
server. Finally there is no central register of names and services - it may be
hard to find out what servers and services are available.
_____________________________________________________________________129
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The client-server model can have many different configurations. In the following
sections, we look at some of these configurations.
This model was initially used to migrate legacy systems to client server architectures.
In this case the legacy system may act as a server in its own right and the GUI may be
implemented on a client. It chief disadvantage is that it places a heavy processing
load on both the server and the network.
With advent of cheaper and more powerful hardware, people thought of using the
processing power of client side machines. So the fat client model came into being. In
this model, more processing is delegated to the client as the application processing is
locally extended. It is suitable for new client/server systems when the client system
capabilities are known in advance. It however is more complex than thin client model
with respect to management issues. Since the client machine now also has a
significant part of the application resident on it, new versions of each application need
to be installed on every client .
Lecture No. 259
Zero Install
As discussed earlier, fat-client architecture posed major challenges in terms of
installation and maintenance of the client side of the application, especially when
there are large number of client machines. So the idea behind zero install architecture
is to develop a system where no installation on the client side is needed. This can only
be done when there is no or little processing done at the client side. This is basically a
trade-off between using the computing power available at the client machine versus
maintenance overhead. This in essence takes us back to an architecture which is
similar to thin-client architecture. There is little difference though. In the classical
thin-client architecture, the entire processing is carried-out by a single server, in the
case of zero-install, the network environment is used to distribute server side
processing by adding a number of servers which share processing load. Web-based
application where the web-pages are put on a web-server is an example of this type of
architecture. In this case, whenever there is a change, the web page is updated
accordingly. Now when the user logs in, he gets to use the modified version of the
application without any changes or updates at the client side.
_____________________________________________________________________130
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
N-Tier architecture
N-tier architecture stems from the struggle to find a middle ground between the fat-
client architecture and the thin-client architecture. In this case the idea is to enhance
scalability and performance by distributing both the data and the application using
multiple server machines. This could involve different types of servers such as
application server, web server, and DB server. Three-tier architecture which is
explained below is a specialized form of this architecture.
Three-tier Architecture
Client
Client
N-tier architecture generalizes the concepts of 3-tier architecture. In this case the system
architecture may have more than 3 layers. That is, in n-tier architecture, in order to
increase performance, we may distribute the application over different servers by putting
different subsystems on different servers.
_____________________________________________________________________131
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This architecture is very similar to data flow diagrams. This is used when the input data is
processed through a series of transformations to yield the desired output. It is also known
as pipes and filters architecture where each processing step is called a filter and the
connecting link from one process to the other is called the pipe through which the
information flows from one process to the other. An important aspect of this model is that
each filter works independently of others and does not require knowledge of the working
of any of the other filters including its neighbours.
If the dataflow has only a single sequence of processes with no alternative or parallel
paths, then it is called batch sequential. These models are depicted in the following
diagrams.
pipes
Filter2 Filter4 Filter5
Filter1
Batch Sequential
_____________________________________________________________________132
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Layered Architecture
As the name suggests, a layered architecture has many different layers. One typical
example of a layered architecture is an operating system where different layers are used
to provide services and functionality and the inner layers are closer to the machine
hardware than the outer layers. In this way, each layer isolates the outer layer from inner
complexities. In order to work properly, the outer layer only needs to know the interface
provided by the inner layer. If there are any changes in the inner layer, as long as the
interface does not change, the outer layer is not affected. This scheme tremendously
portability of the system. The basic layered architecture is depicted in the following
diagram.
Application Layer
Utility Layer
Core Layer
_____________________________________________________________________133
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
7 Ap pl icat io n Ap pl icat io n
5 S es si on S es si on
4 Trans po rt Trans po rt
1 P hy si cal P hy si cal P hy si ca l
C o m mu ni ca t io ns m edi um
_____________________________________________________________________134
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
In the horizontal partitioning we define separate branches of the module hierarchy for
each major function and control modules are used to coordinate communication
between functions. This concept is depicted in the following diagram.
Vertical partitioning divides the application from a decision making perspective. The
architecture is partitioned in horizontal layers so that decision making and work are
stratified with the decision making modules residing at the top of the hierarchy and
worker coming at the bottom. This partitioning is also known as factoring and the
general model is depicted in the following diagram.
_____________________________________________________________________135
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Top Partition
Decision Makers
Bottom Partition
Workers
In a given system, the required characteristics may conflict. Trade-offs seek optimal
combinations of properties based on cost/benefit analysis. So the analysis requires an
understanding of what is required and the relative priority of the attributes has to be
established. The following sequence of steps provides a guideline for performing
architectural analysis.
1. Collect scenarios.
2. Elicit requirements, constraints, and environment description.
3. Describe the architectural styles/patterns that have been chosen to address the
scenarios and requirements. These views include module view, process view, and
data flow view.
4. Evaluate quality attributes by considered each attribute in isolation.
5. Identify the sensitivity of quality attributes to various architectural attributes for a
specific architectural style.
_____________________________________________________________________136
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Even though Alexander was talking about patterns in buildings and towns, what he says
is true about object-oriented design patterns. Our solutions are expressed in terms of
objects and interfaces instead of walls and doors, but the core of both kinds of patterns is
a solution to a problem in a context.
Design Patterns defined
“Description of communicating objects and classes that are customized to solve a general
design in a particular context.”
Patterns are devices that allow programs to share knowledge about their design. In our
daily programming, we encounter many problems that have occurred, and will occur
again. The question we must ask our self is how we are going to solve it this time.
Documenting patterns is one way that you can reuse and possibly share the information
that you have learned about how it is best to solve a specific program design problem.
Essay writing is usually done in a fairly well defined form, and so is documenting design
patterns. The general form for documenting patterns is to define items such as:
_____________________________________________________________________137
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The pattern movement became very quiet until 1987 when patterns appeared again at an
OOPSLA conference. Since then, many papers and presentations have appeared,
authored by people such as Grady Booch, Richard Helm, and Erich Gamma, and Kent
Beck. From then until 1995, many periodicals, featured articles directly or indirectly
relating to patterns. In 1995, Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides published Design Patterns: Elements of Reusable Object-Oriented Software
[Gamma95], which has been followed by more articles in trade journals.
The concept of design patterns is not new as we can find a number of similar pursuits in
the history of program designing and writing. For instance, Standard Template Library
(STL) is a library of reusable components provided by C++ compilers. Likewise, we use
algorithms in data structures that implement typical operations of manipulating data in
data structures. Another, similar effort was from Peter Coad whose patterns are known
for object-oriented analysis and design.
Anti-patterns is another concept that corresponds to common mistakes in analysis and
design. These are identified in order to prevent potential design and analysis defects from
entering into the design. Another, similar concept is object-oriented framework that is a
set of cooperative classes that make up reusable design of a system. Framework dictates
the architecture of the software and describes the limitations and boundaries of
architecture.
With this introduction, we now describe the format that has been adopted in GoF book
for describing various design patterns.
GOF Design Pattern Format
The basic template includes ten things as described below
Name
Works as idiom
Name has to be meaningful
Problem
A statement of the problem which describes its intent
The goals and objectives it wants to reach within the given context
Context
Preconditions under which the problem and its solutions seem to occur
Result or consequence
State or configuration after the pattern has been applied
Forces
Relevant forces and constraints and their interactions and conflicts.
motivational scenario for the pattern.
Solution
Static and dynamic relationships describing how to realize the pattern.
Instructions on how to construct the work products.
_____________________________________________________________________138
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Pictures, diagrams, prose which highlight the pattern’s structure, participants, and
collaborations.
Examples
One or more sample applications to illustrate
o a specific context
o how the pattern is applied
Resulting context
the state or configuration after the pattern has been applied
consequences (good and bad) of applying the pattern
Rationale
justification of the steps or rules in the pattern
how and why it resolves the forces to achieve the desired goals, principles, and
philosophies
how are the forces orchestrated to achieve harmony
how does the pattern actually work
Related patterns
the static and dynamic relationships between this pattern and other patterns
Known uses
to demonstrate that this is a proven solution to a recurring problem
Classifications of deerns
Creational patterns
How to create and instantiate
Abstract the instantiation process and make the system independent of its creational
process.
Class creational rules
Object creational rules
Abstract factory and factory method
Abstract the instantiation process
Make a system independent to its realization
Class Creational use inheritance to vary the instantiated classes
Object Creational delegate instantiation to an another object
Structural patterns
Deals with object’s structure
Class structural patterns concern the aggregation of classes to form the largest classes.
Object structural patterns concerns the aggregation of objects to form the largest
classes
Class Structural patterns concern the aggregation of classes to form largest structures
Object Structural pattern concern the aggregation of objects to form largest structures
Behavioral patterns
_____________________________________________________________________139
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 27
Observer Pattern
Name
Observer
Basic intent
It is intended to define a many to many relationship between objects so that when
one object changes state all its dependants are notified and updated automatically.
Dependence/publish-subscribe mechanism in programming language
o Smalltalk being the first pure Object Oriented language in which observer
pattern was used in implementing its Model View Controller (MVC)
pattern. It was a publish-subscribe mechanism in which views (GUIs)
were linked with their models (containers of information) through
controller objects. Therefore, whenever underlying data changes in the
model objects, the controller would notify the view objects to refresh
themselves and vice versa.
o MVC pattern was based on the observer pattern.
Motivation
It provides a common side effect of partitioning a system into a collection of
cooperating classes that are in the need to maintain consistency between related
objects.
Description
This can be used when multiple displays of state are needed.
Consequences
Optimizations to enhance display performance are impractical.
Example implementation of Observer PatternObject Model
_____________________________________________________________________140
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Many graphical user interface toolkits separate the presentational aspects of the user
interface from the underlying application data. Classes defining application data and
presentations can be reused independently. They can work together, too. Both a
spreadsheet object and bar chart object can depict information in the same application
data object using different presentations. The spreadsheet and the bar chart don’t know
about each other, thereby letting you reuse only the one you need. But they behave as
though they do. When the user changes the information in the spreadsheet, the bar chart
reflects the changes immediately, and vice versa.
50
D
A 25
C ABCD
B 0
Subject
A: 40
B: 25
Observer 1 C: 15 Observer 2
D: 20
Structure
Subject Observer
Attach(Observer)
Update()
Detach(Observer)
Notify() for all o in observers
o -> Update()
ConcreteSubject ConcreteObserver
observerState =
GetState() return SubjectState Update()
subject -> GetState()
SubjectState ObserverState
Participants
_____________________________________________________________________141
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Subject
Knows its observers. Any number of Observer objects may observe a subject.
Provides an interface for attaching and detaching Observer objects.
Observer
Defines an updating interface for objects that should be notified of changes in a
subject.
ConcreteSubject
Stores state of interest to concreteObserver objects.
Sends a notification to its observers when its state changes.
ConcreteObserver
Maintains a reference to a ConcreteSubject object.
Stores state state that should stay consistent with the subject’s.
Implements the Observer updating interface to keep its state consistent with the
subject’s.
Singleton Pattern
Intent
It ensures that a class only has one instance and provides a global point of access
to it.
Applicability
Singleton pattern should be used when there must be exactly one instance of a
class and it must be accessible to clients from a well-known access point.
Singleton pattern should be used when controlling the total number of instances
that would be created for a particular class.
Singleton pattern should be used when the sole instance should be extensible by
sub classing and clients should be able to use an extended instance without
modifying their code.
Structure
Singleton
static instance() return uniqueInstance
SingletonOperation()
GetSingletonData()
static uniqueInstance
singletonData
Participants
Singleton
_____________________________________________________________________142
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Defines an instance operation that lets clients access its unique instance. Instance
is a class operation (that is, a class method in Smalltalk and a static member
function in C++).
May be responsible for creating its own unique instance.
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
Singleton* Singleton::_instance = 0;
Singleton* Singleton::Instance(){
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
Clients access the singleton exclusively through the Instance member function. The
variable _instance is initialized to 0, and the static member function Instance returns its
value, initializing it with the unique instance if it is 0.
Façade Pattern
Intent
It provides a unified interface to a set of interfaces in a sub-system.
Façade defines a higher level interface that makes a subsystem easier to use
Applicability
You would use façade when you want to provide a simple interface to a complex
sub-system.
You would use façade pattern when there are many dependencies between clients
and the implementation classes of an abstraction.
You should introduce a façade to decouple the system from clients and other
subsystems.
You want to layer your subsystem.
You would use façade when you want to provide a simple interface to a complex
sub-system
_____________________________________________________________________143
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
You would use façade pattern when there are many dependencies between clients
and the implementation classes of an abstraction
You should introduce a façade to decouple the system from clients and other
subsystems
You want to layer the subsystem
Abstract example of façade
Structuring a system into subsystems helps reduce complexity. A common design goal is
to minimize the communication and dependencies between subsystems. One way to
achieve this goal is to introduce a façade object that provides a single, simplified
interface to the more general facilities of a subsystem.
client classes
Facade
subsystem classes
Structure
_____________________________________________________________________144
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Facade
Participants
Façade
Knows which subsystem classes are responsible for a request.
Delegates client requests to appropriate subsystem objects.
Subsystem classes
Implement subsystem functionality.
Handle work assigned by the Façade object.
Have no knowledge of the façade, that is, they keep no references to it.
_____________________________________________________________________145
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 28
Good Programming Practices and Guidelines
As we have discussed earlier, in most cases, maintainability is the most desirable quality
of a software artifact. Code is no exception. Good software ought to have code that is
easy to maintain. Fowler says, “Any fool can write code that computers can understand,
good programmers write code that humans can understand.” That is, it is not important
to write code that works, it is important to write code that works and is easy to understand
so that it can be maintained. The three basic principles that guide maintainability are:
simplicity, clarity, and generality or flexibility. The software will be easy to maintain if it
is easy to understand and easy to enhance. Simplicity and clarity help in making the code
easier to understand while flexibility facilitates easy enhancement to the software.
_____________________________________________________________________146
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
From a maintenance perspective, what we need is what is called self documenting code.
A self documenting code is a code that explains itself without the need of comments and
extraneous documentation, like flowcharts, UML diagrams, process-flow state diagrams,
etc. That is, the meaning of the code should be evident just by reading the code without
having to refer to information present outside this code.
There are a number of attributes that contributes towards making the program self
documented. These include, the size of each function, choice of variable and other
identifier names, style of writing expressions, structure of programming statements,
comments, modularity, and issues relating to performance and portability.
Function Size
The size of individual functions plays a significant role in making the program easy or
difficult to understand. In general, as the function becomes longer in size, it becomes
more difficult to understand. Ideally speaking, a function should not be larger than 20
lines of code and in any case should not exceed one page in length. From where did I get
this number 20 and one page? The number 20 is approximately the lines of code that fit
on a computer screen and one page of course refers to one printed page. The idea behind
these heuristics is that when one is reading a function, one should not need to go back and
forth from one screen to the other or from one page to the other and the entire context
should be present on one page or on one screen.
_____________________________________________________________________147
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Identifier Names
Identifier names also play a significant role in enhancing the readability of a program.
The names should be chosen in order to make them meaningful to the reader. In order to
understand the concept, let us look at the following statement.
In this particular case, the meanings of the condition in the if-statement are not clear and
we had to write a comment to explain it. This can be improved if, instead of using x, we
use a more meaningful name. Our new code becomes:
if (AllocFlag == 0)
The situation has improved a little bit but the semantics of the condition are still not very
clear as the meaning of 0 is not very clear. Now consider the following statement:
If (AllocFlag == NEW_NUMBER)
We have improved the quality of the code by replacing the number 0 with a named
constant NEW_NUMBER. Now, the semantics are clear and do not need any extra
comments, hence this piece of code is self-documenting.
_____________________________________________________________________148
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This coding style guide emphasizes on C++ and Java but the concepts are applicable to
other languages as well.
In our style guide, we will be using a naming convention where Hungarian Notation is
mixed with CamelCase.
_____________________________________________________________________149
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
1. Names representing types must be nouns and written in mixed case starting with
upper case.
Line, FilePrefix
_____________________________________________________________________150
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
11. Variables with a large scope should have long names, variables with a small scope
can have short names. Scratch variables used for temporary storage or indices are best
kept short. A programmer reading such variables should be able to assume that its
value is not used outside a few lines of code. Common scratch variables for integers
are i, j, k, m, n and for characters c and d.
12. The name of the object is implicit, and should be avoided in a method name.
line.getLength(); // NOT: line.getLineLength();
The latter seems natural in the class declaration, but proves superfluous in use.
_____________________________________________________________________151
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Using the is prefix solves a common problem of choosing bad boolean names like status
or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more
meaningful names.
There are a few alternatives to the is prefix that fits better in some situations. These are
has, can and should prefixes:
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
Using this term will give the reader the immediate clue that this is a potential time
consuming operation, and if used repeatedly, he might consider caching the result.
4. The term find can be used in methods where something is looked up.
vertex.findNearestVertex(); matrix.findMinElement();
This gives the reader the immediate clue that this is a simple look up method with a
minimum of computations involved.
Simply using the plural form of the base class name for a list (matrixElement (one
matrix element), matrixElements (list of matrix elements)) should be avoided since the
two only differ in a single character and are thereby difficult to distinguish.
A list in this context is the compound data type that can be traversed backwards,
forwards, etc. (typically a Vector). A plain array is simpler. The suffix Array can be used
to denote an array of objects.
_____________________________________________________________________152
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
There are two types of words to consider. First are the common words listed in a
language dictionary. These must never be abbreviated. Never write:
cmd instead of command
cp instead of copy
pt instead of point
comp instead of compute
init instead of initialize
etc.
Then there are domain specific phrases that are more naturally known through their
acronym or abbreviations. These phrases should be kept abbreviated. Never write:
HypertextMarkupLanguage instead of html
CentralProcessingUnit instead of cpu
PriceEarningRatio instead of pe
etc.
_____________________________________________________________________153
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The problem arise when the logical NOT operator is used and double negative arises. It is
not immediately apparent what !isNotError means.
13. Functions (methods returning an object) should be named after what they return and
procedures (void methods) after what they do. This increases readability. Makes it clear
what the unit should do and especially all the things it is not supposed to do. This again
makes it easier to keep the code clean of side effects. Naming pointers in C++
specifically should be clear and should represent the pointer type distinctly.
Line *line //NOT Line *pLine; or Line *lineptr; etc
_____________________________________________________________________154
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
1. C++ header files should have the extension .h. Source files can have the extension
.c++ (recommended), .C, .cc or .cpp.
MyClass.c++, MyClass.h
2. Classes should be declared in individual header files with the file name matching the
class name. Secondary private classes can be declared as inner classes and reside in the
file of the class they belong to. All definitions should reside in source files.
class MyClass
{
public:
int getValue () {return value_;} // NO!
...
private:
int value_;
}
The header files should declare an interface, the source file should implement it. When
looking for an implementation, the programmer should always know that it is found in
the source file. The obvious exception to this rule is of course inline functions that must
be defined in the header file.
3. Special characters like TAB and page break must be avoided. These characters are
bound to cause problem for editors, printers, terminal emulators or debuggers when used
in a multi-programmer, multi-platform environment.
Split lines occurs when a statement exceed the 80 column limit given above. It is difficult
to give rigid rules for how lines should be split, but the examples above should give a
general hint. In general:
Break after a comma.
Break after an operator.
Align the new line with the beginning of the expression on the previous line.
_____________________________________________________________________155
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________156
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The construction is to avoid compilation errors. The construction should appear in the top
of the file (before the file header) so file parsing is aborted immediately and compilation
time is reduced.
_____________________________________________________________________157
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Types
1. Type conversions must always be done explicitly. Never rely on implicit type
conversion.
By this, the programmer indicates that he is aware of the different types involved and that
the mix is intentional.
2. Types that are local to one file only can be declared inside that file.
3. The parts of a class must be sorted public, protected and private. All sections must be
identified explicitly. Not applicable sections should be left out. The ordering is "most
public first" so people who only wish to use the class can stop reading when they
reach the protected/private sections.
Variables
1. Variables should be initialized where they are declared and they should be declared in
the smallest scope possible.
2. Variables must never have dual meaning. This enhances readability by ensuring all
concepts are represented uniquely. Reduce chance of error by side effects.
3. Class variables should never be declared public. The concept of information hiding
and encapsulation is violated by public variables. Use private variables and access
functions instead. One exception to this rule is when the class is essentially a data
structure, with no behavior (equivalent to a C++ struct). In this case it is appropriate
to make the class' instance variables public.
The common requirement of having declarations on separate lines is not useful in the
situations like the ones above. It enhances readability to group variables.
5. Variables should be kept alive for as short a time as possible. Keeping the operations
on a variable within a small scope, it is easier to control the effects and side effects of
the variable.
_____________________________________________________________________158
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
6. Global variables should not be used. Variables should be declared only within scope
of their use. Same is recommended for global functions or file scope variables. It is
easier to control the effects and side effects of the variables if used in limited scope.
7. Implicit test for 0 should not be used other than for boolean variables and pointers.
if (nLines != 0) // NOT: if (nLines)
if (value != 0.0) // NOT: if (value)
It is not necessarily defined by the compiler that ints and floats 0 are implemented as
binary 0. Also, by using explicit test the statement give immediate clue of the type being
tested. It is common also to suggest that pointers shouldn't test implicit for 0 either, i.e. if
(line == 0) instead of if (line). The latter is regarded as such a common practice in
C/C++ however that it can be used.
Loop structures
3. The use of do .... while loops should be avoided. There are two reasons for this. First
is that the construct is superflous; Any statement that can be written as a do .... while
loop can equally well be written as a while lopp or a for loop. Complexity is reduced
by minimizing the number of constructs being used. The other reason is of
readability. A loop with the conditional part at the end is more difficult to read than
one with the conditional at the top.
4. The use of break and continue in loops should be avoided. These statements should
only be used if they prove to give higher readability than their structured counterparts.
In general break should only be used in case statements and continue should be
avoided alltogether.
_____________________________________________________________________159
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This form is better than the functionally equivalent while (true) since this implies a test
against true, which is neither necessary nor meaningful. The form while(true) should be
used for infinite loops.
Conditionals
2. The nominal case should be put in the if-part and the exception in the else-part of an
if statement.
boolean isError = readFile (fileName);
if (!isError) {
:
}
else {
:
}
_____________________________________________________________________160
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Miscellaneous
1. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1
should be considered declared as named constants instead.
2. Floating point constants should always be written with decimal point and at least one
decimal.
double total = 0.0; // NOT: double total = 0;
double speed = 3.0e8; // NOT: double speed = 3e8;
double sum;
:
sum = (a + b) * 10.0;
This emphasizes the different nature of integer and floating point numbers even if their
values might happen to be the same in a specific case. Also, as in the last example above,
it emphasize the type of the assigned variable (sum) at a point in the code where this
might not be evident.
3. Floating point constants should always be written with a digit before the decimal
point.
double total = 0.5; // NOT: double total = .5;
The number and expression system in Java is borrowed from mathematics and one should
adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more
readable than .5; There is no way it can be mixed with the integer 5.
4. Functions in C++ must always have the return value explicitly listed.
int getValue() // NOT: getValue()
{
:
}
If not explicitly listed, C++ implies int return value for functions.
5. goto in C++ should not be used. Goto statements violates the idea of structured code.
Only in some very few cases (for instance breaking out of deeply nested structures)
should goto be considered, and only if the alternative structured counterpart is proven
to be less readable .
_____________________________________________________________________161
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The problem with comments is that they lie. Comments are not syntax checked, there is
nothing forcing them to be accurate. And so, as the code undergoes change during
schedule crunches, the comments become less and less accurate.
As Fowler puts it, comments should not be used as deodorants. Tricky code should not be
commented but rewritten. In general, the use of comments should be minimized by
making the code self-documenting by appropriate name choices and an explicit logical
structure.
If, however, there is a need to write comments for whatever reason, the following
guidelines should be observed.
Since multilevel commenting is not supported in C++ and Java, using // comments ensure
that it is always possible to comment out entire sections of a file using /* */ for
debugging purposes etc.
_____________________________________________________________________162
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Indentation of 1 is to small to emphasize the logical layout of the code. Indentation larger
than 4 makes deeply nested code difficult to read and increase the chance that the lines
must be split. Choosing between indentation of 2, 3 and 4, 2 and 4 are the more common,
and 2 chosen to reduce the chance of splitting code lines.
Expression should be written as if they are written as comments or spoken out aloud.
Conditional expression with negation are always difficult to understand. As an example
consider the following code:
The logic becomes much easier to follow if the code is written in the natural form as
shown below:
Parentheses should always be used as they reduce complexity and clarify things by
specifying grouping. It is especially important to use parentheses when different
unrelated operators are used in the same expression as the precedence rules are often
assumed by the programmers, resulting in logical errors that are very difficult to spot. As
an example consider the following statement:
This causes problems because == operator has higher precedence than & operator.
Hence, MASK and BITS are first compared for equality and then the result, which is 0 or
1, is andded with x. This kind of error will be extremely hard to catch. If, however,
parentheses are used, there will be no ambiguity as shown below.
_____________________________________________________________________163
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Following is another example of the use of parentheses which makes the code easier to
understand and hence easier to maintain.
In this case parentheses have not been used and therefore the definition of a leap year is
not very clear for the code. The code becomes self explanatory with the help of proper
use of parentheses as shown below:
leapYear = ((year % 4 == 0) && (year % 100 != 0)) ||
(year % 400 == 0);
This statement liberally uses a number of operators and hence is very difficult to follow
and understand. If it is broken down into simple set of statements, the logic becomes
easier to follow as shown below:
Sometimes the programmers, in their creative excitement, try to write very concise code
by using shortcuts and playing certain kinds of tricks. This results in a code which is
cryptic in nature and hence is difficult to follow. Maintenance of such code therefore
becomes a nightmare. Following are some examples of such code.
1. Let us start with a very simple shortcut, often used by programmers. Assume that we
have the following statement.
x *= a;
_____________________________________________________________________164
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
x *= a + b;
This seemingly harmless change is actually a little cryptic and causes confusion. The
problem lies with the semantics of this statement. Does it mean x = x*a+b or x=
x*(a+b)? The second one is the right answer but is not obvious from the syntax and
hence causes problems.
2. Let us now look at a more complex example. What is the following code doing?
As can be seen, it is pretty hard to understand and therefore difficult to debug in case
there is any problem. What this code is actually doing is masking bitoff with octal 7
and then use the result to shift subkey those many time. This can be written as
follows:
It is quite evident that the second piece of code is much follow to read than the first
one.
a = a >> 2;
It is easy to see that a is shifted right two times. However, the real semantics of this
code are hidden – the real intent here is to divide a by 4. No doubt that the code above
achieves this objective but it is hard for the reader to understand the intent as to why a
is being shifted right twice. It would have been much better had the code been written
as follows:
a = a/4;
4. A piece of code similar to the following can be found in many data structures books
and is part of circular implementation of queues using arrays.
bool Queue::add(int n)
{
int k = (rear+1) % MAX_SIZE;
if (front == k)
return false;
else {
rear = k;
queue[rear] = n;
return true;
}
}
_____________________________________________________________________165
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
bool Queue::isFull()
{
if (front == (rear+1 % MAX_SIZE))
return true;
else
return false;
}
This code uses the % operator to set the rear pointer to 0 once it has reached
MAX_SIZE. This is not obvious immediately. Similarly, the check for queue full is
also not trivial.
It is always much better to state the logic explicitly. Also, counting is also much
easier to understand and code as compared to some tricky comparisons (e.g. check for
isFull in this case). Application of both these principles resulted in the following
code. It is easy to see that this code is easier to understand. It is interesting to note that
when another group of students were asked to do implement double-ended queue
after showing them this code, almost everyone did it without any problems.
bool Queue::add()
{
if (! isFull() ) {
rear++;
if (rear == MAX_SIZE) rear = 0;
QueueArray[rear] = n;
size++;
return true;
}
else return false;
}
bool Queue::isFull(int n)
{
if (size == MAX_SIZE)
return true;
else
return false;
}
_____________________________________________________________________166
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Switch Statement
In the switch statement, cases should always end with a break. A tricky sequence of fall-
through code like the one below causes more trouble than being helpful.
switch(c) {
case ‘-’ : sign = -1;
case ‘+’ : c = getchar();
case ‘.’ : break;
default : if (! isdigit(c))
return 0;
}
This code is cryptic and difficult to read. It is much better to explicitly write what is
happening, even at the cost of duplication.
switch(c) {
case ‘-’: sign = -1;
c = getchar();
break;
case ‘+’: c = getchar();
break;
case ‘.’: break;
default: if (! isdigit(c))
return 0;
break;
}
It would even be better if such code is written using the if statement as shown below.
if (c == ‘-’) {
sign = -1;
c = getchar();
}
else if (c == ‘+’) {
c = getchar();
}
else if (c != ‘.’ && !isdigit(c)) {
return 0;
}
_____________________________________________________________________167
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Magic Numbers
Can you tell by reading the code what is meant by the numbers 20, 27, 3, 21, 22, and 23.
These are constant that mean something but they do not give any indication of their
importance or derivation, making the program hard to understand and modify. To a
reader they work like magic and hence are called magic numbers. Any number (even 0 or
1) used in the code is a magic number. It should rather have a name of its own that can be
used in the program instead of the number.
The difference would be evident if we look at the code segment below that achieves the
same purpose as the code above.
enum {
MINROW = 1,
MINCOL = 1,
MAXROW = 24,
MAXCOL = 80,
LABELROW = 1,
NLET = 26,
HEIGHT = MAXROW –4,
WIDTH = (MAXCOL-1) / NLET
};
_____________________________________________________________________168
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This is a legacy of old style C programming. It is much better to use symbols to explicitly
indicate the intent of the statement. It is easy to see that the following code is more in line
with the self-documentation philosophy than the code above.
flag = false;
str = NULL;
name[i] = ‘\0’;
x = 0.0;
i = 0;
_____________________________________________________________________169
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
As mentioned earlier, abstraction and encapsulation are two important tools that can help
in managing and mastering the complexity of a program. We also discussed that the size
of individual functions plays a significant role in making the program easy or difficult to
understand. In general, as the function becomes longer in size, it becomes more difficult
to understand. Modularity is a tool that can help us in reducing the size of individual
functions, making them more readable. As an example, consider the following selection
sort function.
Although it is not very long but we can still improve its readability by breaking it into
small functions to perform the logical steps. The modified code is written below:
_____________________________________________________________________170
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
It is easy to see that the new selectionSort function is much more readable. The logical
steps have been abstracted out into the two functions namely, minimum and swap. This
code is not only shorter but also as a by product we now have two functions (minimum
and swap) that can be reused.
Reusability is one of the prime reasons to make functions but is not the only reason.
Modularity is of equal concern (if not more) and a function should be broken into smaller
pieces, even if those pieces are not reused. As an example, let us consider the quickSort
algorithm below.
_____________________________________________________________________171
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
This is actually a very simple algorithm but students find it very difficult to remember. If
is broken in logical steps as shown below, it becomes trivial.
_____________________________________________________________________172
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Short-circuiting is a very useful tool. It can be used where one boolean expression can be
placed first to “guard” a potentially unsafe operation in a second boolean expression.
Also, time is saved in evaluation of complex expressions using operators || and &&.
However, a number of issues arise if proper attention is not paid.
Let us look at the following code segment taken from a commercially developed software
for a large international bank:
struct Node {
int data;
Node * next;
};
Node *ptr;
...
The second part of condition, ptr != NULL, is supposed to be the guard. That is, if the
value of the pointer is NULL, then the control should not enter the body of the while loop
otherwise, it should check whether ptr->data < myData or not and then proceed
accordingly. When the guard is misplaced, if the pointer is NULL then the program will
crash because it is illegal to access a component of a non-existent object. This code is
rewritten as follows. This time the short-circuiting helps in achieving the desired
objective which would have been a little difficult to code without such help.
while (ptr != NULL && ptr->data < myData){
// do something here
}
_____________________________________________________________________173
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
A side effect of a function occurs when the function, besides returning a value, changes
either one of its parameters or a variable declared outside the function but is accessible to
it. That is, a side effect is caused by an operation that may return an explicit result but it
may also modify the values stored in other data objects. Side effects are a major source of
programming errors and they make things difficult during maintenance or debugging
activities. Many languages do not specify the function evaluation order in a single
statement. This combined with side effects causes major problems. As an example,
consider the following statement:
c = f1(a) + f2(b);
The question is, which function (f1 or f2) will be evaluated first as the C/C++ language
does not specify the evaluation order and the implementer (compiler writer) is free to
choose one order or the other. The question is: does it matter?
In this case both f1 and f2 have side effects as they both are doing two things - changing
the value of the parameter and changing the value at the caller side. Now if we have the
following code segment,
a = 3;
b = 4;
c = f1(a) + f2(b);
a=6
b=2
c=8
_____________________________________________________________________174
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
So far there seem to be any problem. But let us now consider the following statement:
c = f1(a) + f2(a);
a=3
b = 9 // 7 + 2
On the other hand, if f2 is evaluated before f2 then, we get totally different results.
a=2
b = 3 // 3 + 0
_____________________________________________________________________175
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
int i, j = 0;
Because of the syntax, many people would assume that i is also being initialized
to 0, while it is not. Combination of , and = -- is fatal. Look at the following
statement:
a = b, c = 0;
A majority of the programmers would assume that all a, b, and c are being
initialized to 0 while only c is initialized and a and b have garbage values in them.
This kind of overlook causes major programming errors which are not caught
easily and are caused only because there are side effects.
Guidelines
If the following guidelines are observed, one can avoid hazards caused by side effects.
_____________________________________________________________________176
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
10.12 Performance
In many cases, performance and maintainability are at odds with one another. When
planning for performance, one should always remember the 80/20 rule - you spend 80
percent of your time in 20 percent of the code. That is, we should not try to optimize
everything. The proper approach is to profile the program and then identify bottlenecks to
be optimized. This is similar to what we do in databases – we usually normalize the
database to remove redundancies but then partially de-normalize if there are performance
issues.
The profiling revealed that most of time was spent in strchr and strncmp and both of these
were called from strstr.
When a small set (a couple of functions) of functions which use each other is so
overwhelmingly the bottleneck, there are two alternatives:
In this particular case strstr was rewritten and profiled again. It was and found out that
although it was much faster but now 99.8% of the time was spent in strstr.
The algorithm was rewritten and restructured again by eliminating strstr, strchr, and
strncmp and used memcmp. Now memcmp was much more complex than strstr but it
gained efficiency by eliminating a number of loops and the new results are as shown:
_____________________________________________________________________177
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Many details of the execution can be discovered by examining the numbers. The trick is
to concentrate on hot spots by first identifying them and then cooling them. As mentioned
earlier, most of the time is spent in loops. Therefore we need to concentrate on loops.
This loop clears field before each new input is read. It was observed that it was taking
almost 50% of the total time. On further investigation it was found out that MAX_FIELD
was 200 but the actual fields that needed to be cleared were 2 or 3 in most cases. The
code was subsequently modified as shown below:
_____________________________________________________________________178
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Although C++ standard does not require function prototypes, one should always write
them.
Sizes of data types cause major portability issues as they vary from one machine to the
other so one should be careful with them.
int i, j, k;
…
j = 20000;
k = 30000;
i = j + k;
_____________________________________________________________________179
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________180
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Order of Evaluation
As mentioned earlier during the discussion of side effects, order of evaluation varies from
one implementation to other. This therefore also causes portability issues. We should
therefore follow guidelines mentioned in the side effect discussion.
Signedness of char
char c;
// between 0 and 255 if unsigned
// -128 to 127 if signed
c = getchar();
if (c == EOF) ??
The C/C++ language has not specified whether right shift >> is arithmetic or logical. In
the arithmetic shift sign bit is copied while the logical shift fills the vacated bits with 0.
This obviously reduces portability.
Interestingly, Java has introduced a new operator to handle this issue. >> is used for for
arithmetic shift and >>> for logical shift.
The order in which bytes of one word are stored is hardware dependent. For example in
Intel architecture the lowest byte is the most significant byte while in Motorola
architecture the highest byte of a word is the most significant one. This causes problem
when dealing with binary data and we need to be careful while exchanging data between
to heterogeneous machines. One should therefore only use text for data exchange. One
should also be aware of the internationalization issues and hence should not assume
ASCII as well as English.
_____________________________________________________________________181
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Alignment
The C/C++ language does not define the alignment of items within structures, classes, an
unions. data may be aligned on word or byte boundaries. For example:
struct X {
char c;
int i;
};
_____________________________________________________________________182
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Bit Fields
Bit fields allow the packing of data in a structure. This is especially useful when memory
or data storage is at a premium. Typical examples:
Packing several objects into a machine word. e.g. 1 bit flags can be compacted --
Symbol tables in compilers.
Reading external file formats -- non-standard file formats could be read in. E.g. 9
bit integers.
C lets us do this in a structure definition by putting :bit length after the variable. i.e.
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int funny_int:9;
} pack;
Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit
type and a 9 bit funny_int.
C automatically packs the above bit fields as compactly as possible, provided that the
maximum length of the field is less than or equal to the integer word length of the
computer. If this is not the case then some compilers may allow memory overlap for the
fields whilst other would store the next field in the next word.
Bit fields are a convenient way to express many difficult operations. However, bit fields
do suffer from a lack of portability between platforms:
_____________________________________________________________________183
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The idea is to raise some error flag every time something goes wrong. There is a system
that is always on the lookout for this error flag. Third, the previous system calls the error
handling code if the error flag has been spotted. The raising of the imaginary error flag is
simply called raising or throwing an error. When an error is thrown the overall system
responds by catching the error. Surrounding a block of error-sensitive code with
exception handling is called trying to execute a block. The following code segment
illustrates the general exception handling mechanism.
try {
___...
___...
___throw Exception()
___...
___...
} catch( Exception e )
{
___...
___...
}
One of the most powerful features of exception handling is that an error can be thrown
over function boundaries. This allows programmers to put the error handling code in one
place, such as the main-function of your program.
_____________________________________________________________________184
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________185
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The argument is passed by value, which invokes the copy constructor. This copy
e.Title() might itself throw, or it might return an object of class type by value, and
Same as above.
To match a valid ==() operator, the string literal may need to be converted to a
temporary object of class type and that construction of the temporary might throw.
Same as above.
Same as above.
_____________________________________________________________________186
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Same as above.
9-13 cout << e.First() << “ “ << e.Last() << “ is overpaid” << endl;
As per C++ standard, any of the five calls to << operator might throw.
14-15 cout << e.First() << “ “ << e.Last() << “ is overpaid” << endl
similar to 2 and 3.
similar to 14-15.
similar to 4.
Summary:
_____________________________________________________________________187
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The Challenge:
Can we make this code exception safe and exception neutral? That is, rewrite it (if
needed) so that it works properly in the presence of an exception and propagates all
exceptions to the caller?
Exception-Safety:
A function is exception safe if it might throw but do not have any side effects if it does
throw and any objects being used, including temporaries, are exception safe and clean-up
there resources when destroyed.
Exception Neutral:
A function is said to be exception neutral if it propagates all exceptions to the caller.
As far as the second side-effect is concerned, the function meets the strong
guarantee because if an exception occurs the value will never be returned.
As far as the first side-effect is concerned, the function is not exception safe for
two reasons:
if exception is thrown after the first part of the message has been emitted
to cout but before the message has been completed (for example if the
fourth << operator throws), then a partial message was emitted to cout.
If the message emitted successfully but an exception occurs in later in the
function (for example during the assembly of the return value), then a
_____________________________________________________________________188
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
message was emitted to cout even though the function failed because of an
exception. It should be complete commit or complete roll-back.
Strong Guarantee
To meet strong guarantee, either both side-effects are completed or an exception is
// First attempt:
}
return result;
}
String theName;
theName = evaluateSalarayAndReturnName(someEmplyee);
_____________________________________________________________________189
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Can we do better and perhaps avoid the problem by avoiding the copy?
// Second attempt:
}
r = result;
}
Looks better but assignment to r might still fail which leaves us with one side-effect
completed and other incomplete.
// Third attempt:
}
return result;(); // rely on transfer of ownership
// this can’t throw
}
We have effectively hidden all the work to construct the second side-effect (the return
value), while we ensured that it can be safely returned to the caller using only non-
throwing operation after the first side-effect has completed the printing of the
message. In this case we know that once the function is complete, the return value
will make successfully into the hands of the caller and be correctly cleaned-up in all
cases. This is because the aut_ptr semantics guarantee that If the caller accepts the
returned value, the act of accepting a copy of the auto_ptr causes the caller to take the
ownership and if the caller does not accept the returned value, say by ignoring the
_____________________________________________________________________190
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
return value, the allocated string will automatically be destroyed with proper clean-
up.
When such a situation comes with two or more unrelated side-effects which cannot be
combined then the best way to handle such a situation is break it into two separate
functions. That way, at least, the caller would know that these are two separate atomic
steps.
Summary
1. Providing the strong exception-safety guarantee often requires you to trade-off
performance.
2. If a function has multiple un-related side-effects, it cannot always be made
strongly exception safe. If not, it can be done only by splitting the function
into several functions, each of whose side-effects can be performed
atomically.
3. Not all functions need to be strongly exception-safe. Both the original code
and attempt#1 satisfy the basic guarantee. For many clients, attempt # 1 is
sufficient and minimizes the opportunity for side-effects to occur in the
exceptional situation, without requiring the performance trade-off of attempt
#3.
_____________________________________________________________________191
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________192
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
is the process of executing software product on test data and examining its output vis-à-
vis the documented behavior.
Software testing objective
The correct approach to testing a scientific theory is not to try to verify it, but to
seek to refute the theory. That is to prove that it has errors. (Popper 1965)
The goal of testing is to expose latent defects in a software system before it is put
to use.
A software tester tries to break the system. The objective is to show the presence
of a defect not the absence of it.
Testing cannot show the absence of a defect. It only increases your confidence in
the software.
This is because exhaustive testing of software is not possible – it is simply too
expansive and needs virtually infinite resources.
Successful Test
From the following sayings, a successful test can be defined
“If you think your task is to find problems then you will look harder for them than if you
think your task is to verify that the program has none” – Myers 1979.
The success of a test depends upon the ability to discover a bug not in the ability to prove
that the software does not have one. As, it is impossible to check all the different
scenarios of a software application, however, we can apply techniques that can discover
potential bugs from the application. Thus a test that helps in discovering a bug is a
successful test. In software testing phase, our emphasis is on discovering all the major
bugs that can be identified by running certain test scenarios. However it is important to
keep in mind that testing activity has certain limitations.
Limitations of testing
With the help of the following example, we shall see how difficult it may become to
discover a defect from a software application.
Example (adapted from Backhouse)
This is a function that compares two strings of characters stored in an array for equality.
The tester who has to test this function has devised the following test cases in which
different combinations of inputs are tried and their expected behavior is documented.
From the look of this table, it seems that almost all major combinations of inputs have
been documented.
Inputs and Expected Outputs
A b Expected result
“cat” “dog” False
“” “” True
“hen” “hen” True
“hen” “heN” False
“” “” False
_____________________________________________________________________193
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
“” “ball” False
“cat” “” False
“HEN” “hen” False
“rat” “door” False
“ ” “ ” True
Results of testing
The tester runs all the above-mentioned test cases and function returns the same results as
expected. But it is still not correct. What can be a problem To analyze the problem, lets
look at the code of this string equal routine
Code of the Function
bool isStringsEqual(char a[], char b[])
{
bool result;
if (strlen(a) != strlen(b))
result = false;
else {
for (int i =0; i < strlen(a); i++)
if (a[i] == b[i])
result = true;
else result = false;
}
return result;
}
Analysis of the code
It passes all the designated tests but fails for two different strings of same length
ending with the same character. For example, “cut” and “rat” would results in true
which is not correct.
The above-mentioned defect signifies a clear limitation of the testing process in
discovering a defect which is not very frequent. However, it should be noted from this
example that a tester cannot generate all possible combinations of test cases to test
an application as the number of scenarios may become exhaustive.
Testing limitations
In order to prove that a formula or hypothesis is incorrect all you have to do to
show only one example in which you prove that the formula or theorem is not
working.
On the other hand, million of examples can be developed to support the
hypothesis but this will not prove that it is correct.
These examples only help you in coming up with a hypothesis but they are not
proves by themselves and they only enhance your comfort level in that particular
hypothesis or in this particular case, in your piece of software.
You cannot test a program completely because:
o the domain of the possible inputs is too large to test.
o there are too many possible paths through the program to test.
According to Discrete Mathematics
_____________________________________________________________________194
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________195
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
FS
Analysis,
Test Planning, Analysis,
Test Case and Design,
Activities Test Data
Preparation
Coding Activities
carried out carried out
by the testing by the
team Test Case development
Execution and
Defect Bug Fixing team
Reporting
Description
Functional specification document is the starting point, base document for both
testing and the development
Right side boxes describe the development, whereas, left side boxes explain the
testing process
Development team is involved into the analysis, design and coding activities.
Whereas, testing team too is busy in analysis of requirements, for test planning,
test cases and test data generation.
System comes into testing after development is completed.
Test cases are executed with test data and actual results (application behavior) are
compared with the expected results,
Upon discovering defects, tester generates the bug report and sends it to the
development team for fixing.
Development team runs the scenario as described in the bug report and try to
reproduce the defect.
If the defect is reproduced in the development environment, the development
team identifies the root cause, fixes it and sends the patch to the testing team
along with a bug resolution report.
Testing team incorporates the fix (checking in), runs the same test case/scenario
again and verifies the fix.
If problem does not appear again testing team closes down the defect, otherwise,
it is reported again.
11.5 The Developer and Tester
Development Testing
Development is a creative activity Testing is a destructive activity
Objective of development is to show that Objective of testing is to show that the
the program works program does not work
_____________________________________________________________________196
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________197
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________198
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
When should I say that further testing is unlikely to discover another error?
Testing types
To answer these questions, we divide a problem domain in different classes. These are
called Equivalence Classes.
Lecture No. 38
Equivalence Classes or Equivalence Partitioning
Two tests are considered to be equivalent if it is believed that:
if one discovers a defect, the other probably will too, and
if one does not discover a defect, the other probably won’t either.
Equivalence classes help you in designing test cases to test the system effectively and
efficiently. One should have reasons to believe that the test cases are equivalent. As for
this purpose, one would need to understand the system and see in how many partitions it
can be divided. These partitions should be devised such that a clear distinction should be
marked. Test cases written for one partition should not yield the same results when run
for the second partition as otherwise these two partitions should become one. However,
finding equivalence classes is a subjective process, as two people analyzing a program
_____________________________________________________________________199
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
If
Second structural form is the If statement. In the following graph, the first node at the left
depicts the if statement and the two nodes next to the first node correspond to the
successful case (if condition is true) and unsuccessful case (if condition is false)
consecutively. The control comes to the same instruction from either of these
intermediate instructions.
_____________________________________________________________________200
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Case
In Case statement, control can take either of several branches (as opposed to only two in
If statement.) First node represents the switch statement (C/C++) and nodes in middle
correspond to all different cases. Program can take one branch and result into the same
instruction.
While
A while loop structure consists of a loop guard instruction through which the iteration in
the loop is controlled. The control keeps iterating in the loop as long as the loop guard
condition is true. It branches to the last instruction when it becomes false.
_____________________________________________________________________201
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
sorted = false; 6 1
while (!sorted) { //1
sorted = true; 2
for (i=0; i < N-1; i++) { //2
if a[i] > a[i+1] {
3
swap(a[i], a[i+1]); //3
sorted = false;
} //4 4
} //5
} //6 5
Paths
Following are possible paths from starting to the end of this code.
Path1: 1-6
Path2: 1-2-3-4-5-1-6
Path3: 1-2-4-5-1-6
Path4: 1-2-4-2-3-4-5-6-1
Lecture No. 39
White box testing
As described in the section above, in white box testing we test the structure of the
program. In this technique the test cases are written in a manner to cover different
possibilities in code. Below are described three coverage schemes.
Coverage
Statement Coverage: In this scheme, statements of the code are tested for a
successful test that checks all the statements lying on the path of a successful
scenario.
Branch Coverage: In this scheme, all the possible branches of decision structures
are tested. Therefore, sequences of statements following a decision are tested.
Path Coverage: In path coverage, all possible paths of a program from input
instruction to the output instruction are tested. An exhaustive list of test cases is
generated and tested against the code.
_____________________________________________________________________202
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
if (a = = b) //1 1
c = d; //2
2
a++; //3
3
Statement coverage:
a=1,b=1
If a==b then statement 2, statement 3
Branch coverage
Statement 1: two braches 1-2, 1-3
Test case 1: if a =1, b=1 then statement 2
Test case 2: if a=1,b=2: then statement 3
Path coverage
Same as branch testing
Paths in a program containing loops
Now we shall apply the path coverage scheme on a piece of code that contains a loop
statement and see how many test cases can possibly be developed.
for (i = 0; i < N; i++) { //1 1
if (condition1)
// do something here //2
else 2 3
// do something here //3
// something here //4 4
}
//5 5
Paths
The following is an analysis of the above-mentioned code and the flow diagram. It
determines the number of paths against different iterations of the loop.
N = 0: If the control does not enter into the loop then only one path will be
traversed. It is 1-5.
N=1: Two different paths can possibly be traversed (depending on condition).
o 1-2-4-1-5
o 1-3-4-1-5
N=2: Four possible paths can be traversed.
o 1-2-4-1-2-4-1-5
o 1-2-4-1-3-4-1-5
_____________________________________________________________________203
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
o 1-3-4-1-2-4-1-5
o 1-3-4-1-3-4-1-5
Generalizing the relation between loop variable N and the number of possible
paths, for the value of N, 2N paths are possible
o Thus if N = 20 it means more then 1 million paths are possible.
Flow graph of a hypothetical program
Following is a flow graph of a hypothetical program whose structure is such that it
consists of two loops, one embedded in the other. Left side of the diagram signifies the
loops where inner loop seem to be containing two if statements. Second loop has a branch
and then program finishes.
Simple graph contains 1852 paths with each loop not iterated more than twice
Thus, the number of paths in a program that contains loops tends to infinity. It is
impossible to conduct exhaustive testing of a program that may consist of infinite number
of test cases. The question arises, how many test cases need to be executed in order to test
all the major scenarios in the code at least once? The answer is, calculate the cyclomatic
_____________________________________________________________________204
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
complexity of the code. This will give us a number that corresponds to the total number
of test cases that need to be generated in order to test all the statements and branches in
the code at least once.
Cyclomatic complexity
The concept of cyclomatic complexity is extremely useful in white box testing when
analyzing the relative complexity of the program to be tested. It revolves around
independent paths in a program which is any path through the program (from start to end)
that introduces at least one new set of processing statements or a new condition. An
independent path covers statements and branches of the code.
Cyclomatic complexity is a quantitative measure of the logical complexity of a program.
It defines number of independent paths in the basis set of a program. It provides an upper
bound for the number of tests that must be conducted to ensure that all statements and
branches have been executed at least once.
} //5
} //6 5
Cyclomatic complexity
Number of edges = 8
Number of nodes = 6
C(G) = 8-6+2 = 4
Paths to be tested
Path1: 1-6
_____________________________________________________________________205
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Path2: 1-2-3-4-5-1-6
Path3: 1-2-4-5-1-6
Path4: 1-2-4-2-3-4-5-6-1
Infeasible paths
Infeasible path is a path through a program which is never traversed for any input data.
Example
1
if (a == b) //1 2
c = c-1; //2
if (a != b) //3 3
c = c+1; //4
//5 4
In the above-mentioned example, there are two infeasible paths that will never be
traversed.
Path1: 1-2-3-4-5
Path2: 1-3-5
A good programming practice is such that minimize infeasible paths to zero. It will
reduce the number of test cases that need to be generated in order to test the application.
How can we minimize infeasible paths, by simply using else part with the if statement
and avoid program statements as given above.
Modified code segment
Infeasible paths can be analyzed and fixed.
1
if (a == b) //1
c = c-1; //2
else 2 3
c = c+1; //3
//4
4
There are no infeasible paths now !
_____________________________________________________________________206
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 40
11.11 Unit testing
A software program is made up of units that include procedures, functions, classes etc.
The unit testing process involves the developer in testing of these units. Unit testing is
roughly equivalent to chip-level testing for hardware in which each chip is tested
thoroughly after manufacturing. Similarly, unit testing is done to each module, in
isolation, to verify its behaviour. Typically the unit test will establish some sort of
artificial environment and then invoke routines in the module being tested. It then checks
the results returned against either some known value or against the results from previous
runs of the same test (regression testing). When the modules are assembled we can use
the same tests to test the system as a whole.
Software should be tested more like hardware, with
Built-in self testing: such that each unit can be tested independently
Internal diagnostics: diagnostics for program units should be defined.
Test harness
The emphasis is on built in testability of the program units from the very beginning
where each piece should be tested thoroughly before trying to wire them together.
Unit Testing Principles
In unit testing, developers test their own code units (modules, classes, etc.) during
implementation.
Normal and boundary inputs against expected results are tested.
Thus unit testing is a great way to test an API.
Quantitative Benefits
Repeatable: Unit test cases can be repeated to verify that no unintended side
effects have occurred due to some modification in the code.
Bounded: Narrow focus simplifies finding and fixing defects.
Cheaper: Find and fix defects early
Qualitative Benefits
Assessment-oriented: Writing the unit test forces us to deal with design issues -
cohesion, coupling.
Confidence-building: We know what works at an early stage. Also easier to
change when it’s easy to retest.
Testing against the contract (Example)
When we write unit tests we want to write test cases that ensure a given unit honors its
contract. This will tell us whether the code meets the contract and whether the contract
means what we think the unit is supposed to do in the program.
Contract for square root routine
result = squareRoot(argument);
assert (abs (result * result – argument) < epsilon);
_____________________________________________________________________207
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Design Inspection
Code Inspection
Quality Assurance
Testing
Worst 30% 37% 50% 55% 65% 75% 77% 85% 95%
Median 40% 53% 65% 70% 80% 87% 90% 97% 99%
Best 50% 60% 75% 80% 87% 93% 95% 99% 99.9%
The above table depicts data that was published after analyzing 1500 projects. In these
projects, four different types of quality assurance mechanisms were employed. It is
evident from this table that testing alone can only remove 53% of defects. However,
testing and quality assurance mechanisms combine yield up to 65% efficiency. Whereas,
if we combine code inspection and testing together, results are up to 75%. Similarly,
design inspections and testing yield up to 80%. Moreover, combining design inspections,
quality assurance and testing results are up to 95%. If all four techniques are combined,
results are up to 99.9%.
_____________________________________________________________________208
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Defect
Requirement Design Coding Origination
Documentatio Testing
n Maintenance
Defect
Detection Chaotic
Zone
In this diagram, a chaotic zone has been defined. In fact, if defects are not discovered and
fixed at the appropriate stage, then at the testing and maintenance phases, these defects
are piled up. Therefore, a chaotic zone is formed for the testing and the development
teams as the number of defects which are piled up, destabilize the application and it
becomes extremely hard to fix all these defects as some of these bugs may involve
changes in requirements and design. At testing or the maintenance phases, fixing a defect
in requirements or design becomes extremely expensive, as underlying code will have to
be changed as well.
If we combine the results of the above two diagrams, it is evident that testing alone does
not suffice. We need to employ inspection techniques and combine them with testing to
increase the effectiveness of defect removal efficiency.
11.13 Defect origination
In inspections the emphasis is on early detection and fixing of defects from the program.
Following are the points in a development life cycle where defects enter into the
program.
Requirements
Design
Coding
User documentation
Testing itself can cause defects due to bad fixes
Change requests at the maintenance or initial usage time
_____________________________________________________________________209
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
It is important to identify defects and fix them as near to their point of origination as
possible.
Lecture No. 41
11.14 Inspection versus Testing
Inspections and testing are complementary and not opposing verification techniques.
Both should be used during the verification and validation process. Inspections can check
conformance with a specification but not conformance with the customer’s real
requirements. Inspections cannot check non-functional characteristics such as
performance, usability, etc. Inspection does not require execution of program and they
maybe used before implementation. Many different defects may be discovered in a single
inspection. In testing, one defect may mask another so several executions are required.
For inspections, checklists are prepared that contain information regarding defects. Reuse
domain and programming knowledge of the viewers likely to help in preparing these
checklists. Inspections involve people examining the source representation with the aim
of discovering anomalies and defects. Inspections may be applied to any representation of
the system (requirements, design, test data, etc.) Thus inspections are a very effective
technique for discovering errors in a software program.
Inspection pre-conditions
A precise specification must be available before inspections. Team members must be
familiar with the organization standards. In addition to it, syntactically correct code must
be available to the inspectors. Inspectors should prepare a checklist that can help them
during the inspection process.
Inspection checklists.
Checklist of common errors in a program should be developed and used to drive the
inspection process. These error checklists are programming language dependent such that
the inspector has to analyze major constructs of the programming language and develop
checklists to verify code that is written using these checklists. For example, in a language
of weak type checking, one can expect a number of peculiarities in code that should be
verified. So the corresponding checklist can be larger. Other example of programming
language dependant defects are defects in variable initialization, constant naming, loop
termination, array bounds, etc.
Inspection Checklist
Following is an example of an inspection checklist.
Exception Have all possible error conditions been taken into account?
management
faults
Fault Class Inspection Check
_____________________________________________________________________210
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Data faults Are all program variables initialized before their values are used?
Have all constants been named?
Should the lower bound of arrays be 0, 1, or something else?
Should the upper bound of arrays be size or size -1?
If character strings are used, is a delimiter explicitly assigned?
Control faults For each conditional statement, is the condition correct?
Is each loop certain to terminate?
Are compound statements correctly bracketed?
In case statements, are all possible cases accounted for?
Input/Output Are all input variables used?
faults Are all output variables assigned a value before they are output?
Interface faults Do all function and procedure calls have correct number of parameters?
Do formal and actual parameters types match?
Are the parameters in right order?
If components access shared memory, do they have the same model of
shared memory structure?
Storage If a linked structure is modified, have all links been correctly assigned?
management If dynamic storage is used, has space been allocated correctly?
faults Is space explicitly de-allocated after it is no longer required?
In the checklist mentioned above, a number of fault classes have been specified and their
corresponding inspection checks are described in the column at the right side. This type
of checklist helps an inspector to look for specific defects in the program. These
inspection checks are the outcomes of experience that the inspector has gained out of
developing or testing similar programs.
_____________________________________________________________________211
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
_____________________________________________________________________212
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Lecture No. 42
Debugging
12.1 Debugging
As Benjamin Franklin said, “in this world, nothing is certain but death and taxes.” If you
are in the software development business, however, you can amend that statement.
Nothing in life is certain except death, taxes, and software bugs. If you cryogenically
freeze yourself, you can delay death indefinitely. If you move to a country with no
income tax, you can avoid paying taxes by not buying anything. If you develop software,
however, no remedy known to mankind can save you from the horror of software bugs.
What is a Bug?
We call them by many names: software defects, software bugs, software problems, and
even software “features.” Whatever you want to call them, they are things the software
does that it is not supposed to do (or, alternatively, something the software doesn’t do
that it is supposed to). Software bugs range from program crashes to returning incorrect
information to having garbled displays.
12.2 A Brief History of Debugging
It would appear that as long as there have been computers, there have been computer
bugs. However, this is not exactly true. Even though the earliest known computer
programs contained errors, they were not, at that time, referred to as “bugs.” It took a
lady named Admiral Grace Hopper to actually coin the term “bug.”
After graduating from Vassar in 1928, she went to Yale to receive her master’s degree in
mathematics. After graduating from Yale, she worked at the university as a mathematics
professor. Leaving Yale in 1943, with the onset of World War II, Mrs. Hopper decided to
work for the Navy. Mrs. Hopper’s first assignment was under Commander Howard Aiken
at Howard University, working at the Bureau of Ordinance Computation. She was a
programmer on the Mark II, the world’s first automatically sequenced digital computer.
The Mark II was used to determine shooting angles for the big guns in varying weather
conditions during wartime.
It was during her term with the Mark II that Hopper was credited with coining the term
“bug” for a computer problem. The first “bug” was actually a moth, which flew through
an open window and into one of the Mark II’s relays. At that time, physical relays were
used in computers, unlike digital components we use today. The moth shorted out across
two contacts, temporarily shutting down the system. The moth would later be removed
(de-bugged?) and pasted into the logbook of the project. From that point on, if her team
was not producing numbers or working on the code, they claimed to be “debugging” the
system.
From that auspicious beginning, computer debugging developed into something of a hit-
or-miss procedure for quite a few years. Early debugging efforts mostly centered around
either data dumps of the system or used output devices, such as printers and display
lights, to indicate when an error occurred. Programmers would then step through the code
line by line until they could determine the location of the problem. The next step in the
_____________________________________________________________________213
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
evolution of debugging came with the advent of command-line debuggers. These simple
programs were an amazing step forward for the programmers. Although difficult to use,
even at the time, these programs represented the first real attempt to turn debugging from
a hit-or-miss proposition into a reproducible process.
Once the debugger became a part of the programmer’s arsenal, the software world began
to consider other ways that programs could be more easily debugged. Software projects
starting getting bigger, and the same techniques that worked well for small projects no
longer worked when the program reached a certain size.
Importance of Debugging
As we mentioned earlier in this course, one of the prime objectives of software
engineering is to develop cost effective software applications. According to a survey,
when a software application is in the maintenance phase, 20% of its lifecycle cost is
attributed towards the defects which are found in the software application after
installation. Please bear in mind that the maintenance is the phase in which 2/3rd of the
overall software cost incurs. Therefore, 20% of the 2/3rd cost is again a huge cost and we
need to understand why this much cost and effort is incurred. In fact, when a software
application is installed and being used, any peculiarity in it can cost a lot of direct and
indirect damages to the organization. A system downtime is the period in which
tremendous pressure is on developers end to fix the problem and make the system
running again. In these moments, every second costs hugs losses to the organization and
it becomes vital to find out the bug in the software application and fix it. Debugging
techniques are the only mechanism to reach at the code that is malfunctioning. In the
following subsection, we shall discuss an incident that took place in 1990 and see how
much loss the company had to suffer due to a mere bug in the software application.
12.4 Problem at AT&T
In the telecommunications industry, loss of service is known as an outage. For most of us,
when as outage occurs, we lose our telephone service; we cannot make calls and we
cannot receive calls. Outages are accepted and expected hazards in the industry.
On January 15. 1990, AT&T had a US wide telephone system outage that lasted for nine
hours. The cause was due to a program error in the software that was meant to make the
system more efficient. Eight years later, on April 13, 1998, AT&T suffered another
massive failure in its frame-relay network, which affected ATM machines, credit card
transactions and other business data services. This failure lasted 26 hours. Again, the bug
was introduced during a software upgrade.
Description of the Problem
The code snippet that caused the outage is illustrated as follows
1. do {
2. ...
3. switch (expression) {
4. case 0: {
5. if (some_condition) {
_____________________________________________________________________214
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
6. ...
7. break;
8. } else {
9. ...
10. }
11. ...
12. break;
13. }
14. ...
15. }
16. . . .
17. } while (some_other_condition);
In this case the break statement at line 7 was the culprit. As implemented, if the
logical_test on line 5 was successful, the program should have proceeded to line 6 to
execute those statements. When the program stepped to line 7, the break statement caused
the program to exit the “switch” block between line 3 and line 15, and proceeded to
execute the codes in line 16. However, this path of execution was not the intention of the
programmer. The programmer intended the break statement in line 7 to break the if-then
clause; so, after the program executed line 7, it was supposed to continue execution in
line 11.
AT&T statement about the Problem
“We believe that the software design, development, and testing processes we use are
based on solid, quality foundations. All future releases of software will continue to be
religiously tested. We will use the experience we've gained through this problem to
further improve our procedures.”
We do not believe we can fault AT&T’s software development process for the 1990
outage, and we have no reason to believe that AT&T did not rigorously test its software
update. In hindsight, it is easy to say that if the developers had only tested the software,
they would have seen the bug. Or that if they had performed a code inspection, they
would have found the defect. Code inspection might have helped in this case. However,
the only way the code inspection could have uncovered this bug is if another engineer
saw this particular line of code and asked the original programmer if that was his or her
intension. The only reason that the code reviewers might have asked this question is if
they were familiar with the specifications for this particular code block.
_____________________________________________________________________215
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
“code” and when he has to check this code, he can potentially miss out obvious mistakes
due to this impression or bias. Therefore, it is strongly recommended that in order to
reach to a defect in the code, one needs “another pair of eyes”. That is, start discovering
the defect by applying your own heuristics and if you could reach to the problem, fine,
otherwise ask a companion to help you in this process. We shall further elaborate this
idea based on the following example.
Program at Bulletin Board Example
Following piece of code was once placed on a bulletin board making an invitation to
people to discover the problem in this code. Please look at this code and discover the
problem
Well if you could not guess it by now, the problem lies with the syntax of the while loop.
This is so obvious that almost everyone forgot to ponder upon when placed on the
bulletin board of a university. The loop is “while” but the syntax used is a “for” loop.
In order to reach such defects, one needs a scientific approach to check and verify the
code methodically. Based on this discussion, we are now in a position to introduce a few
classes of bugs to the reader. This is not an exhaustive list since there could be a number
of other classes of bugs as well but the following classes will help the reader know about
some well known bugs that we usually find in the code.
Lecture No. 43
12.6 Bug Classes
Memory and resource leak
A memory leak bug is one in which memory is somehow allocated from either the
operating system or an internal memory "pool", but never deallocated when the memory
is finished being used.
Symptoms
System slowdowns
Crashes that occur "randomly" over a long period of time
Example 1
Let’s take a look at a simple memory leak error that can occur trivially in a C program.
This type of code is found in hundreds of programs across the programming spectrum. It
illustrates the simplest possible case of a memory leak, which is when memory is
allocated and not deallocated in all cases. This particular form of the bug is the most
frustrating because the memory is usually deallocated, but not always
_____________________________________________________________________216
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
delete buffer;
return okCode;
Note that in many cases, this code works perfectly. If no error occurs in the processing
stage (which is the norm) the memory is freed up properly. If, however, the processing
stage encounters an error, the memory is not freed up and a leak occurs.
Example 2
The following code snippet from some old C++ code contains a slightly more insidious
bug. It illustrates the point well.
Class Foo
{
private:
int nStringLength;
char *sString;
public:
Foo()
{
nStringLength = 20; //Default
sString = new
char[nStringLength + 1];
}
~Foo()
{
delete sString;
}
void SetString(const char
*inString)
{
_____________________________________________________________________217
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Let’s discuss what happens. In most cases, the Foo object is created and nothing bad
happens. If, however, you call the SetString method, all bets are off. The previously
allocated string is overwritten by the new allocation, and the old allocated memory goes
nowhere. We have an instant memory leak. Worse, we can do this multiple times if we
accidentally call the method with a NULL string because it first allocates the block, and
then checks to see if the input string was correct. Don’t do things like this. If you see an
allocation in a class, check to see if the string can be allocated before it gets to that point.
Logical Errors
A logical error occurs when the code is syntactically correct but does not do what you
expect it to do.
Symptoms
The code is misbehaving in a way that isn't easily explained.
The program doesn't crash, but the flow of the program takes odd branches
through the code.
Results are the opposite of what is expected.
Output looks strange, but has no obvious symptoms of corruption.
Example
// Make sure that the input is valid. For this value, valid ranges are 1-10 and 15-20
A coding error is a simple problem in writing the code. IT can be a failure to check error
returns, a failure to check for certain valid conditions, or a failure to take into account
other parts of the system. Yet another form of a coding error is incorrect parameter
passing and invalid return type coercion.
Symptoms
Unexpected errors in black box testing.
The errors that unexpectedly occur are usually caused by coding errors.
Compiler warnings.
Coding errors are usually caused by lack of attention to details.
Example
In the following example, a function accepts an input integer and converts it into a string
that contains that integer in its word representation.
}
}
There are a few things to notice in the preceding code. The ConvertToString function
does not handle all cases of inputs, which becomes very obvious you pass a zero value.
Worse, the function does not initialize the output variables, leaving them at whatever they
happened to be when they came into the function. This isn’t a problem for the output
string, necessarily, but it will become a serious issue for the output length.
Memory over-runs
_____________________________________________________________________219
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
a memory overrun occurs when you use memory that does not belong to you. This can be
caused by overstepping an array boundary or by copying a string that is too big for the
block of memory it is defined to hold. Memory overruns were once extremely common in
the programming world because of the inability to tell what the actual size of something
really was.
Symptoms
Program crashes quite regularly after a given routine is called, that routine should
be examined for a possible overrun condition.
If the routine in question does not appear to have any such problem the most
likely cause is that another routine, called in the prior sequence, has already
trashed variables or memory blocks.
Checking the trace log of the called routines leading up to one with the problem
will often show up the error.
Example
This particular example shows not only a memory overrun, but also how most
programmers “fix” problems in an application. The ZeroArray function steps all over the
array boundaries by initializing 100 separate entries. The problem is that that particular
array only has 50 slots available in its allocation. What happens at that point is that the
function goes past the end of the array and starts to walk on things beyond its control.
_____________________________________________________________________220
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The preceding code fragment contains an indirect looping error such that the loop will
continue until the impossibleCondition becomes true which is impossible to happen.
int anArray[50];
int i;
i = 50;
while(i >= 0){
anArray[i] = 0;
i = i - 1;
}
In this example, the programmer was trying to be smart. He worked his way backward
though the array, assuming that this way there would be no chance of an error. Of course,
if you examine the loop, you will find that it performed 51 times. There are only fifty
elements in the array. This will certainly lead to a problem later on in the program, if it
doesn’t first trigger an immediate error from the system.
int nIndex = 0;
for(int i=0; i<kMaxIterations; ++i)
{
while (nIndex < 20)
{
ComputeSomething(i*20 + nIndex);
nIndex ++;
}
}
The final situation is an improper exit condition for a loop. This is most easily illustrated
using a set of nested loops. In the above example, we are trying to compute something
within the inner loop for some number of iterations. The code appears to do what we said
it should do. It computes whatever it is we are computing in the inner loop for each
iteration of the outer loop, 20 times. The problem, however, is that the exit condition
simply says that nIndex should be less than 20. The first time through the outer loop, this
variable will become 21, and the inner loop will exit. This is correct, and exactly the way
_____________________________________________________________________221
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
you would expect this to happen. The problem, however, is that the next time through the
loop, the inner loop will not be executed at all.
Pointer errors
A pointer error is any case where something is being used as an indirect pointer to
another item.
Uninitialized pointers: These are pointers that are used to point at something, but
we fail to ever assign them something to point at.
Deleted pointers, which continue to be used.
An Invalid pointer is something that is pointing to a valid block of memory, but
that memory does not contain the data you expect it to.
Symptoms
The program usually crashes or behaves in an unpredictable and baffling way.
You will generally observe stack corruptions, failure to allocate memory, and odd
changing of variable values.
Changing a single line of code can change where the problem occurs.
If the problem "goes away" when you place a print statement or new variable into
the code that you suspect contains the problem.
Example
Let’s take a look at one of the most common forms of the pointer error, using a pointer
after it has been deleted. As you can see by the following example, it is not always clear
when you are doing this incorrectly:
int func()
{
char *s = new char[80];
cleanup_function(s);
delete s;
}
In this example, the programmer meant to be neat and tidy. He probably wrote the code
originally to allocate the pointer at the top of this function, and then by habit put in a
deallocation at the bottom of the function. This is, after all, good programming practice to
avoid memory leaks. The problem is introduced with th3e cleanup_function routine. This
function was probably written at a later time by another developer and might have been
used to ensure that all allocated pointers were stored to the permanent drive and then
freed up to avoid any possible leaks. In fact, the code in question comes from a set of
functions that was reused from a memory pool system that saved its data to disk before
destroying the pointer, so that another pointer could be retrieved from the persistent pool.
_____________________________________________________________________222
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
The problem is, the reuse did not take into account the existing system. This problem is
common when reusing only parts of a system.
When the second delete occurs at the bottom of func(), the results are unpredictable. At
best, the delete function recognizes that this pointer has been deleted already and doesn’t
do anything. At worst, memory is corrupted and you are left with a memory crash
somewhat later in the program, which will be very difficult to find and fix.
Boolean bugs
Boolean bugs occur because the mathematical precision of Boolean algebra has virtually
nothing to do with equivalent English words.
When we say "and", we really mean the boolean "or" and vice versa.
Symptoms
When the program does exactly the opposite of what you expect it to. For
example, you might have thought you needed to select only one entry from a list
in order to proceed. Instead, the program will not continue until you select more
than one. Worse, it keeps telling you to select only one value.
For true/false problems, you will usually see some sort of debug output indicating
an error in a function, only to see the calling function proceed as though the
problem had not occurred.
Examples
The following code contains a simple example of a function that returns a counter-
intuitive Boolean value and shows how that value leads to problems in the rest of the
application code. This case performs an action and indicates to the user whether or not
the action succeeded.
After looking at the function, ask yourself this – What is the return value in the case of
success? What would it be in the case of failure? How would you know this by simply
glancing at the function declaration?
int Value;
int Ret;
Value = 11;
_____________________________________________________________________223
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Ret = DoSomeAction(Value);
if(Ret)
cout <<Error in DoSomeAction<<;
If you were debugging this application, you might start out by wondering why it didn’t
work. Further investigation would show that the error statement is never triggered in spite
of the fact that the routine did, in fact, encounter an error.. Why did this happen? It
happened because the routine didn’t return nonzero value for failure, it returned nonzero
for success. This Boolean value was not intuitive given the condition of the function and
led to a poor assumption by the programmer who wrote the code that used it.
Lecture No. 44
12.7 Holistic approach
Holistic means
Emphasizing the importance of the whole and the interdependence of its parts.
Concerned with wholes rather than analysis or separation into parts
What this meant is that a holistic approach focuses on the entire system rather than
whatever piece appears to be broken. Holistic medicine, for example, concerns itself with
the state of the body as a whole, not the disease that is currently attacking it. Similarly,
programmers and debuggers must understand that you cannot treat the symptoms of a
problem, you must focus on the application system as a whole.
Now that you understand what holistic means, how do you apply holistic concepts to
debugging the software programs and procedures? Let’s start by thinking about what
emphasizing the whole over the individual pieces means in debugging. When you are
debugging an application, you often simply look at the problem reported by the user and
how you can make that problem go away.
As a simple example, consider the case where the program mysteriously crashes at a
particular point in the code each and every time the program is run. The point at which
the code crashes makes no sense at all. For example, in C++, you might have a member
function of a class that reads:
void SetX(int X)
{
mX = X;
}
The program always crashes on the line that assigns X to the member variable mX(mX =
X). Looking at this code snippet, we see very few valid ways in which the program could
be encountering a problem at this point. Oddly, we might discover that inserting a
message statement makes the problem stop occurring when the indicated steps are
followed for reproducing the problem. Is the problem fixed?
_____________________________________________________________________224
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
Most experienced programmers, managers, or debuggers would say that the problem is
not fixed, although few could tell you exactly why that is the case. The fact is, in this
case, we are directly treating the symptoms (the program crashing) rather than looking
into the actual problem and ignoring the overall problem is endemic in our industry.
1. "I started by trying to setup a Favorites list. I first went to the home page. Then, I
selected Favorites from the menu on the right. I scrolled down to the third entry and
pressed Enter on the keyboard. Then I moved to the fourth entry on the submenu and
clicked it with the mouse. Finally, I entered my name as Irving, clicked on OK, and
the program crashed."
2. "I went to the programming menu and selected the New menu option. I then clicked
on the Create Object menu entry and entered the name HouseObject for the object
name field. Then I clicked OK, and the program crashed."
3. "I selected the New Project menu option, and then clicked on the icon that looks like
a Gear. I entered the name Rudolph for the project name, and then clicked OK. The
program crashed."
After all, they appear to relate to three different sections of the program.
Most people, when reporting bugs, focus on what they think was the important
step in the process.
Filter out the unimportant information and see what each case really has in
common.
First, each user clicked on the OK button to finalize the process, and the program
crashed.
It might seem likely, therefore, that the program OK handler contains a fatal flaw.
A bit of experimentation will show whether this is the case or not.
When we examine the statements of the witnesses, we notice that each was
working with a menu.
We can see that each person used both the keyboard and the mouse to select from
the menus before clicking the OK button.
"I selected Favorites from the menu on the right. I scrolled down to the third entry and
pressed Enter on the keyboard. Then I moved to the fourth entry on the submenu and
_____________________________________________________________________225
© Copyright Virtual University of Pakistan
CS504-Software Engineering – I VU
"... selected the New menu option. I then clicked on the Create Object menu entry ..."
"I selected the New Project menu option, and then clicked on the icon that looks ..."
We can infer, therefore, that the user in this case used both the keyboard and
mouse.
The next logical place to look is in the menu handler to see whether it deals with
mouse and keyboard entries differently.
The final clue is in the third entry, where the user did not select anything from the
menu with the mouse, but instead clicked on an icon.
While looking at the code, I would try to see what happens when the program
deals with a combination of keyboard and menu entry.
It is likely, given the user discussion, that you will find the root of the problem in
this area.
After finding such a common bug, it is likely that the fix will repair a whole lot of
problems at once
This is a debugger's dream.
Good clues, Easy Bugs
Get A Stack Trace
In the debugging process a stack trace is a very useful tool.
Following stack trace information may help in debugging process.
Source line numbers in stack trace is the single, most useful piece of debugging
information.
After that, values of arguments are important
o Are the values improbable (zero, very large, negative, character strings
with non-alphabetic characters?
Debuggers can be used to display values of local or global variables.
o These give additional information about what went wrong.
Non-reproducible bugs
Bugs that won't "stand still" (almost random) are the most difficult to deal with.
Randomness itself, however, is information.
Are all variables initialized? (random data in variables could affect output).
Does bug disappeared when debugging code is inserted? Memory allocation
(malloc) problems are probably a culprit.
Is the crash site far away from anything that could be wrong?
Check for dangling pointers.
Example
Lecture No. 45
Summary
_____________________________________________________________________227
© Copyright Virtual University of Pakistan