Principles of Programming Language-Unit 1
Principles of Programming Language-Unit 1
Principles of Programming Language-Unit 1
SOFTWARE DESIGN
INTRODUCTION
Program Is a sequence of instructions written to perform a specified task for a computer.
Software - Is a collection of computer programs and related data that provide, the instructions telling a
computer what to do.
Software Design
Software design is Planning that lays the basis for making of every obect or system. !or"
#riginating $ developing a plan for a product%.
&esign Process Involves.
'onceiving $ planning out in mind
(aking a drawing, pattern or sketch.
)hree distinct types of activities in software design*
+. ,-ternal design
.. /rchitectural design
0. &etailed design.
/rchitectural and detailed designs are collectively referred to as internal design.
External Design
,-ternal design of software involves conceiving, planning out, and specifying the e-ternally
observable characteristics of a software product.
)hese characteristics include user displays and report formats, e-ternal data sources and data
sinks, and the functional characteristics, performance requirements, and high level process
structure for the product.
,-ternal design begins during the analysis phase and continues into the design phase.
,-ternal design is concerned with refining e-ternal, functional, performance requirements as
well as e-ception handling and establishing the high level structural view of the system.
Internal Design
Involves conceiving, planning out, and specifying the internal structure and processing
details of the software product.
)he goals of internal design are to specify internal structure and processing details, to record
design decisions and indicate why certain alternatives and also to provide a blueprint for
implementation, testing and maintenance activities.
)he work products of internal design include a specification of architectural structure, the
details of algorithms and structure, and the plan.
Architectural Design
1
Principles And Programming Languages Unit - I
is concerned with refining the conceptual view of the system by
Identifying the internal processing function
&ecomposing high-level functions into sub-functions
&efining internal data streams, data stores and establishing relationships and
interconnections among function, data streams data stores.
Test plans
)est plans describes the obectives of testing, the test completion criteria, the integration
plan ,particular tools and techniques to be used, and the actual test cases and e-pected
results.
1unctional tests and performance tests are developed during requirements analysis and are
refined during the design phase.
)ests that e-amine the internal structure of the software product and tests that attempt to
break the system are developed during detailed design and implementation.
,-ternal design and architectural design typically span the period from software requirements
review to preliminary design review.
&etailed design spans the period from preliminary design review to critical design review as
represented below in fig +.
FUNDAMENTAL DESIGN CONCEPTS
,very intellectual discipline is characteri2ed by fundamental concepts and specific techniques that
provide the basis for development and evaluation techniques.
)echniques are the e-pression of the concepts as they apply to particular situations. )hese
techniques come and go with changes in technology, economic conditions and social
concerns.
1undamental concepts of software design include
+. /bstraction
2
Phases* /nalysis &esign Implementation
/ctivities*
Planning
3equirements
&efinition
,-ternal
/rchitectural
&etailed
'oding
&ebugging
)esting
'&3 P&3 S33 3eviews*
Fig.1 Timing of the Softw!e Re"#i!ement$ Re%iew &SRR'( the P!e)imin!* De$ign Re%iew &PDR'( n+ the
C!iti,) De$ign Re%iew &CDR'
Principles And Programming Languages Unit - I
.. Structure
0. Information hiding
4. (odularity
5. 'oncurrency
6. 7erification
8. &esign aesthetics
Abstraction
/bstraction is an intellectual tool that allows us to deal with concepts apart from detailed
illustration of those concepts.
/bstractions are formed by reducing the information content of a concept or an observable
phenomenon, typically to retain only information which is relevant for a particular purpose.
&uring software design, abstraction allows us to organi2e and channel our thought processes by
postponing structural considerations and detailed algorithmic considerations until the functional
characteristics, data streams, and data stores have been established.
Structural considerations are then addressed prior to consideration of algorithmic details.
)his approach reduces the amount of comple-ity that must be dealt with at any particular point in
the design process.
/rchitectural design specifications are models of software in which the functional and structural
attributes of the system are empathi2ed.
&uring detailed design, the architectural structure is refined into implementation details.
)he contrasts use of abstraction in science $ mathematics is that design is a process of proceeding
from abstract considerations to concrete representations. 9here fundamental principles are
abstracted from a collection of concrete situations.
)here widely used abstractions mechanisms in software design are
+. 1unctional abstraction
.. &ata abstraction
0. 'ontrol abstraction.
)hese mechanisms allow us to control the comple-ity of the design process by systematically
proceeding from the abstract to the concrete.
Functional abstraction
Involves the use of parameteri2ed subprograms.
3
Principles And Programming Languages Unit - I
)he ability to parameteri2e a subprogram and to bind different parameter values on different
invocations of the subprogram is a powerful abstraction mechanism.
1unctional abstraction can be generali2ed to collections of subprograms, herein called
groups% !packages in /da, clusters in ':;". 9ithin a group, certain routines have the
visible% property, which allows them to be used by routines in other groups.
3outines without the visible property are hidden from other groups and can only be used with
the containing group.
/ group thus provides a functional abstraction in which the visible routines communicate
with other groups and the hidden routines e-ist to support the visible ones.
Data abstraction
Involves specifying a data type or a data obect by specifying legal operations on obects<
representation and manipulation details are suppressed.
)hus the type %stack% can be specified abstractly as a :I1# mechanism in which the
routines =,9, P;S>, )#P, P#P and ,(P)?.
Several modern programming languages, including ':; and /da, provide abstract data
types.
&ata encapsulation, sometimes referred to as data hiding, is the mechanism whereby the
implementation details of a class are kept hidden from the user. )he user can only perform a
restricted set of operations on the hidden members of the class by e-ecuting special
functions commonly called methods.
@inding of data and functions into a single unit is called encapsulation.
/bstract data types
/bstract data types are abstract in the sense that representation details of the data
items and implementation details of the functions that manipulate the data items are
hidden within the group that implements the abstract type.
#ther groups that use abstraction do not have access to the internal details of abstract
the obects. #bects of abstract type are thus known only by the functions that can be
performed on them.
,-ample* stack is an /bstract data type, but stack implemented with an array and with
linked list are both different data structures.
&uring architectural design, the visible functions that operate on abstract obects are
specified.
Control Abstraction
)hird commonly used abstraction mechanism in software design.
'ontrol abstraction is used to state a desired effect without stating the e-act mechanism of
control.
4
Principles And Programming Languages Unit - I
I1 statements and 9>I:, statements in modern programming languages are abstractions of
machine code implementations that involves conditional ump instructions.
,-ample* / statement of the form for all I is S sort files I :eaves unspecified the sorting
technique, the nature of S, the nature of the files, and how for all I in S is to be handled.
/t the architectural design level, control abstraction permits specification of sequential
subprograms, e-ception handlers, and concurrent program units without concern for the
e-act details of implementation.
Information Hiding
Information hiding is a fundamental design concept for software.
9hen a software system is designed using information hiding approach, each module in the system
hides the internal details of its processing activities and modules communicate only through well-
defined interfaces.
&esign should begin with a list of difficult design decisions and design decisions that are likely to
change.
,ach module is designed to hide such a decision from the other modules. @ecause these design
decisions transcend e-ecution time, design modules may not correspond to processing steps in the
implementation of the system.
Information hiding can be used as the principal design technique for architectural designing of a
system, or as a modulari2ation criterion with other design techniques.
Structures
Structure is a fundamental characteristic of computer software.
)he use of structure permits decomposition of a large system into smaller,
more manageable units with well-defined relationships to the other units in the system.
)he most general form of system structure is the network.
/ computing network can be represented as a directed graph, consisting of nodes and arcs.
)he nodes can represent processing elements that transform data and the arcs can be used to
represent data links between nodes.
/lternatively, the nodes can represent data stares and the arcs data transformation.
In simplest form, a network might specify data flow and processing steps within a single
subprogram, or the data flow among a collection of sequential subprograms.
)he most comple- form of computing network is a distributing computing system in which
each mode represents a geographically distinct processor with private memory.
)he structure inside a comple- processing node
5
Principles And Programming Languages Unit - I
'onsist of concurrent processes e-ecuting in parallel and communicating through
some combination of shared variables and synchronous and asynchronous message
passing.
Inside each process, one might find functional abstraction groups, data abstraction
groups, and control abstraction groups.
,ach group might consist of a visible specification part and a hidden body.
)he visible portion would provide attributes such as procedure interface, data types,
and data obects available for use by other groups.
)he body of a processing group is typically a hierarchical collection of subprograms
and static data areas that implement the attributes specified in the visible specification
part of the group.
)he entire network might be a comple- abstraction that provides an information utility and
in turn forms a node in a more comple- structure of people and machines.
)he process network view of software structure is illustrated in figure ..
6
:ink
=ode
=etwork
)emplate Aroup
Processing Aroup
;tility Aroup
Process
Processes
,nvironment group templates
Shared #bects
=ode
7isible Part
Static /rea
>idden Part
Aroup
Fig 2. Software System Structure
Principles And Programming Languages Unit - I
)he relationship uses% and the complementary relationship% is used by% provide the basis for
hierarchical ordering of abstractions in a software system. )he uses% relationship can be
represented as a directed graph, where the notation A B means A uses B% or% B is used by A.%.
>ierarchical ordering of abstraction
is established by the following rule*
If A and B are distinct entities, and if A uses B,
)hen B is not permitted to use A or any entity
)hat makes use of A.
>ierarchical ordering relation can be represented as an acyclic, directed graph with a
distinguished node that represents the root entity.
>ierarchical structure may or may not form structures.
1igure 0 !a" and !b" illustrate a directed, acyclic graph and a tree structure respectively.
=ote that in a tree there is a unique path from the root to each node.
In an acyclic, directed graph there may be more than one path from the root to a node.
@elow represented figure 0 is a structure charts not flowcharts because there is no
indication of the processing sequence, and no indication of the conditions under
which A might use B.
7
A
B C
!
A
B C
!
!a" !b"
Figure. 3 (a) A gra! structure c!ar and (b) A tree structure c!art
Principles And Programming Languages Unit - I
In cases where the structure chart depicts the structure of subroutines in a system, the data passed
between routines can be indicated on the arcs connecting routines, as illustrated in figure 0.
&irected recursive routines those that invoke themselves can be indicated on a structure chart by
placing closed arcs on the nodes for those routines.
Indirectly recursive routines violate the hierarchical structuring rule, and
should generally be avoided. /llowable e-ceptions include mutually recursive routines and co-
routines.
)he hierarchical structures illustrated in figure 0 !a" and !b" are desirable because they reduce the
comple-ity of interactions among software components.
1igure 4 represents, there are =!=-+"B. interconnection of = nodes in a connected graph, but only
=-+ interconnections of = nodes connected in a tree structure. =-+ is the minimum number of
connections for = nodes.
/ hierarchical structure isolated software components and promotes ease of understanding,
implementation, debugging, testing, integration, and modification of a system.
In addition, programmers can be assigned, either individually or in teams, to implements the
various subsystems in a hierarchical structure. In this sense, the organi2ational structure of teams
that develop software systems should resemble the desired structure of the software being
developed.
In hierarchical systems, there are usually one or more groups of routines designated as utility
groups.
)hese groups typically contain lowest level routines !routines that do not use other routines"
that are used throughout the hierarchy.
)ypical utilities include math library functions, IB# routines, plotting packages, and other
general-purpose software.
Several different criteria are available to guide hierarchical decomposition of a software
system.
)hese include decomposition into processing steps and sub-steps, decomposition to
reinforce information hiding, coupling and cohesion, data encapsulation, andBor problem
modeling.
"odu#arity
(odule
In software, a module is a part of a program.
"
!/ @ ' /"
!/ @"
Figure $. (a) I##ustrating %(%&')(2 #in)s
among % nodes in a connected gra!
Figure $. (b) I##ustrating (%&') #in)s among %
nodes in a tree
Principles And Programming Languages Unit - I
Programs are composed of one or more independently developed modules that are not combined
until the program is linked.
/ single module can contain one or several routines.
(odular systems
Incorporate collections of abstractions in which each functional abstraction, each data
abstraction, and each control abstraction handles a local aspect of the problem being solved.
(odular systems consist of well defined, manageable units with well-defined interfaces
among the units.
&esirable properties of a modular system include*
+. ,ach processing abstraction is a well-defined subsystem that is potentially useful in
other applications.
.. ,ach function in each abstraction has a single, well defined purpose.
0. ,ach functions manipulated no more than one maor data structure.
4. 1unctions share global data selectively. It is easy to identify all routines that share a
maor data structure.
5. 1unction that manipulate instances of abstract data types are encapsulated with the
data structure being manipulated.
(odularity enhances design clarity, which in turn eases implementation,
debugging, testing, documenting, and maintenance of the software product.
*oncurrency
'oncurrency is a fundamental principle of software design because
parallelism in software introduces added comple-ity and additional degrees of freedom into the
design process.
Software systems categori2ed as
Sequential systems
'oncurrent systems.
Sequential system,
#nly one portion of the system is active at ant given time.
'oncurrent systems
>ave independent processes that can be activated simultaneously if multiple processors are
available.
#n a single processor, concurrent processes can be interleaved in e-ecution time. )his
permits implementation of time-shared, multi-programmed, and real-time systems.
Problem unique to concurrent systems includes
+. &eadlock*
o It is an undesirable situation that occurs when all processes in a computing
system are waiting for other processes to complete some actions so that each
can proceed.
#
Principles And Programming Languages Unit - I
.. (utual e-clusion*
o (utual e-clusion is necessary to ensure that multiple processes do not attempt
to update the same components of the shared processing state at the same time.
0. Synchroni2ation of processes*
o Synchroni2ations is required so that concurrent processes operating at
differing e-ecution histories.
/s hardware becomes more sophisticated, and as computing systems become more
comple-, it becomes increasingly necessary for every software engineer to understand the
issues and techniques of concurrent software design.
+erification
7erification is a fundamental concept in software design.
&esign
&esign is the bridge between customer requirements and an implementation that satisfies
those requirements.
/ design is verifiable if it can be demonstrated that the design will result in an
implementation that satisfies the customerCs requirements.
&esign verification typically done in two steps*
'oncurrency is a fundamental principle of software design because parallelism in software
introduces added comple-ity and additional degrees of freedom into the design process.
+. 7erification that the software requirements definition satisfies the customerCs needs
!verification of the requirements"
.. 7erification that the design satisfies the requirements definition !verification of the
design".
)est Plan
)est plan is a product of the design process. )he test plan must be coupled to specifications
that are testable.
In software design, one must ensure that the system is structured so that the internal states
can be observed, tested, and the results related to the requirements.
Aest!etics
/esthetic considerations are fundamental to design, whether in art or technology.
Simplicity, elegance, and clarity of purpose distinguish products of outstanding quality from
mediocre products.
Speaking of mathematical elegance or structural beauty, we are speaking of those properties that go
beyond mere satisfaction of the requirements.
It is difficult to list obective criteria for evaluating the aesthetic factors in a software product, but
an aesthetically pleasing product is easily recogni2ed.
1$
Principles And Programming Languages Unit - I
MODULES AND MODULARI-ATION CRITERIA
/rchitectural design has the goal of producing well-structured, modular software systems.
Software module are named entity that have the following characteristics*
+. (odules can contain instructions, processing logic, and data structures.
.. (odules can be separately compiled and stored in a library.
0. (odules can be included in a program.
4. (odules segments can be used by invoking a name and some parameters.
5. (odules can use other modules.
,-amples of modules include
Procedures, subroutines, and functions
1unctional groups of related procedures, subroutines, and functions
&ata abstraction groups< utility groups< and concurrent processes.
(odulari2ation allows the designer to decompose a system into functional units,
to impose hierarchical ordering on function usage, to implement data abstractions, and to develop
independently useful subsystems.
(odulari2ation can be used to isolate machine dependencies, to improve the
performance of a software product, or to ease debugging, testing, integration, tuning and
modification of the system.
)here are numerous criteria that can be used to guide the modulari2ation of a
system. &epending on the criteria used, different system structures may result.
(odulari2ation criteria include
conventional criterion, in which each module and its sub-modules correspond to a
processing step in the e-ecution sequence
information hiding criterion, in which each module hides a difficult or changeable decision
from the other modules
data abstraction criterion, in which each module hides the representation details of a maor
data structure behind functions that access and modify the data structure
levels of abstraction, in which the modules and collection of modules provide a hierarchical
set of increasingly comple- services
Problem modeling in which the modular structure of the system matches the structures of
the problem being solved.
In practice, a software system can be modulari2ed using a single design criterion or aspects of
several criteria.
In any case, structures of higher quality !easier to understand, easier to implement, easier to
modify" are produced when the designer uses well-defined modulari2ation criteria to guide the
design process.
*ou#ing and *o!esion
11
Principles And Programming Languages Unit - I
/ fundamental goal of software design is to structure the software product so that the number and
comple-ity of interconnections between modules is minimi2ed.
/n appealing set of heuristics for achieving this goal involves the concepts of coupling and
cohesion.
Coupling
)he strength of coupling between two modules is influenced by the comple-ity of the
interface, the type of connection, and the type of communication.
1or e-ample, interfaces established by common control blocks, common data blocks,
common overlay regions of memory, common IBo devices, andBor global variable names are
more comple- !more tightly coupled" than interfaces established by parameter lists passed
between modules.
'onnections established by referring to other module names are more loosely coupled than
connections established by referring to the internal elements of other modules.
'ommunication between modules involves passing of data, passing elements of control
!such as flags, switches, labels, and procedure names", and modification of one moduleCs
code by another module.
)he degree of coupling is lowest for data communication, higher for control communication,
and highest for modules that modify other modules.
'oupling between modules can be ranked on a scale of strongest !least desirable" to weakest
!most desirable" as follows*
+. 'ontent coupling
.. 'ommon coupling
0. 'ontrol coupling
4. Stamp coupling
5. &ata coupling
'ontent coupling
)his coupling occurs when one module modifies local data values or instructions in
another module.
'ontent coupling can occur in assembly language programs.
'ommon coupling
(odules are bound together by global data structures. 1or instance, common coupling
results when all routines in a 1#3)3/= program reference a single common data
block.
'ontrol coupling
)his coupling involves in passing control flags !as parameters or global" between
modules so that one module controls the sequence of processing steps in another
module.
Stamp coupling
)his coupling is similar to common coupling, e-cept that global data items are shared
selectively among routines that require the data.
Stamp coupling is more desirable than common coupling because fewer modules will
have to be modified if a shared data structure is modified.
&ata coupling
)his coupling involves the use of parameter lists to pass data items between routines.
12
Principles And Programming Languages Unit - I
)he most desirable form of coupling between modules is a combination of stamp and
data coupling.
Cohesion
)he internal cohesion of a module is measured in terms of the strength of
binding of elements within the module.
'ohesion of elements occurs on the scale of weakest !least desirable" to
strongest !most desirable" in the following order*
+. 'oincidental cohesion
.. :ogical cohesion
0. )emporal cohesion
4. 'ommunication cohesion
5. Sequential cohesion
6. 1unctional cohesion
8. Informational cohesion
'oincidental cohesion
)his cohesion occurs when the elements within a module have no apparent
relationship to one another.
)his results when a large, monolithic program is modulari2ed% by arbitrarily
segmenting the program into several small modules, or when a module is created from
a group of unrelated instructions that appear several times in other modules.
:ogical cohesion
)his implies some relationship among the elements of the module
/ logically bound module often combines several related functions in a comple- and
interrelated fashion. )his results in passing of control parameters, and in shared and
tricky code that is difficult to understand and modify.
(ath library routines often e-hibit logical cohesion. :ogically cohesive modules
usually require further decomposition.
1or e-ample, a logically cohesive module to process records might be decomposed
into four modules to process master records, process update records, process addition
records, and process deletion records.
)emporal 'ohesion
(odules with temporal cohesion e-hibit many of the same disadvantages as logically
bound modules.
)hey are higher on the scale of binding because all elements are e-ecuted at one time,
and no parameters or logic are required to determine which elements to e-ecute.
/ typical e-ample of temporal cohesion is a module that performs program
initiali2ation.
'ommunicational 'ohesion
)he elements of a module possessing communicational cohesion refer to the same set
of input andBor output data.
1or e-ample, Print and Punch the #utput 1ile% is communication ally bound.
13
Principles And Programming Languages Unit - I
'ommunicational binding is higher on the binding scale than temporal binding
because the elements are e-ecuted at one time and also refer to the same data.
Sequential cohesion
)his occurs when the output of one element is the input for the ne-t element.
1or e-ample, 3ead =e-t )ransaction and ;pdate (aster 1ile% is sequentially bound.
Sequential cohesion is high on the binding scale because the module structure usually
bears a close resemblance to the problem structure.
/ sequentially bound module can contain several functions or part of a function.
1unctional cohesion
)his is a strong and desirable type of cohesion for binding of elements in a module
because all elements are related to the performance of a single function.
,-amples of functionally bound modules are 'ompute Square 3oot%, #btain
3andom =umber%, and 9rite 3ecord to #utput 1ile%.
Informational cohesion
Informational cohesion of elements in a module occurs when the module contains a
comple- data structure and several routines to manipulate the data structure.
,ach routine in the module e-hibits functional binding.
Informational cohesion is the concrete reali2ation of data abstraction.
Informational cohesion is similar to communicational cohesion in that both refer to a
single data entity.
>owever, informational cohesion differs from communicational cohesion is that all
code in the module is e-ecuted on each invocation of the module.
Informational cohesion requires that only one functionally cohesive segment of the
module be e-ecuted on each invocation of the module.
,t!er "odu#ari-ation *riteria
/dditional criteria for deciding which function to place in which module of a software*
hiding difficult and changeable design decisions
limiting the physical si2e of modules
structuring the system to improve observer ability and testability
isolating machine dependence to a few routines calls
easing likely changes providing general purpose utility functions
developing an accessibility overlay structure in a machine with limited memory capacity
(inimi2ing page faults in a virtual memory machine.
1or each software product the designer must weigh these factors and develop a consistent set
of modulari2ation criteria to guide the design process .
,fficiency of the resulting implementation is a concern that frequently arises when
decomposing the system into modules.
14
Principles And Programming Languages Unit - I
)he preferred technique for optimi2ing the efficiency of a system is to be first design and
implement the system in a highly modular fashion.
System performance is than measured ,and bottlenecks are removed by reconfiguring and
recombining modules ,and by hand coding critical linkage and critical routine in assembly languages
if necessary .In these situations the modular source code should be retained as documentation for the
assembly language routines.
)he soundnessC of this technique is based on two observations .
1irst most software system spends a large portion of the code typically DEF or more of
e-ecution time is spent in .EF or less of the code.
)he region of code where the maority of time is spent is usually not predictable
until the program is not implemented and actual performance is measured
Second ,it is relatively easy to configure and recombine the small modules into larger units if
necessary for better performance <however failure to
DESIGN NOTATIONS
In software design, as in mathematics, the representation schemes are of fundamental importance.
Aood notation can clarify the inter relationships and interactions of interest, while poor notation
can complicate and interfere with good design practice.
)hree levels of design specifications e-ist*
,-ternal design specifications, which describe the e-ternal characteristics of a software
system
/rchitectural design specifications, which describe the structure of the system
&etailed design specifications, which describe control flow, data representation, and other
algorithmic details within the modules.
&esign representations are appropriate for use on more than one level of design,
while others are appropriate for only one level. @ecause the boundary between requirements analysis
and e-ternal is not well defined, some of the notations are also useful for e-ternal design.
=otations used to specify the e-ternal characteristics, architectural structure, and
processing details of a software system include data flow diagrams, structure charts, >IP# diagrams,
procedures specifications, pseudo code, structured ,nglish, and structured flowcharts.
Data F#ow Diagrams
&ata flow diagrams !@ubble 'hart%" are directed graphs in which the nodes specify processing
activities and the arcs specify data items transmitted between processing nodes.
:ike flow charts, data flow diagrams can be used at any desired level of abstraction.
/ data flow diagram might represent data flow between individual statements or blocks of
statements in a routine, data flow between sequential routines, data flow between concurrent
processes, or data flow in a distributed computing system where each node represent a
geographically remote processing units.
15
Principles And Programming Languages Unit - I
;nlike flow charts, diagrams do not indicate decision logic or conditions under which various
processing nodes in the diagrams might be activated.
&ata flow diagrams can be e-pressed using informal notations, or special symbols can be used to
denote processing nodes, data source data sinks, and data stores.
&ata flow diagrams are e-cellent mechanisms for communicating with customers during
requirements analyses< they are also widely used for representation of e-ternal and top-level
internal design specifications.
In the latter situations, data flow diagrams are quite valuable for establishing naming conventions
and names of system components such as subsystems, files, and data links.
Structure c!arts
Structure charts are used during architectural design to document hierarchical structure, parameters,
and interconnections in a system.
/ structure chart differs from a flowchart in two ways* a structure chart has no decision bo-es, and
the sequential ordering of tasks inherent in a flowchart can be suppressed in a structure chart.
)he structure of a hierarchical system can be specified using a structure chart as illustrated in fig. 6.
16
&raw 1ig 5.6 a and b in Page
+50 G 1rom 3ichard 1airly
+
.
/
0
1
2
3
8
I=P;)
&/)/
#;)P;)
&/)/
Principles And Programming Languages Unit - I
)he chart can be augmented with module-by-module specification of the input and output
parameters, as well as the input and output parameter attributes.
&uring architectural design the parameter attributes are abstract< they are refined into
concrete representation during detailed design.
HIP, Diagrams
>IP# diagrams !>ierarchy Gprocess-input-output" were developed at I@( as design representation
schemes for top-down software development, and as e-ternal documentation aids for released
products.
/ set of >IP# diagrams contains a visual table of contents, a set of overview diagrams, and a set of
detailed diagrams.
7isual table of contents
is a directory to the set of diagrams in the package
it consists of a treeGstructured !or graph-structured" directory, a summary of the
contents of each overview diagram , and a legend of symbols as represented in 1ig. 8.
)he visual table of contents is a styli2ed structured chart.
#verview diagrams
Specify the functional processes in a system.
,ach overview diagram describes the inputs, processing steps and output for the
function being specified.
/n overview diagram can specify several subordinate detail diagrams.
&etailed diagram have the same format as that of overview diagrams.
Procedura# .em#ate
P3#',&;3, =/(,
P/3) #1* ! Subsystem name $ number"
'/::,& @?*
P;3P#S,*
&,SIA=,3B&/),!s"
P/3/(,),3S !names, modes, attributes, purpose"
I=P;) /SS,3)I#=*! pre-condition"
#;)P;) /SS,3)I#=* !post-conditions"
A:#@/:S* ! names, modes, attributes, purpose, shared with"
SI&, ,11,')S*
:#'/: &/)/ S)3;');3,S* !names, attributes, purposes"
17
+
.
/
0
1
2
3
8
Fig. / Format of a Structure *!art
%e&er 'ig( 5(" in Page 155 )
Page 156
:,7,: - +
:,7,: - .
:,7,: - 0
Principles And Programming Languages Unit - I
,H',P)I#=S*! conditions, responses"
)I(I=A '#=S)3/I=)S*
#)>,3 :I(I)/)I#=S*
P3#',&;3, @#&?* !pseudo code, structured ,nglish, structured flowchart, decision table"
Fig. 0 Format of a rocedure tem#ate
)he format of procedural interface specification is as represented in fig. 8
In the early stages of architectural design only the information in level + will be supplied.
/s design progress the information on levels ., 0, 4 can be included in successive steps.
)he term side effects in the fig 8
(eans any effects a procedure can e-ert on the processing environment that is not evident
from the procedure name and parameters.
(odification to global variables, reading or writing a file, opening or closing a file, or calling
a procedure that in turn e-hibits side effects are all e-ample of side effects.
#nly information on level + in fig. 8 is provided during initial architectural design
Specification of side effects, e-ception handling, processing algorithms and concrete data
representation will sidetrack the designer into inappropriate levels of detail.
&uring detail design, the processing algorithms and data structures can be specified using structured
flowcharts, pseudo code or structured ,nglish.
Procedure interface specifications
/re effective notations for architectural design when used in combination with structure
charts and data flow diagrams.
)hey also provide a natural transition from architectural to detailed design, and from detailed
design to implementation.
)he procedure interface and pseudo code procedure body can be e-panded directly into
source code during product implementation.
Pseudo *ode
Pseudocode notation can be used in both the architectural and detailed design phases.
:ike flowcharts, pseducode can be used at any desired level of abstraction.
;sing pseudocode, the designer describes system characteristics using short, concise, ,nglish
language phrases that are structured by key words such as It-then-,lse, 9hile-&o, and ,nd.
Iey words and indentation describe the flow of control while the ,nglish phrases describe
processing actions.
;sing the top-down design strategy, each ,nglish phrase is e-panded into more detailed pseudocode
until the design specification reaches the level of detail of the implementation language.
1"
:,7,: - 4
Principles And Programming Languages Unit - I
Pseudocode can replace flowcharts and reduce the amount of e-ternal documentation required to
describe a system.
)he use of pseudocode for detailed design specification is illustrated below.
I=I)I/:IJ, tables and counter< #P,= files
3,/& the first te-t record
9>I:, there are more te-t records &#
9>I:, there are more words in the te-t record &#
,H)3/') the ne-t word
S,/3'> word Ktable for the e-tracted word
I1 the e-tracted word is found )>,=
I='3,(,=) the e-tracted wordCs occurrence count
,:S,
I=S,3) the e-tracted word into the word Ktable
,=&I1
I='3,(,=) the words processed counter
,=&9>I:, at the end of the te-t record
,=&9>I:, when all te-t records have been processed
P3I=) the word-table and words processed counter
':#S, files
),3(I=/), the program
Structured F#owc!arts
1lowcharts are the traditional means for specifying and documenting algorithm details in a software
system.
1lowcharts incorporate rectangular bo-es for actions, diamond shaped bo-es for decision, directed
arcs for specifying interconnections between bo-es, and a variety if specially shaped symbols to
denote input , output, data store, etc.
Structure flowcharts differ from traditional flowcharts
o Structured flowcharts are restricted to compositions of certain basics forms.
o )his makes the resulting flowchart the graphical equivalent of a structured pseduocode
description.
/ typical set of basic forms and the pseudocode equivalents are illustracted in the
below figure.
1#
*1
+
*2+
p
s
'
,
9>I:, P &#
S<
*
P
,
%!P!A, *
U-,IL P
Principles And Programming Languages Unit - I
)he basic forms are characteri2ed by single entry into and the single e-it from the form.
1orm can be nested within forms to any arbitrary depth, and in any arbitrary fashion.
/s the single entry, single e-it property is preserved.
Structure flowcharts are logically equivalent to pseudocode that they have the same e-pressive
power as pseudocode, where both can be used to e-press any conceivable algorithm.
Structured flowcharts may be preferred in situations where clarity of control flow is to be
emphasi2ed.
)he single entry, single e-it property allow hierarchical nested of structured flowchart constructed
to document a design in top-down fashion, starting with top level structure and proceeding through
detailed design .
Structure flowcharts emphasi2e flow of control mechanisms due to the graphical nature of the
visual image.
)hey are thus appropriate when decision mechanisms and sequencing of control flow are to be
emphasi2ed.
1lowcharts make it easy to violate the single entry, single e-it property, and they are not machine-
readable or machine-modifiable, as is pseudocode.
Structured 1ng#is!
Structured ,nglish can be used to provide a step-by-step specification for an algorithm.
:ike pseudocode, structured ,nglish can be used at any desired level of detail.
Structured ,nglish is often used to specify cookbook recipes*
+. Preheat oven to 05E degrees 1
.. (i- eggs, milk and vanilla
0. /dd flour and baking soda
4. Pour into a greased baking dish
5. 'ook until done.
Decision .ab#es
&ecision tables can be used to specify comple- decision logic in a high-level
software specification.
)hey are also useful for specifying algorithmic logic during detailed design.
2$
P
*1 *2
, '
I' P ,.!-
*1
!L*! *2
Principles And Programming Languages Unit - I
/t the level of detailed design usage of decision tables can be specified and
translated into source code logic.
Several preprocessor packages are available to translate decision tables into
'#@#:.
DESIGN TEC4NI5UES
&esign process involves
+. &eveloping a conceptual view of the system
.. ,stablishing system structure
0. Identifying data streams and data stores
4. &ecomposing high level functions into sub-functions
5. ,stablishing relationship and interconnections among components
6. &eveloping concrete data representations and specifying algorithmic details
&eveloping a conceptual view of a software system involves
&etermining the type of system to be built.
)he system may be a data-base system, a graphics system, a telecommunications system, a
process control system, or a data processing system< or the system may combine aspects of
different system types !e.g. a combined database, graphics, and real time system".
In each of these application areas there are certain viewpoints, terminology, tools, and
notations suitable to that class of applications.
It is essential that the software design team have a strong conceptual understanding of the
nature of the system to be constructed and be familiar with the tools and techniques in the
appropriate application areas.
It is not uncommon for a design team to be composed of one or more specialists from each
appropriate area.
/ data store is a conceptual data structure.
&uring e-ternal and architectural design, one way identify the need for a stack, queue, or file.
@ut the e-act implementation details of the data structure should be deferred until detailed
design.
&etailed design decisions should be delayed as long as possible.
,arly binding of design decisions, particularly in regard to representation details for data
structures, can result in a system structure that is difficult to modify during subsequent
development and maintenance activities.
&uring e-ternal and architectural design, data structures should be defined as data
abstractions, with emphasis placed on the desired operations and not on implementation
details.
&ata streams and data stores
21
Principles And Programming Languages Unit - I
)hese can be specified using data flow diagrams, data dictionaries, and data abstraction
techniques.
,-ternal data streams are identified during software requirements analysis and e-ternal
design< internal data streams and data stores are developed during architectural design.
&ecomposition of high-level functions can be initiated from data flow diagrams and often involves
use of structure diagrams, >IP# diagrams, and procedure specification.
Several techniques or design methodologies have been developed for software design.
+. stepwise refinement
.. levels of abstraction
0. structured design
4. integrated too-down development
5. Lackson design methods
)here are in fact viewpoints and guidelines for the design process.
Software design is a creative activity. / framework and a viewpoint are essential along with
all creation process.
&esign techniques are typically based on the top-down% andBor bottom-up% design strategies.
)op-down approach
In this approach attention is first focused on global aspects of the overall system.
/s the design progresses, the system is decomposed into subsystems and more consideration
is given to specific issues.
@acktracking is fundamental to top-down design.
/s design decisions are decomposed to more elementary levels, it may become apparent that a
high-level decision has led to inefficient or awkward decomposition of lower-level functions.
)hus, a high-level decision may have to be reconsidered and the system restructured
accordingly.
In order to minimi2e backtracking, many designers advocate a mi-ed strategy that is
predominately top-down, but involves specifying the lowest-level modules first.
)he primary advantage of the top-down strategy is that attention is first directed to the
customerCs needs, user interfaces, and the overall nature of the problem being solved.
@ottom-up approach
;sing this approach to design software, the designer first attempts to identify a set of primitive
obects, actions, and relationships that will provide a basis for problem solution.
>igher Glevel concepts are then formulated in terms of the primitives.
)he bottom-up strategy requires the designer to combine features provided by the
implementation language into more sophisticated entities.
)hese entities are combined in turn until a set of functions, data structures, and
interconnections has been constructed to solve the problem using elements available in the
actual programming environment.
22
Principles And Programming Languages Unit - I
@ottom-up design may also require redesign and design backtracking.
)he success of bottom-up design depends on identifying the proper% set of primitive ideas
sufficient to implement the system,
@ottom-up design and implementation permits assessment of subsystem performance during
system evolution.
9hen using top- down methods, performance evaluation must be deferred until the entire system is
assembled.
#n the other hand, top-down design and implementation permits only demonstration of
functional capabilities at the user level< dummy routines !program stubs" can be used to
simulate the lower, unimplemented levels of the system.
In practice, design of a software system is seldom, if ever, accomplished in pure top-down or pure
bottom-up fashion.
/ predominately top-down strategy is most successful when a well-defined environment e-ists for
software development.
,-ample, when writing a complier for use with a stable operating system, or when writing an
application program in a well-defined computer environment.
9hen the environment is ill-defined, as in the development of system software for a new
machine, the design strategy must, of mi-ed or predominately bottom-up.
Stewise refinement
Stepwise refinement is a top-down technique for decomposing a system from high-level
specifications into more elementary levels.
Stepwise refinement is also known as stepwise program development% and% successive
refinement%.
Stepwise refinement involves the following activities*
+. &ecomposing design decisions to elementary levels.
.. Isolating design aspects that are not truly interdependent.
0. Postponing decisions concerning representation details as long as possible.
4. 'arefully demonstrating that each successive step in the refinement process is a faithful
e-pansion of previous steps.
Incremental addition of detail at each step in the refinement process postpones design decisions as
long as possible and allows the designer to argue convincingly that the resulting software product is
consistent with the design specifications.
Stepwise refinement begins with the specifications derived during requirements analyses and
e-ternal design.
)he problem is first decomposed into a few maor processing steps that will demonstrably solve the
problem.
)he process is then repeated for each part of the system until it is decomposed in sufficient
detail so that implementation in a e-ecutable programming language is straight forward.
23
Principles And Programming Languages Unit - I
/n e-plicit representation technique is not prescribed in stepwise refinement.
;se of structure charts, procedure specifications, and pseudocode is consistent with successive
refinement.
)he early stages of refinement are typically stated in an informal pseudocode that becomes
more precise as the refinement proceeds.
)he resulting design is quite close to, and may actually incorporate, statements from the
implementation language.
Successive refinement can be used to perform detailed design of the
individual modules in a software product.
,-ample for successive refinement
/ routine is required to write the first = prime number into file 1.
= is a formal parameter in the routine, and 1 is globally known.
)he initial version of the routine
Initial version* procedure P3I(,!=* integer"<
7ar I,H* integer<
begin rewrite!1"< H *M +<
for I *M + to = do
begin H *M ne-t prime number%<
write!1,H"
end<
end NP3I(,O<
)he ne-t step is so refine the statement H *M ne-t prime number%< @y
introducing a @oolean variable, P3I(, the statement can be e-pressed as
3efinement +* repeat H *M P+<
P3I( *M - IS / P3I(, =;(@,3%
;ntil P3I(<
/ll prime numbers e-cept the first !which is ." are odd.
9e can treat . as a special case and increment H by . in the repeat loop.
3efinement .* begin rewrite!1"< H *M +<
If = QM + then write!1,."<
for I*M . to = do
begin
repeat H*M HP.<
P3I( *M%H is a prime number %
;ntil P3I(<
9rite!1,H"
end<
end<
24
Principles And Programming Languages Unit - I
)he ne-t refinement involves determining whether H is a prime number.
H is prime if it is divisible only by + and itself with 2ero remainder.
3efinement 0* repeat H *MHP.< I *M.<
3epeat
I *MI P +<
P3I( *M%H is not divisible by I %
;ntil not !P3I(" or !I M H-+"
;ntil P3I(<
)he remainder function ,mod can be used to determine whether H is divisible
by I*
3efinement 4* P3I( * M !H mod I " M E<
#ur procedure now has the following structure *
Procedure P3I(, !=*integer"<
7ar I,H,I* integer<
P3I( * @oolean<
@egin rewrite !1"< H * M+<
If =QM+ then write !1,."<
1or I * M . to = do
@egin
3epeat H* M H P .< I * M .<
3epeat I* M I P +<
P3I( * M !H mod I " M E <
until not !P3I(" or !k M H-+ "<
until P3I( <
9rite !1,H"
end
end <
)he procedure for computing the first = prime numbers and writing them in file 1 is complete.
It is demonstrably correct because each refinement follows logically from the previous
version.
It is complete because each pseudocode statement has been refined into e-ecutable source
code.
>owever, the efficiency of the program can be vastly improved in several ways.
1or e-ample
it is not necessary to check H for divisibility by every number I between 0
and H G +.
3ecall that every non prime numbers can be e-pressed as the product of prime
factors.
25
Principles And Programming Languages Unit - I
If - is divisible by a nonprime number k, it is also divisible by the prime
factors of k.
)hus keep the prime numbers already calculated in an array p, and only check
- for divisibility by the elements of p.
)his result in
3efinement 5* H* M+< P R+S*M.< :I(* M+<
1or I* M. to = do
@egin
3epeat H* M HP.< k* M.< P3I(* Mtrue<
9hile P3I( and !k T :I(" do
@egin
Prim* M !H mod PRkS TQE<
I* M IP+<
,nd<
;ntil P3I(<
P RIS*M H< :I(* M :I(P+<
,nd<
,nd<
#ur approach is to first develop an obviously correct Program and then modify it to improve
efficiency.
)he maor benefits of stepwise refinement as a design technique are*
+. )op-down decomposition
.. Incremental addition of detail
0. Postponement of design decisions
4. 'ontinual verification of consistency !formally or informally"
;sing stepwise refinement, a problem is segmented into small, manageable pieces, and the amount
of detail that must be dealt with at any particular time is minimi2ed.
In the manner, the designerCs thought processes are channeled to the proper concerns at the proper
time.
It must be observed, however, that successive refinement is not so much a design technique as a
general approach to problem solving.
Success with the method is highly dependent on having a clear conceptual understanding of the
desired solution, and on the ability of the designer.
2e3e#s of abstraction
:evels of abstraction is originally described as a bottom-up design technique in which an operating
system was designed as a layering of hierarchical
26
Principles And Programming Languages Unit - I
levels starting at level E !processor allocation, real-time clock interrupts" and building up to level of
processing independent user programs.
,ach level of abstraction is composed of a group of related function, some of which are e-ternally
visible !can be invoked by functions on higher levels of abstaction " and some of which are internal
to the level.
Internal functions are hidden from other levels
)hey can only be invoked by functions on the same level.
)he internal functions are used to perform tasks common to the work being performed on
that level of abstraction.
1unctions on higher levels cannot be used by functions on lower levels.
1unction usage establishes the levels of abstraction.
,ach level of abstraction performs a set of services for the functions on the ne-t
higher level of abstraction.
,-ample, a file manipulation system might be layered as a set of routines to
manipulate fields ! bit vectors on level E" , a set of routines to manipulate records ! sets of fields on
level +" , and a set of routines to manipulate files ! sets of records on level . ".
,ach level of abstraction has e-clusive use of certain resources ! IB# devices ,
data structures" that other levels are not permitted to access .
>igher Glevel functions can invoke functions on lower level , but lower Glevel
functions cannot invoke or in any way make use of higher-level functions . )his latter restriction is
important because lower levels are then self G sufficient for supporting other abstractions .
)he lower levels can be used without change as the lower-level routines in other
applications, or in adaptations and modifications to an e-isting system.
)he strict hierarchical ordering of routines facilities intellectual manageability%
of a comple- software system. )he levels of abstraction utili2ed in the ).>.,. operating system are
listed in )able below
T6)e. Le%e)$ of 6$t!,tion in the T.4.E. o7e!ting $*$tem
:evel E* Processor allocation
clock interrupt handling
:evel +* (emory segment controller
:evel .* 'onsole message interpreter
:evel 0* IB# buffering
:evel 4* ;ser programs
:evel 5* #perator
27
Principles And Programming Languages Unit - I
St!#,t#!e+ De$ign
Structured design was developed by 'onstantine as a top-down technique for architectural design of
software systems.
)he basic approach in structured design is systematic conversion of data flow diagrams into structure
charts.
&esign heuristics such as coupling and cohesion are used to guide the design process.
'oupling measures the degree to which two distinct modules are bound together, and cohesion is a
measure of the relationship of elements within a module to one another.
/ well G designed system e-hibits a low degree of coupling between modules and a high degree of
cohesion among elements in each module.
)he first step in structured design is review and refinement of the data flow diagrams developed
during requirement definition and e-ternal design.
)he second step is to determine whether the system is transform-centered or transaction-driven to
derive a high-level structure chart based on this determination.
In a transform-centered system the data flow diagram contains Input, Processing, and #utput
segments that are converted into Input, Processing, and #utput subsystem in the structure
chart.
@oundaries between the three maor subsystems in a transform-centered system are identified
by determining the point of most abstract input data and the point of most abstract output data
on the data flow diagram.
)he situation is pointed out in the below 1igure U.
)he point of most abstract is
Input data is the point in the data flow diagram where the input stream can no longer be
identified.
Similarly, the point of most abstract, output data is the point in the data flow diagram where
components of the output data stream can first be identified.
Identification of these boundaries is somewhat obective, but with practice the designers
become consistent in identifying them.
)he third step in structured design is decomposition of each subsystem using guidelines such as
coupling, cohesion, information hiding, levels of abstraction, data abstraction, and the other
decomposition criteria.
/ hierarchical tree structure is the solution form that usually results in the lowest cost
implementation !where cost refers to the cost of designing, coding, testing, modifying and
maintaining the system".
2"
&raw 1ig 5.+4 in Page +6D G
1rom 3ichard 1airly
Principles And Programming Languages Unit - I
&ecomposition of processing functions into modules should be continued until each module contains
no subset of elements that can be used alone, and until each module is small enough that its entire
implementation can be grasped at once.
In the initial design phase one should sub-divide too finely because small modules can be easily
recombined at a later time.
In addition to cohesion, coupling, data abstraction, information hiding, the other decomposition
criteria, the concepts of Scope of ,ffects% and Scope of 'ontrol% can be used to determine the
relative positions of modules in a hierarchical framework.
Scope of control
Scope of control of a module is that module plus all the modules that are subordinate to it in
the structured chart.
In the below e-ample from figure +E the scope of control of module @ is @, & and ,.
Scope of effects
Scope of effect of a decision is the set of all modules that contain code that is e-ecuted based
on the outcome of that decision.
In general systems are more loosely coupled when the scope of effect of a decision is within the
scope of control of the module containing the decision.
Illustration using figure +E.
Suppose e-ecution of some source code in module @ depends on the outcome of decision, H
in module ,.
,ither , will return a control flag to @ or the decision process will have to be repeated in @.
)he former approach requires additional code to implement the flag and results in control
coupling between @ and ,.
)he latter approach requires duplication of some of ,Cs code !decision process H" in module
@.
&uplication of code is inefficient and causes difficulties in coordination changes to both
copies.
)he situation can be remedied by modifying the system so that the scope of effect of
decision H is within its scope of control.
(oving the decision process upward into @ or moving the code in @ affected by the
decision into , !or into a routine subordinate to ," will produce the desired effect.
)he primary benefits of structured design are
+. )he use of data flow diagrams focuses attention on the problem structure. )his naturally
follows from requirements analysis and e-ternal design.
.. )he method of translating data flow diagram into structure charts provides a method for
initiating architectural design in a systematic manner.
2#
1igure +E - &raw 1ig 5.+5 in Page
+6U G 1rom 3ichard 1airly
Principles And Programming Languages Unit - I
0. &ata dictionaries can be used in conunction with structure charts to specify data attributes
and data relationships.
4. &esign heuristics such as coupling and cohesion, and scope of effect and scope of control
provide criteria for systematic development of architectural structure and for comparison of
alternatives design structures.
5. &etailed design techniques and notations such as successive refinement, >IP# diagrams,
procedure specification forms, and pseudocode can be used to perform detailed design of the
individual modules.
)he primary strength of structured design is a provision of systematic method for converting data
flow diagram into top-level structured charts.
)his method does not provide much guidelines for decomposing top-level structured charts
into detailed structures.
)he primary disadvantage of structured design is that the technique produces systems that are
structured as sequences of processing steps.
&ecomposing a system into processing steps is inconsistent with the design criterion of
information hiding.
&isregard for information hiding and separation of concerns may result in a system that is
difficult to modify.
Integrated .o&Down De3e#oment
Integrated top-down development integrates design, implementation, and testing.
;sing integrated top-down development, design proceeds top-down from the highest-level routines.
)hey have the primary function of coordinating and sequencing the lower-level routines.
:ower-level routines may be implementations of elementary function !those that call no other
routines", or they may in turn invoke more primitive routines.
)hus a hierarchical structure to a top-down system in which routines can invoke lower-level
routines but cannot invoke routines on a higher level.
)he integration of design, implementation, and testing is illustrated by the following e-ample.
S)3/),A?* &,SIA= (/I=
'#&, (/I=
S);@S 1#3 A,), P3#',SS, P;)
),S) (/I=
&,SIA= A,)
'#&, A,)
),S) (/I= A,)
3$
Principles And Programming Languages Unit - I
&,SIA= P3#',SS
'#&, P3#',SS
S);@S 1#3 S;@+,S;@.
),S) (/I= A,), P3#',SS
&,SIA= P;)
'#&, P;)
),S) (/I=, A,), P3#',SS, P;)
&,SIA= S;@+
'#&, S;@+
),S) (/I=, A,), P3#',SS, P;), S;@+
&,SIA= S;@.
'#&, S;@.
),S) (/I=, A,), P3#',SS, P;), S;@+, S;@.
Figure '' Integrated to&down de3e#oment strategy.
)he purpose of procedure (/I= is to coordinate and sequence the A,), P3#',SS, and
P;) routines.
)hese three routines can communicate only through (/I=< similarly, S;@+ and S;@.
!which support P3#',SS",can communicate only through P3#',SS.
)he stubs referred to in 1igure ++.are dummy routines written to simulate sub-functions that are
invoked higher-level function.
Stubs can fulfill a number of useful purposes prior to e-pansion into full functionality.
)hey can provide output messages, test input parameters, deliver simulated output
parameters, and simulate timing requirements and resource utili2ation.
;se of program stubs in top-down development provides an operational prototype of the
system as development progresses.
Some designers restrict data communication between modules to the parameters lists, while other
designers allow global variables that are common to two or more modules.
/ reasonable compromise is to communicate data between levels via parameters lists and to permits
access to common global data by modules on the same level of hierarchical.
)he technique provides an orderly and systematic framework for software developed.
&esign and coding are integrated because e-pansion of a stub will typically require creation
of new stubs to support it.
/dvantage
&istribution of system integration across the proect, interfaces are established, coded $
tested as the design progress.
&isadvantage
31
Principles And Programming Languages Unit - I
,arly high-level design decisions may have to be reconsidered when the design progresses to
lower level.
)his may require design backtracking and considerable rewriting of code.
#ther disadvantages is to integrated top-down development
)he system may be a very e-pensive test harness for newly added procedure
It may not be possible to find high-level test data to e-ercise newly added procedure
in the desired manner.
It may be necessary to first write and test some low-level procedures before
proceeding top-down development.
4ac)son Structured Programming.
Lackson structured programming was developed by (ichael Lackson as a systematic technique for
mapping the structure of a program into a structure to solve the problem.
)he mapping is accomplished in three steps*
+. )he problem is modeled by specifying the input and output data structures using tree
structured diagrams.
.. )he input-output model is converted into a structural model for the program by
indentifying points of corresponds between nodes in the input and output trees.
0. )he structural model of the program is e-panded into a detailed designed model that
contains the operations needed to solve the problem.
Input and output structures are specified using a graphical notation to specify data hierarchy,
sequences of data, repetition of data items, and alternate data items.
Specification of data item is illustrated in 1ig.+..
/ccording to this notation , item / consists of a @ followed by a ' followed by a &!reading
left to right on same level".
@ and & have no substructures. ' consists of either an , or an 1 !denoted by %#%".
, consists of 2ero or more occurrencesC of A!denoted by V%", and 1 consists of an >
followed by an I .
)his notation is the graphical equivalent of regular e-pression.
)his formats of input and output data structures are thus specified using graphical
representations of regular grammars.
)he second step of Lackson method involves converting the input $ output structures into structured
model of the program.
:abels on the data items is the resulting structure are converted to process names that
performs the required processing of the data items.
)he third step e-pands the structural model of the program into a detailed design containing
operations needed to solve the problem.
32
1igure ++ - &raw 1ig 5..E in Page
+85 G 1rom 3ichard 1airly
Principles And Programming Languages Unit - I
)his performed in three steps
+. / list of operations required to perform the processing steps is developed.
.. )he operations are associated with the program structure.
3( Program structure and operations are e-pressed in a notation called schematic logic,
which is styli2ed pseudocode. 'ontrol 1low for selection and iteration are specified in
this step.
)he following e-ample illustrates the basic concept of Lackson (ethod.
/ input file consists of a collection of inventory records sorted by part number.
,ach record contains a part number and the number of units of that item issued or received in
one transaction.
/n output report is to be produced that contains a heading and a net movement line for each
part number in the input file.
)he input file is sorted by part number, all issues and receipts of a given part number are in a
contiguous portion of the file called a part group.
,ach record in a part group is called a movement record.
Figure '2 inut and outut structure for an in3entory rob#em
)he input $ output structure are illustrated in figure +..
)he input file consists of 2ero or more part groups.
,ach part group consists of 2ero or more movement records.
/ movement record is either an issue record or a receipt record.
)he output report consists of a heading followed by a body !reading left to right on the same
level".
)he body consists of 2ero or more net movement lines.
)he corresponding between input and output structures is illustrated in figure +0.
)he input file corresponds to the output report, and each part group in the input file
corresponding to a net movement line in the output report.
)he program structure is derived by superimposing the input file structure on the output
report structure and overlaying the corresponding nodes in the two graphs.
33
Principles And Programming Languages Unit - I
Figure '3 corresondences between inut and t!e outut structure for an in3entory rob#em
)he resulting program structure is illustrated in figure +4.
FI5 '$ Program structure for an in3entory rob#em
)he program consists of a number of processing steps.
)here is a processing step to write the report heading, followed by a step to write the report
body.
)he body consists of repetitive invocation of P)AP $ line !part group and line", one
invocation per part group in the input file. P)AP $ line contains a processing step for a part
group followed by a step to print the net movement line for that part group.
)he part group body consist of a processing step that is invoked once for each part record in
the group. ,ach invocation of process record processes an issue or a receipt.
&etailed design involves developing a list of operations needed in the program, associating
the operations with program structure, and translating the annotated structure diagram into
schematic logic !pseudo code".
34
Program
Process
heading
Process
body
Process
PTGP
line
Proces
s line
Proces
s
record
Proces
s issue
Process
receipt
Process
PTGP
body
Principles And Programming Languages Unit - I
)hese steps are illustrated in fig +5.
+. #P,= 1I:,S
.. ':#S, 1I:,S
0. S)#P 3;=
4. 3,/& / 3,'#3& I=)# P/3)K=;(,(#7(=)
5. 93I), >,/&I=A
6. 93I), =,)K(#7(=) :I=,
8. S,) =,)K(#7(=) )# =,) (#7(=)
D. S;@)3/') (#7(=) 13#( =,)K(#7(=)
Figure '6 (a) ,erations needed in t!e in3entory rogram
@,AI= P3#A3/(
#P,= 1I:,S
3,/& P/3) G=;( (#7(=)
93I), >,/&I=A
I),3/), 9>I:, =#)!,=&-#1-:I1,"
S,) =,)-(#7(=) )# J,3#
I),3/), 9>I:, S/(,-P/3)-=;(@,3
I1!(#7(=)MISS;,")>,=
S;@)3/') (#7(=) 13#( =,)-(#7(=)
,:S, I1!(#7(=)M3,',IP)" )>,=
/&& (#7(=) )# =,)- (#7(=)
,=& I1
3,/& P/3) G=;( ,(#7(=)
,=& 9>I:,
93I), =,)-(#7(=) :I=,
,=& 9>I:,
':#S, 1I:,S
S)#P
,=& P3#A3/(
Figure '6 (*) Sc!ematic #ogic reresentation of an in3entory rogram
&ifficulties encountered in applying the Lackson method include structure clashes and the need for
look-ahead.
Structure clashes occur when points of commonality between input and output data structures
cannot be identified.
Structure clashes can be resolved by a technique called program inversion.
;sing program inversion,
/ consumer routine calls on a producer routine to deliver the ne-t required data item.
35
'igure 15 /01 2 re&er
page 17" 3g( 5(25
Principles And Programming Languages Unit - I
)he producer delivers values to the consumer on a demand basis, and, to the
consumer, it appears as if the values are being produced from a sequential file of
values.
Implementation of program inversion can be accomplished using a co routine
structure for the producer and consumer.
)he need for look-ahead arises when processing of a data item depends on some
characteristics of yet-to-be-processed data.
)his situation can occur, for e-ample, when a set of data records is to be treated as bad data if
any record in the set is bad< otherwise, each record is processed as good data.
:ook-ahead problems can be resolved by a technique called backtracking, which involves
saving the program state at the beginning of each processing sequence that may be incorrect.
If it is determined that a processing sequence is incorrect, the program state is reset to the
state prior to entry of that processing sequence and an alternative processing sequence is
invoked.
(ore recently, (ichael Lackson has developed a method for software design called the Lackson design
method which involves modeling the real world phenomenon of interest as a network of sequential
processes that communicate using serial data stream.
.Lackson structured programming is widely used and is quite effective in situations input and output
data structure can be defined in prWcised manner.
TEST PLANS
)he test plan is an important, but often ignored, product of software design.
It prescribes various kinds of activities that will be performed to demonstrate that the software product
meets it requirements.
)he test plan specifies the obective of testing !eg.., to achieve error-free operation under stated
conditions for a stated period of time" ,the test completion criteria !to achieve a specified rate of error
e-posure ,to achieve a specified percent of logical path coverage", the system integration plan !strategy
,schedule ,responsible individuals" ,methods to be used on particular modules !walkthrough
,inspections, static analysis ,dynamic test, formal verification",and the particular test cases to be used.
)here are four types of test that software must satisfy*
functional test,
performance test,
stress test. 1unctions test
performance test
)hese tests are based on the requirements specifications< they are designed to
demonstrate that the system satisfies the requirements, which in turn must be phased in,
quantified, testable terms.
Functional test cases
specifies typical operating conditions ,typical input values , and typical e-pected results .
36
Principles And Programming Languages Unit - I
1unctional test should also be designed to test boundary conditions ust inside and ust beyond
the boundaries!eg., square root of negative numbers ,inversions of one-by-one matrices".
/lso ,special values, such as files and array containing identical values, the identity matri-, the
2ero matri-,etc<., should be tested .
/ssumed initial values and system default should be tested with data that have both correct and
incorrect ordering.
Performance test
&esigned to verify response time!under various loads" ,e-ecutive time ,throughput ,primary and
secondary memory utili2ation ,and traffic rates on data channels and communications links.
Performance test will often indicate processing bottlenecks to be addressed during system
testing and turning.
,ach functional test and performance test should specify the machine configuration ,assumptions
concerning the system status for the test case ,the requirements being tested the test inputs ,and the
e-pected test results .
It is particularly important that the e-pected results of each test should specified prior to system
implementation and actual testing .#therwise ,it is easy to rationali2e an incorrect result.
Stress tests
&esigned to overload a system in various ways, such as attempting to sign on more than the
ma-imum allowed number of terminals, processing more than the allowed n umber of
identifiers or static levels or disconnecting a communication link.
)he purpose of this testing are to determine the limitation of the system and when the system
fails, to determine the manner in which the failure is manifest.
)his test provides a valuable insight concerning the strength and weakness of a system.
Structural tests
'oncerned with e-amining he internal processing logic of a software system.
)he particular routines called and the logical paths transverse through the routines are the
obect.
)he main goal is to transverse a specified number of paths through each routine in the system
to establish thoroughness of testing.
1unctional, performance and stress tests are recommended to be implemented on system and to
argument these tests with additional structure tests to achieve the desired level of test coverage.
Structured test cannot be designed until the system is implemented and subected to the predefined test
plan.
DESIGN GUIDELINES
&esign is a creative process that can be guided and directed, but it can never be reduced to an
algorithmic procedure.
37
Principles And Programming Languages Unit - I
)he design of a real-time system is a much different activity than the design of a data processing
application.
)he following guidelines do not constitute a design methodology,% but rather provide some
guidance for organi2ing the activities of software design.
+. 3eview the requirements specification. In particular, study the desired functional
characteristics and performance attributes of the system.
.. 3eview and e-pand the e-ternal interfaces, user dialogues, and report formats developed
during requirements analysis.
0. 3eview and refine the data flow diagrams developed during requirements analysis and
e-ternal design. Identify internal data stores and elaborate the processing functions.
4. Identify functional abstractions and data abstractions. 3ecord them using a design notation.
5. &efine the visible interfaces for each functional abstraction and each data abstraction. 3ecord
them using a design notation.
6. &efine the modulari2ation criteria to be used in establishing system structure.
8. /pply the techniques of your particular design method to establish system structure. 1or
e-ample, derive the input and output data structures and convert the data structures into a
processing structure that ma-imi2es information hiding, or a structure that enhances the
overlay capabilities or real-time response rate, etc.
D. 7erify that the resulting system structure satisfies the requirements.
U. &evelop interface specifications for the procedures in each module.
+E. 'onduct the preliminary design review. )he level of detail should be inclusive to levels + and
. of the procedure templates
++. &evelop concrete data representations for the data stores and data abstractions.
+.. ,-pand the procedure templates to include the information in level 0.
+0. Specify algorithmic details for the body of each procedure in the system, using successive
refinement, >IP# diagrams, pseudo code, structured ,nglish, andBor structured flowcharts.
&evelop concrete data structures and algorithms.
+4. 'onduct the critical design review.
+5. 3edesign as necessary.
)he maor difficulties in software design are caused by inadequate requirements, failure to consider
alternative design strategies, and the temptation to provide too much detail too soon.
/ great deal of iteration among the various possibilities for solutions improves.
)he uses of systematic design notations will greatly enhance your thought processes and improve
your ability to think about, communicate, and verify the design.
IMPLEMNTATION ISSUES
INTRODUCTION
Implementation phase of software development is concerned with translating design specification
into source code.
)he primary goal of implementation is to write source code and internal documentation so that
conformance of the code to its specifications can be easily verified, and so that debugging, testing,
and modification are eased.
3"
Principles And Programming Languages Unit - I
)he primary goal can be achieved by making the source code as clear and straightforward as
possible.
Simplicity, clarity, and elegance which are the hallmarks of good programs.
Source-code clarity is enhanced by structured coding techniques, by good coding style, by
appropriate supporting documents, by good internal comments, and by the features provided in
modern programming languages.
Production of high-quality software
3equires that the programming team have a designated leader
/ well-defined organi2ational structure
/ thorough understanding of the duties and responsibilities of each team member.
Implementation team
Should be provided with a well-defined set of software requirements, an architectural design
specification, and a detailed design description.
,ach team member must understand the obectives of implementation.
&ifferent implementation goals for the same program* minimi2e the required ma-imi2e
output readability, ma-imi2e source te-t readability, minimi2e the number of source
statements, and minimi2e development time.
It is clear that each programmer achieved the desired obective and ranked high on related
obectives.
1or e-ample,
o )he programmer who minimi2ed memory ranked second in minimi2ing the
number of source statements.
o )he programmer who ma-imi2ed output readability ranked second in source-
code readability.
o (ost programmers will strive to achieve the stated obectives, provided those
obectives are well understood.
STRUCTURED CODING TEC4NI5UES
)he goal of structured coding is to liner arise control flow through a computer program so that the
e-ecution sequence follows the sequence in which the code is written.
)his enhances readability of code, which eases understanding, debugging, testing, documentation,
and modification of programs.
It also facilitates formal verification of programs.
:inear flow of control can be achieved by restricting the set of allowed program constructs to single
entry, single e-it formats
Strict adherence to nested, single entry, single e-it constructs leads to distort efficiency and this leads
to the violations of single entry, single e-it.
3#
Principles And Programming Languages Unit - I
'ertain issues regarding single entry and single e-it are discussed below.
Sing#e 1ntry7 Sing#e 18it *onstructs
Set of constructs for describing the control flow of every conceivable algorithms
Sequencing
,g. Sequencing * S+< S.< S0<
Selection among alternative actions
,g. Selection * if @ then S+ else S.<
Iterations
,g. Iteration * while @ do S<
)he single entry, single e-it nature of the constructs is represented below
)he single entry, single e-it property permits nesting of constructs within one another in any
desirable fashion
,ach statement Si might be an assignment statement, a procedure call, an if-then-else, or
while-do.
Statements of the latter forms may in turn contain nested statements.
)he most important aspects of single entry, single e-it property is that linearity of control flow is
retained, even with arbitrarily deep nesting of constructs.
,g. 'ontrol flow constructs illustrated in Pascal
'ig( # /a1 i& B t4en else
'ig( # /01 i& B t4en *1 else *2+
'ig( # /c1
case1 o&
a5*1+
05*2+
6((+
4$
'ig( # - %e&er 'ig( 6(2 in Page 1#4
Principles And Programming Languages Unit - I
n5 *n+
end case+
'ig( # /d1 74ile B do *
'ig( # /e1 repeat * until B
'ig( # /&1 &or1589 to /do:n to1 - do
'ig( # /g1 &unction call5 'ig( # /41 procedure call5
/ for% loop can be e-pressed as a sequence of the form
SE<
9hile @ loop
S+<
S.<
,nd loop<
9here SE initiali2es the loop variable, @ tests the limits, and S. increments or
decrements the loop variables.
S+ is the loop body
41
Principles And Programming Languages Unit - I
)he total set of constructs provided by Pascal and other modern programming languages offers
increased notational convenience, increased readability and in some cases, increased efficiency.
)he set of structured constructs selected for use in any particular application is primarily a matter of
notational convenience.
)he selected constructs should be conceptually simple and widely applicable in practice.
1fficiency *onsideration
'riteria of strict adherence to single entry, single e-it construct results in inefficient use of memory
space $ e-ecution time.
)o avoid the above said inefficiencies there is a need for au-iliary variables, repeated segments of
codes $ e-cessive subprogram calls are often cited.
,g. @elow illustrates the need for au-iliary variables in a search loop on a linked list. )he search is
on a linked list for value H
P *M :<
9hile !P XM null" and !P.7al XM H" loop
P *M P.:I=I<
,nd loop<
If ! P XM null" then
--- code for H in list<
else
--- code for H not in list<
end if<
P is a pointer variable, : is the :inked :ist, H is the value to be searched.
#n loop e-it P will contain the address of the memory cell that contain H provided H
is in the list.
:oop e-it also occurs when P.7al M H
42
null
.
.
: 7/: :I=I
: null
/n ,mpty :ist* : M null
Principles And Programming Languages Unit - I
(any language translators evaluate all relational e-pression in a @oolean operation
before performing the @oolean operation.
H is searched in the whole :ist one by one till the end of the :ist. If H is not found in
the pointer !P" location of the :ist then the pointer is transferred to the ne-t position in the :ist
!P* M P.:ink" till the end of the :ist. If H is not in the :ist P is assigned a null value when end
of the list is encountered.
'ontrol is transferred to the start of the loop, $ the test evaluates the relational
e-pressions !P* M null" and !P.7al*M H" before applying the /=& operation.
If the P value is null then P.7al is undefined. )o avoid this problem language
translator evaluate relational e-pressions in left-right fashions.
If the left most operand /=& is false the entire /=& must be false. So that
the rightmost operand need not be evaluated.
)he above e-ample will e-ecute correctly< otherwise an e-ception will occur. )o avoid this e-ception
occurrence /da programming language provides and-then and or-else @oolean operators for these
situations. )hese operations are called short-circuit conditions%.
,g.
9hile !P XM null" and then !P.7al XM H" :oop
P *M P.:ink<
,nd :oop<
If a language standard does not specify the way in which @oolean e-pressions are to be evaluated as
in the case of Pascal different translators will handle the situation according to the view points of
different language implementers.
/n obvious% solution to the above problem is to use a goto statement for premature loop e-it $ to
handle alternative action of loop e-it.
9hile !P XM null" loop
If !P.7al M H" then go to :+<
P *M P.:I=I<
,nd loop<
TT:+QQ If ! P XM null" then
--- code for H in list<
else
--- code for H not in list<
end if<
@elow are three alternative structure solutions for the search loop. ,ach solution requires an
au-iliary variable to achieve the same effect as the goto solution.
P *M :<
Y *M null<
9hile !P XM null" loop
If !P.7al M H" then Y *M P<
P *M P.:ink<
,nd loop<
43
Principles And Programming Languages Unit - I
If !Y XM null" then
---code for H in :ist<
,lse
---code for H not in :ist<
,nd if<
(a) Au8i#iary ointer so#ution
Y records the location of H in the :ist. #n loop e-it Y will point to the last occurrence of Y in the list
provided H is in the list otherwise, null.
Inefficient if multiple occurrence of H e-ists in the :ist, even if the +
st
occurrence of - is acceptable
then also the entire list should be checked even though the :ist is very long.
If last occurrence of H is required then solution !a" is correct.
1or the first occurrence of H can to be found by modifying the loop test as below for !a"
P *M :<
Y *M null<
9hile !P XM null" and !Y M null" loop
If !P.7al M H" then Y *M P<
P *M P.:ink<
,nd loop<
If !Y XM null" then
---code for H in :ist<
,lse
---code for H not in :ist<
,nd if<
Solution !b" uses a @oolean variable !a flag" to trigger loop e-it when the first occurrence of H is
located.
if H is in the list, 1#;=& will be true on loop e-it $ P will point the
location of the first occurrence of H.
If H is not in the :ist 1#;=& will be false $ P will be null on e-it.
P *M :<
1#;=& *M false<
9hile !P XM null" and !1#;=& M false" loop
If !P.7al M H" then 1#;=& *M true<
,lse P *M P.:ink<
,nd loop<
If !P XM null" then
---code for H in :ist<
,lse
---code for H not in :ist<
44
Principles And Programming Languages Unit - I
,nd if<
(b) Au8i#iary f#ag 3ariab#e
Solution !c" assumes that the total no. of nodes in the list = is known. >ere an integer counter I is
used to count the number of nodes visited for search H in the list.
P *M :<
I *M +<
9hile !I TM =" loop
If !P.7al XM H" then
P *M P.:ink<
I *M I P +<
,nd loop<
If !P XM null" then
---code for H in :ist<
,lse
---code for H not in :ist<
,nd if<
( c ) %ode&*ount So#ution
#n e-it, P will point to the last occurrence of an H in the list, otherwise P
will be null on e-it.
)his solution ! c " is not desirable because it is inconvenient to maintain the
total node count = in dynamic :ist processing.
)he refinement over the problems encountered in this e-ample can be avoided by slight change in
the data structure.
P *M :<
9hile !P.:ink XM null" and !P.7al XM H" loop
P *M P.:ink<
,nd loop<
If !P.7al M null" then
---code for H in :ist<
,lse
---code for H not in :ist<
,nd if<
45
null
.
.
: 7/: :I=I
null
/n empty list* :. :ink M null
Principles And Programming Languages Unit - I
Fig. 2in)ed wit! Header %ode
/dding a header node : to the list is represented below which permits the above search algorithm.
'hange of loop test P.:ink XM null, rather than P XM null.
/n empty set is denoted by :.:ink M null.
)he search algorithm requires that the value field of the header node :.val not equal to H for any
permissible H.
If the list is empty, P.:ink is null on loop entry and control will fall through the loop. >ere P equals to
: on loop e-it, if H is in the loop and P will point to the location of the +
st
H on loop e-it.
P will point to the last node on the list on loop e-it where H may or not contained in the list.
)he current modification in coding structure illustrates three important points about structured
coding.
+. (ost important structured coding practices give no guidance in the design $ method
access to data representations.
.. Structure coding is a technique for lineari2ing control flow !'arefully thinking about data
representation $ data access techniques will erase arise of difficult situations".
0. It may not be possible to design a data structure that will satisfy all requirements in an
optimal manner.
/nother maor concern about efficiency in structured coding is the need to
represent segments of codes or alternatively, to place a code segment in a sub program and call it
repeatedly. #therwise the single entry, single e-it rule must be violated.
,g. four versions of code segments are represented below
a) If&t!en&e#se so#ution
if P then /< @<
else @<
,nd if<
9hile Y loop
/< @<
,nd loop<
b) if&t!en so#ution
if P then /< end if<
@<
9hile Y loop
/< @<
,nd loop<
46
Principles And Programming Languages Unit - I
c) goto so#ution
d) Aternati3e goto so#ution
if P the TT:+QQ /<
end if<
@<
If Y then goto :+<
!a" adheres to three basic constructs with repeated subprogram calls.
!b" uses if-then construct to reduce the no. of repeated code segments.
!c " $ !d" use goto statements to completely eliminate repeated code
segments.
It is sometimes true that efficiency consideration is required as represented above
!eg. (icroprocessors with limited memory $ real-time processing constraints".
In order to address efficiency consideration when using single entry $ single e-it
constructs the following strategy is advised as in !b".
Place the repeated code segments in subprograms and invoke them as needed or
repeat them perhaps using macros, include facility.
9hen the system or a maor subsystem becomes operational, measure the
percentage of e-ecution time spent in various regions of code ! typically a large F of e-ecution time
spent in a small region of the code".
Identify few code segments that are candidate for performance enhancement.
If this is done, use both internal and e-ternal documentation to e-plain
why the code is written in this manner to aid understanding of an otherwise obscure code
segments.
'ritical regions of code can be collapsed together for efficiency purpose $
the remaining code will retain a clear and understandable structure.
+io#ations of sing#e entry7 sing#e e8it
Aoal of structured coding is to improve the clarity $ readability of source program.
'larity is greatly enhanced by use of single entry, single e-it constructs.
)here are commonly occurring situations which warrant violations of strict adherence to single entry,
single e-it. @ut, yet there are consistent with the goal of improved clarity.
)hree commonly occurring situations are
+. (ultiple loop e-ists
.. ,rror handling
0. &ata encapsulation
A. Multiple loops exists
It is used to have several different conditions for termination of a loop.
47
Principles And Programming Languages Unit - I
)he best procedure for dealing with multiple loop e-its is to redesign the algorithm so
that, multiple loops are not required.
If avoiding multiple loops are not possible, one technique for achieving multiple loop
e-its is to introduce a @oolean flag variable for each condition and test flags on each iteration of the
loop. ,-ample when 1ig.. is compared with 1ig.+
Fig. ' Fig. 2
P*M :<
Y*Mnull<
9hile !PXM null" loop
If !P.7/: M H" then Y*MP<
P*M P.:I=I<
,nd loop<
If !YXM null" then
---- code for H in list<
,lse
--- code for H no in list<
,nd if<
P*M:<
1ound*Mfalse<
9hile !PXM null" and !1ound*M false" loop
If !P.7/: M H" then 1ound*M true<
,lse P*M P. :I=I<
,nd loop<
If !PXM null" then
---code for H in list<
,lse
---code for H not in list
,nd if<
)here are three difficulties with this approach of using @oolean flag variables in
multiple loop e-it
=eed for additional variables
/dditional test required on loop e-it to determine which condition caused
the e-it.
)he requirement in many cases is that the loop body be terminated
immediately on the occurrence of a given condition and not at the start of the ne-t iteration as
would occur on testing a loop flag.
Solution for multiple loop e-it have been e-pressed in 1#3)3/= I7 below
&o +E I M +, =
-------
-------
If !'ond+" Ao )o .E
-------
-------
If !'ond." Ao )o 0E
-------
-------
+E 'ontinue
.E --- code for 'ond+ ,-it
0E ---code for 'ond. ,-it
4E 'ontinue
Fig. 3 "u#ti#e 2oo 18its in F,9.9A% I+
4"
Principles And Programming Languages Unit - I
/lthough gotoCs are used to achieve multiple loop e-it $ to isolate alternative actions
on e-it. )he spirit of clarity $ locality is maintained. 'ontrol is transferred only to the neighboring
statements of the loop e-it.
,-ample for multiple loop e-it in /da have been represented below
1or I in +Z..(a- loop
-------
-------
,-it when cond+<
-------
-------
,-it when cond.<
-------
-------
,nd loop<
If !cond+" then
--- code for 'ond+ ,-it<
,lseif !cond." then
---code for 'ond. ,-it<
,ndif<
---code for normal ,-it<
Fig. $ "u#ti#e 2oo 18its in Ada
/n /da e-it statement transfers control to the statement immediately following the
end of the containing loop when the associated condition become true.
/da loops can be given names, and e-it statements of the form
If condition then e-it loop.<
'an be used to achieve e-it from nested lop or from an inner loop to an outer loop.
/lgorithms can often be redesigned to eliminate the need for multiple e-its.
. Data encapsulation.
Involves packing of a data structure and its access routines in a single module
)he data structure is manipulated only by the access routines. #ther routines use the
data structure by calling the appropriate access routine.
/ data structure is thus defined by the operations that can be performed on it.
3outines that use the structure need not know the details of data representation or data
manipulation.
,ncapsulated data structure provides abstract obects in the same way the
mathematical library routines provide abstract operations.
&ata encapsulation is different from that of abstract data type nor with data
abstraction.
/ abstract data type is a user-defined template that can be used to create numerous
instances of encapsulated data obects, in the same way that the integer type can be used to create
numerous instance of integer obect.
4#
Principles And Programming Languages Unit - I
&ata abstraction is used to describe a design principle that incorporates both data
encapsulation and abstract data types.
In primitive programming such as 1#3)3/=, data encapsulation can be
implemented in a manner that violates single entry, single e-it. ?et maintains linearity and locality of
control flow.
S;@3#;)I=, I=)S)I!I),(, 1:/A"
- I),( IS )>, S)/'I 7/:;,
- ,331:A IS )>, ,33#3 1:/A
- ,331:A 3,);3= E IS =#3(/:
- ,331:A 3,);3= + IS S)/'I 1;::
- ,331:A 3,);3= -+ IS S)/'I ,(P)?
- I=),A,3 I),(, ,331:A, I=&,H, S)/'I!+EE"
- I=&,H IS )>, S)/'I P#I=),3
- S)/'I IS )>, /33/? 3,P3,S,=)/)I#=
- I=I)I/:IJ/)I#= '#&, 1#::#9S
I=&,H M E
3,);3=
- P;S> S,')I#= 1#::#9S
,=)3? P;S>
I1 !I=&,H.A,.+EE" A# )# +E
,331:A M E
I=&,H M I=&,H P +
S)/'I !I=&,H" M I),(
3,);3=
- P#P S,')I#= 1#::#9S
,=)3? :##P
I1 !I=&,H.:,.E" A#) )# .E
,331:A M E
I),( M S)/'I !I=&,H"
I=&,H M I=&,H G +
3,);3,=
- ,33#3 >/=&:,3S
+E ,331:A M +
3,);3=
.E ,331:A M -+
3,);3=
,=&
Fig. Stac) 1ncasu#ation in F,9.9A% I+
Subroutine I=)S)I has two entry points !push and pop", five return statements and
two goto statements.
I=)S)I is called to initiali2e the array inde-.
5$
Principles And Programming Languages Unit - I
Impending stack overflow !I=&,H.A,.+EE" $ Impending stack underflow
!I=&,H.:,.E".
Aoto statement is used to transfer control to error handling code that sets error flag
appropriately and returns control to the calling routine.
- It is calling routineCs responsibility to test the error flag and proceed accordingly.
)o be strictly correct, S)/'I $ I=&,H should be placed in '#((#= block to
make them static obect although most 1#3)3/= I7 implementations allocate memory statically
only '#((#= blocks are guaranteed to be static.
Placing S)/'I array $ I=&,H pointer in a '#((#= block would make them
globally accessible $ this would violate the principle of information hiding used in the
encapsulation.
In the above eg. 1ive basic features that must be provided by data encapsulation
facility.
(ultiple entry and return points
:ocal hidden source code $ data representation
Static data obects
/n initiali2ation section
,-ceptional handling
5,., Statement
Provides unconditional transfer of control and thus allows violation of single entry, single e-it
conditions of structured coding.
,ven there is violation of single entry, single e-it and yet maintained locality and linearity of
control flow.
Aoto statements can be used to simulate single entry, single e-it constructs in primitive
languages.
,g. @elow the use of Aoto statement in 1#3)3/= I7 to simulate If-then-else and 9hile-do
If @ then S+ else S.< I1 !.=#).!@"" A# )# +E
S+
A# )# .E
+E S.
.E '#=)I=;,
9hile @ do S +E I1 !.=#).!@"" A# )# .E
S
A# )# +E
.E '#=)I=;,
Fig. Simu#ation of structured contro# f#ow in F,9.9A% I+
51
1ig. a. Simulation of if-then-else in 1#3)3/= I7
1ig. b. Simulation of while-do in 1#3)3/= I7
Principles And Programming Languages Unit - I
Preprocessors and macro processors are available to automatically translate structured
constructs into 1#3)3/= I7, '#@#: and various assembly languages.
/ Aoto statement should be reversed for unusual or uncommon situations where the natural
structure of an algorithm has to be broken.
/ good rule is to avoid the use of umps to e-press regular iteration or conditional of
statements.
1or such umps, destroy the reflection of the structure of the computational in te-tual
!static" structure of the program.
:ack of correspondence between te-tual and computational !static $ dynamic"
structure. )his is e-tremely harm to the clarity of the program and makes the task of
verification much more difficult.
/lthough goto statement can often be used with positive effect on program
clarity, it is e-tremely low-level construct and is easily misused.
/ serious problem is using goto statements is the insidious mind set that
results from thinking in terms of gotos.
'ode for a four-way selection might be implemented using gotos in the following
manner
If ! condition +" then go to :+<
If ! condition . " then go to :.<
If ! condition 0 " then go to :0<
Aoto :4<
:+* - code for condition +<
Aoto :5<
:.* - code for condition .<
Aoto :5<
:0* - code for condition 0<
Aoto :5<
:4* - code for all other conditions<
:5*- 'ontinue<
In a primitive programming languages, this goto version could be best structured that can be
achieved.
If ! condition +" then
--- code for condition +<
,lse if ! condition . " then
--- code for condition .<
,lse if ! condition 0 " then
--- code for condition 0<
52
Principles And Programming Languages Unit - I
,lse
--- code for condition 4<
,nd if<
If one is used to, program with gotos, the clear and more compact solution that results from nested
else-if constructs may not come to mind as readily as the goto version. ,ven though else-if is
available in the implementation language.
In general goto statement can be a valuable mechanism when used in a disciplined and stylistic
manner.
/s a general rule, forward goto to e-it local construct $ to transfer control
to local error-handling code are acceptable.
Aoto statements that transfer control to remote regions of the code, or that
ump in and out of code segments in clever destroy the linearity and locality of control
flow which are to be avoided.
9ecursion
/ recursion subprogram is one that calls itself, either directly or indirectly.
3ecursion is a powerful $ elegant programming technique.
9hen properly used recursive subprograms are easy to understand and are ust as efficient as,
iterative implementation of essential or inherently recursive algorithms.
3ecursive algorithm arises naturally in conunction with recursive data structure !eg. :inked lists,
trees". 9hen the e-act topology $ the number of elements in the structure are not known.
3ecursion in other situations, it requires backtracking !eg. /n algorithm for in-order traversal of
binary trees can be e-pressed recursively".
)he distinguished characteristic of recursive subprograms is use of a system provided stack to hold
value of local variables, parameters $ return points during recursive calls.
/ 1#3)3/= system that uses static memory allocation cannot support recursive subprogram
because stack is required to record successive return addresses on successive invocations prior to
returns.
3ecursion invocation of a routine under static memory management would result in overwriting of
the original return address for the routine.
3ecursion can be simulated in statically allocated languages such as 1#3)3/=.
/ great deal of code must be supplied by the programmer to manipulate an
e-plicitly declared stack data structure.
)he required effort is usually not cost effective.
3ecursion is used inappropriately to implement algorithms that are naturally iterative such algorithms
do not require a stack or any other backtracking mechanism.
,g. Inappropriate use of recursion includes routines to compute factorials
and 1ibonacci numbers.
53
Principles And Programming Languages Unit - I
)hese routines are often used in introducing te-t to illustrate recursive
implementation of recursive specifications.
3ecursion is a powerful specification and implementation technique in appropriate circumstances.
1unctional specification state what is required, not how to achieve it.
)he algorithmic form of a recursive specification is often best e-pressed in
an iterative manner.
3ecursive implementations of factorial $ 1ibonacci numbers are inappropriate because there is no
inherent need for recursion as there is for tree traversal $ other backtracking algorithms.
3ecursion implementation usage in a 1ibonacci is easier to understand that the iterative version. )here
are sufficient ustifications for using recursive version of an inherently iterative algorithm.
/n iterative implementation of an inherently recursive algorithm will result in a user-maintained stack
to simulate recursion or clever manipulation of pointers in the data structures to setup backtracking
links. )his is sometimes less efficient and is always less understandable than a recursive implantation.
CODING ST8LE
Style is the consistent pattern of choice made among alternative ways of achieving a desired effect.
'oding style is manifest !clear" in the pattern used by programmers to e-press a desired action or
outcome.
It has been recogni2ed that good coding style can overcome many of the deficiencies of a primitive
programming languages.
7ery poor style can defeat the intent of an e-cellent language.
)he goals of good coding style are to provide easily understood, straightforward, elegant code.
)here is no single set of rules that can be applied in every situation< however there are general
guidelines that are widely applicable.
some of the guidelines listed below are &oCs and &onCts of a good coding style
Do9$ of Goo+ Co+ing St*)e
;se of few standard, agreed-upon control constructs
;se gotos in a disciplined way
Introduce user-defined data type to model entities in the problem domain
>ide data structure behind access functions
Isolate machine dependencies in a few routines
Provide standard documentation prologues for each subprogram and B or compilation unit
'arefully e-amine routines having fewer than 5 or more than .5 e-ecutable statements
;se indentation, parentheses, black spaces, blank lines and borders around comment blocks to enhance
readability.
Don9t$ of Goo+ Co+ing St*)e
54
Principles And Programming Languages Unit - I
&onCt be too clever
/void null )hen statements
/void )hen-If statements
&onCt nest too deeply
/void obscure side effects
&onCt suboptimi2e
'arefully e-amine routines having more than five formal parameters
&onCt use an identifier routines having more than five formal parameters
&onCt use an identifier for multiple purposes.
Do:s of 5ood *oding Sty#e
!se a fe" standard control constructs
)here is standard set of constructs for structured coding.
=esting of statement sequencing, selection and iteration are sufficient mechanism
If primitive languages are to be used like 1#3)3/=, '#@/:, @asic, structured constructs
can be achieved by using conditional and unconditional branching in stylistic patterns to
achieve the effects.
Preprocessors are sometimes used to translate structured constructs into primitive
languages.
If the implementation language does not provide structured coding constructs, a few
stylistic patterns should be used by the programmers who implement the system.
)his will make coding style more uniform among various programmers, with the result that
programs will be easier to read, easier to understand, and easier to modify.
!se gotos in a disciplined "a#
In primitive programming languages, the goto statement can be used in conunction with the if
statement to achieve the format and effect of structured coding constructs.
)he goto transferring control to error handling code. In all these cases, the goto is used in a
stylistic, disciplined manner to achieve a desired result.
In particular, the acceptable uses of the goto statement are almost always forward transfers of
control within a local region of code.
;sing a goto to achieve backward transfers of control or to perform ump to a remote region of
a program is rarely acceptable.
)he /da programming language provides numerous structured constructs
o ,-it statements for loop termination, and e-ception handling mechanisms.
o )hese facilities reduce the need for goto statements
)he goto statement is not provided to encourage violation of structured coding practices.
)he goto statement, coupled with the if statement permit user needed control flow mechanisms in
the same way that user-defined data types permit user definition of unavailable data
representations.
55
Principles And Programming Languages Unit - I
@oth goto statements and user-defined data types should be further the goals of simplicity, clarity,
and elegance of programs.
Introduce user$defined data t#pe to model entities in the problem domain
/da and other modern programming languages provide user Gdefined data types.
;se of distinct data types makes it possible for humans and computer systems to distinguish
between entities from the problem domain.
1or e-ample enumeration data types can be enumerate the elements of an inde-ing sequence<
subtypes can be used to place constraints on obects of a given type< and derived types permit
segregation of obects that have similar representations.
/ll entities in the problem domain must be mapped into obects of predefined type !logical,
integers, real, array etc.".
Integers are typically used for inde-ing, and inde- values !e.g., color values".
&ifferent entities in the problem domain are mapped into the same data type in
1#3)3/= I7.
1or e-ample, velocity obects and temperature obects both map into obects of type
3,/:.
;ser Gdefined data types that segment the problem domain in a logical manner can greatly
improve the clarity and readability of a source program.
;nder strong type-checking rules, user-defined data types also provide increased data security.
Programs written in languages that do not support user-defined data types cannot be made as
clear or as secure as programs written in a modern language
>owever, naming conventions for obect declarations can be adopted to improve the quality of
source code.
%ide data structure behind access functions
In software system designed using information hiding, each module makes visible only those
features required by others modules.
/ll other aspects of the modules are hidden from e-ternal view.
>iding data structures behind access functions is the approach taken in data encapsulation,
wherein a data structure and in access routines are encapsulated in a single module.
In languages having global scope !assembly language, @/SI', '#@#:", disciplined
programming style can be used to ensure that maor data structures are manipulated in only a
few regions of the source code.
/ll other code segments that used data structured should do so by invoking the appropriate
access code.
)his approach improves the modularity of a source program, and new access
functions can be provided as needed.
'hanges in the details of data representations require only local changes to, and only
local recompilation of, access code.
56
Principles And Programming Languages Unit - I
If the specification part of an access routine is changed, all routines that call the
modified access routines must be modified and recompiled, but the modification
required is very simple*
#nly the call statement to the access routine, and perhaps the base in which the calling
parameters are used, need be modified.
'all statement needing modification can be identified using a call graph listing.
Isolate machine dependencies in a fe" routines
Similar reasoning for hiding data structure behind access functions also applies to the isolation
of machine dependencies in a few separate routines.
If the nature of data representation need be changed, or if the program is moved to a different
machine, details of machines dependencies are locali2ed and can be modified accordingly.
Pro&ide standard documentation prologues for each subprogram and ' or compilation unit
)he documentations prologues contain information about a subprogram or compilation unit
that is not obvious from reading the source te-t of the subprogram are compilation unit.
)he e-act from and content of prologue depends on the nature of the implementation
language.
/ routine written in /da is more self descriptive done one written in assembling language, and
will require less information in the documentation prologue.
1or instance, the program of the assembly language the routine should describe the base in
which various machine and parameters areas are used by the routine.
,g. In 1#3)3/= routines, the documentation prologue should describe the inputBoutput
modes and problems domain characteristics of formal parameters.
Information provided through a combination of the documentation prologue and the self
documenting features of the implementation language are listed in below table.
Carefull# examine routines ha&ing fe"er than ( or more than )( executable statements
/ subprogram consists of specification, documentation prologue, declarations, e-ecutable
statements, and some language, e-ception handless.
)he e-ecution portion of a subprogram should implement a well defined function that can be
displayed by a simple sentence having many routines that have five to twenty five e-ecutable
statements.
/ subprogram has more than .5 e-ecutable statements probably contains one or more
e-ecutable sub functions that can be packaged has distinct sub programs and invoked when
needed.
/lso it has been suggested that 0E e-ecutable statements is upper limit of comprehension for
a single reading of a subprogram written in a procedural programming language.
57
,a0le 2 - %e&er Page 222 ta0le 6(3
Principles And Programming Languages Unit - I
/ sub program that has fewer done five statements is usually too small to provide a well
defined functions
It is usually preferable to insert five or fewer statements in-line as needed rather than
to invoke a subprogram.
,fficiency should not be overriding concern during initial implementation of a
system, but linkage over head a significant portion of a five statements subprogram,
and common sense should prevail in all cases.
#bvious e-ceptions to these guidelines e-ist* absolute values and mod routines of
fewer than five lines can be quite useful, and routines such as optimi2ation
logarithms, for e-ample, are often much larger than .5 lines< however a routine
>aving fewer than 5 or more than .5 e-ecutable statements should be closely e-amine for
inline placement in the calling routine !less than 5 statements".
Identification of well defined sub functions that can be placed in separate routines and are
called as needed !more than 5 statements".
#ften the well defined sub functions that placed in separate routines provides stand alone
utili2es that can be used in other contacts.
!se indentation* parentheses* blac+ spaces* blan+ lines and borders around comment bloc+s to
enhance readabilit#.
/ pleasing format of presentation greatly enhances the readability of a source program.
1ormatting of source te-t can be done manually by the programmer, or by a pretty print%
routine that automatically indents code to emphasi2e the syntactic structure of the
programming language.
/ formatting routine can also insert blank lines and borders around comment statements.
If formatting of source te-t is done by the programmers, standards conventions should be
agreed to and adhered to by all programmers.
If formatting done by a program, all source code should be processed by the formatter before
it is retained in a permanent file.
In any case a source te-t formatting program is a valuable tool.
Don:ts of good coding sty#e
Don,t be too cle&er
)his is illustrated by the following segment of code written in 1#3)3/= I7
&# +E I M +,=
&# +E L M +,=
+E /!I,L"M!IBL"V!LBI"
=ot only is the code segment unclear, it is also inefficient.
@efore continuing, pause for a moment to determine what is accomplished by this
code segment.
)he following code segment achieves the same result in a clearer and more efficient
manner.
5"
Principles And Programming Languages Unit - I
&# .E I M +,=
&# +E L M +,=
/!I,L" M E.E
+E '#=)I=;,
/!I,I" M +.E
.E '#=)I=;,
)he second version of this algorithm makes obvious the initiali2ation of matri- /
using = e-tra assignment statements !one e-tra assignment per matri- row".
>owever, the first version requires an integer multiply operation, two integer division
operations, and a floating-point conversion for each of the != squared" elements in the
matri-< thus the second version is not only much clearer but also far more efficient
than the first version.
A&oid obscure side effects
/ side effect of a subprogram invocation is any change to the computational state that occurs as a
result of calling the invoked routine.
Side effects include modification of parameters passed by reference or by value-result,
modification of global variables, IB# operations, and other items.
/n obscure side effect is one that is not obvious from the invocation of the called routine. /n
invocation of the form
A,) !H"<
)hat reads a value from a default input file and stores the value in location H e-erts an
obvious, self documenting side effect.
If, in addition, the A,) routine sorts a file, rewinds a tape, and launches a guided missile,
it e-erts obscure side effects.
Don,t sub$optimi-e
Sub-optimi2ation occurs when one devotes e-cessive effort to refining a situation that has little
effect on the overall outcome.
)here are two aspects to sub-optimi2ation of software.
1irst, it is usually not possible to determine what portion of the code will occupy the
maority of e-ecution time until e-ecution characteristics of the running program are
measured.
Second, unless one has intimate knowledge of the language translator, operating system,
and hardware, it usually is not clear how various situations will be handled by the system.
)hus, the programmer may waste time and effort worrying about situations that are handled in
non intuitive ways of the system, and that have little effect on overall performance.
#ne should, of course, choose the optimal approach when it is obvious.
#ne should not, however, agoni2e over minor decisions.
Carefull# examine routines ha&ing more than fi&e formal parameters
5#
Principles And Programming Languages Unit - I
Parameters and global variables are the mechanisms used to communicate data values
among routines.
Parameters bind different arguments to a routine on different invocations on the routine,
and global variables communicate arguments whose bindings do not change between calls to the
routine.
Parameters and global variables should be few in number.
:ong, involved parameter lists results in e-cessively comple- routines that are difficult
to understand and difficult to use< they result from inadequate decomposition of a software
system.
Selection of the number five as the suggested upper bound on the number of parameters
in a sub-program is not an entirely arbitrary choice.
,ase of understanding a sub-program call, or the body of a sub-program
definition, is a sensitive function of the number of parameters and global variables
used in the routine.
1ewer parameters and fewer global variables improve the clarity and
simplicity of sub-programs. In this regard, five is a very lenient upper bound.
Don,t use an identifier for multiple purposes.
Programmers sometimes use one identifier to denote several entities.
)he rationale is memory efficiency.
)hree variables require three or more memory cells.
)here are several things wrong with this practice.
,ach identifier in a program should be given a descriptive name that suggests its
purpose which is not possible if the identifier is used for multiple purposes.
)he use of a single identifier for multiple purposes indicates multiple regions of code
that have low cohesion.
;sing an identifier for multiple purposes is a dangerous practice, because it makes the
source code very sensitive to future modifications that lead to e-treme confusion for
the reader of a program.
If a system is so tightly constrained in memory space
)hen single identifiers must be used for multiple purposes, the system should be
segmented into several smaller routines with an overlay structure.
If this violates e-ecution time restrictions, the system should be redesigned.
A&oid null Then statements
/ null then statement is of the form
if @ then <
else S<
which is equivalent to
if !not @" then S<
9hich one would probably not write a null.
6$
Principles And Programming Languages Unit - I
A&oid Then$If statements
/ then..if statement is of the form
if !/Q@" then
if !HQ?" then
/* M H<
else
/* M @<
end if<
else
/* M @<
end if<
)hen..if statements tend to obscure the conditions under which various actions are performed.
/ then..if statement can always be rewritten in the more obvious else..if forms, as in the
following /da segment*
if !/T@" then
/* M @<
else..if !HQ?" then
@* M ?<
else
/* M H<
end if<
Don,t nest too deepl#
)he maor advantage of single entry, single e-it constructs is the ability to nest constructs
within one another to any desired depth while maintaining linearity of control flow.
If the nesting becomes too deep, as in
while @+ loop
if @. then
repeat S+
while @0 loop
if @4 then S.
It becomes difficult to determine the conditions under which statement S. will be
e-ecuted< the clarity of the code is obscured.
,-cessive nesting is also an indication of fu22y thinking and poor design.
/s a general guideline, nesting of program constructs to depth greater than three or four levels
should be avoided. In addition, procedures should only be nested one level deep within one
another.
61
Principles And Programming Languages Unit - I
62