0% found this document useful (0 votes)
48 views48 pages

Chapter 5 - Abstraction and Sequence Control

Uploaded by

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

Chapter 5 - Abstraction and Sequence Control

Uploaded by

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

Chapter 5

Abstraction and Sequence


Controls
Encapsulation and Inheritance

1
5.1 Abstraction

2
Introduction
• An abstraction is a view or representation of an entity
that includes only the most significant attributes.
• The data represent an abstraction of reality in the sense
that certain properties and characteristics of the real
objects are ignored because they are peripheral and
irrelevant to the particular problem
• Abstraction is simplification of facts
Example: Consider a personnel file of an employer.
Every employee is represented (abstracted) on this file
by a set of data relevant to his/her accounting
procedures. This set may include Name, Age, Salary but
it will most probably not include irrelevant data such as
the hair color, weight, and height. 3
Introduction
• Process abstraction
All subprograms are process abstractions because
they provide a way for a program to specify a
process, without providing the details of how it
performs its task
Example: Function call
sortInt(list, listLen);
• This call is an abstraction of the actual sorting
process, whose algorithm is not specified.

4
Cont….
• The call is independent of the algorithm implemented
in the called subprogram.
• The only essential attributes in the above call are:
• the name of the array to be sorted
• the type of its elements
• the array’s length,
• the fact that the call to sortInt will result in
the array being sorted.

5
Data Abstraction
• The first data abstraction was done by COBOL: Record
• And the C-based languages: struct (is actually a record)
• General definition:
An abstract data type (ADT) is a data structure, in
the form of a record, but which includes
subprograms that manipulate its data.
• Syntactical definition
An abstract data type is an enclosure that includes
only the data representation of one specific data
type and the subprograms that provide the
operations for that type
• An instance of an abstract data type is called an object.
6
Data Abstraction
• Built-in data types as an Abstract Data Type
• All built-in data types are abstract data types
• A floating-point type provides
• The means to create variables to store floating-point
• A set of arithmetic operations for manipulating objects of
the type.
• Information hiding
• The actual format of the floating-point data value in a
memory cell is hidden from the user
• The only operations available are those provided by the
language
• The user is not allowed to create new operations on data
of the type
7
Data Abstraction
• User-defined Abstract Data Type
• A user-defined abstract data type should provide the
same characteristics as those of language-defined
types, such as a floating-point type:
• A type definition that allows program units to declare
variables of the type but hides the representation of
objects of the type
• A set of operations for manipulating objects of the
type.
• Advantages of information hiding
• Reliability: Clients cannot manipulate the
underlying representations of objects directly,
either intentionally or by accident 8
Data Abstraction
• User-defined Abstract Data Type
• Advantages of information hiding
Reduces the range of code and number of variables of
which a programmer must be aware when writing or
reading a part of the program
Makes name conflicts less likely, because the scope of
variables is smaller.

9
Cont…

Suppose that the original implementation of the


stack abstraction uses a linked list representation.
At a later time, because of memory management
problems with that representation, the stack
abstraction is changed to use a contiguous
representation (array representation)
Because data abstraction was used, this change
can be made in the code that defines the stack
type, but no changes will be required in any of
the clients of the stack abstraction

10
Data Abstraction
• User-defined Abstract Data Type
• Many situations arise in which clients need to access these
data members
• Common solution is to provide accessor methods, sometimes
called getters and setters
• Three reasons why accessors are better than making data
public
1. Read-only access can be provided, by having a getter
method but no corresponding setter method.
2. Constraints can be included in setters. For example, if the
data value should be restricted to a particular range, the
setter can enforce that.
3. The actual implementation of the data member can be
changed without affecting the clients if getters and setters
are the only access.
11
Data Abstraction
• Example: Stack ADT

12
Generic Abstract Data Types
Consider the following: a programmer should not need to write
three different sorting subprograms to sort three arrays that
differ only in element type.
int a[]={5, 9, 2, 6};

floate b[]={2.5, 6.3, 1.2, 3.3};

char c[]={‘f’, ’r’, ’d’, ’m’};


It is possible to develop a blueprint for how to sort the above
arrays with a single Generdic subprogramtemplate in c++

13
Generic Abstract Data Types
• If we want to create a list of an ADT (Ex. list of
employees), we can create an Employee ADT and use
arrays , linked lists … .
• However, what if we don’t want to specify the type of our
list element at ADT creation?
• For instance, one can think of lists of apples, cars or
people.
• The semantical definition of a list is always the same.
• Only the type of the data elements change according to
what type the list should operate on.
• This additional information could be specified by a
generic parameter which is specified at instance creation
14
time.
Generic Abstract Data Types
Example in C++

template<class Type>
Type compare(Type a, Type b) {
return a>b ? a : b;
}

void result(int a, int b, float c, float d) {


int m1 = compare(a,b);
float m2 = compare(c,d);
}

15
Encapsulation by Subprograms
• Two possible abstractions in programming languages
• Data abstraction
• Process abstraction

• In the early history of high level programming


languages, only process abstraction was included
There were no user-defined abstract data types

• Process abstraction, in the form of subprograms, has


been a central concept in all programming languages.

16
Encapsulation by Subprograms
• General Subprogram Characteristics
Each subprogram has a single entry point

The calling program unit is suspended during the execution of


the called subprogram
There is only one subprogram in execution at any given
time

Control always returns to the caller when the subprogram


execution terminates.

17
Encapsulation by Subprograms
• A subprogram is an encapsulation of a computation in some form
that allows it to be executed from various points in a program---
function calls
• Examples of subprograms are functions and procedures
• The encapsulation may be partial in the sense that subprograms
may be able to use external data, such as nonlocal variables and
files.
• A subprogram represents an abstraction of a function that maps
the subprogram's inputs, including both parameters and external
data, into its outputs, including changes to external data as well
as any value that is the result of the computation.

18
Subprogram Design issues
• Are local variables statically or dynamically allocated?
• What parameter-passing method or methods are
used?
• Are the types of the actual parameters checked
against the types of the formal parameters?
• If subprograms can be passed as parameters and
subprograms can be nested, what is the referencing
environment of a passed subprogram?
• Can subprograms be overloaded?
• Can subprograms be generic?
19
Encapsulation by Subprograms
• Basic definitions
A subprogram definition describes the interface to and the
actions of the subprogram abstraction.
A subprogram call is the explicit request that the called
subprogram be executed.
A subprogram is said to be active if, after having been called,
it has begun execution but has not yet completed that
execution
A subprogram header, which is the first part of the definition.
Serves several purposes
Specifies that the following syntactic unit is a
subprogram definition
 Provides a name for the subprogram
 May optionally specify a list of parameters
20
Encapsulation by Subprograms
• Basic definitions
The parameter profile (signature) of a subprogram contains
the number, order and types of its formal parameters
The protocol of a subprogram is its
Parameter profile and,
if it is a function, its return type.
• In almost all languages today, the runtime stack is used to
allocate space for the parameters and local data of the
subprogram
• This space is automatically freed when the subprogram
returns or terminates.
• The data are stack-dynamic

21
Parameters
• The parameters in the subprogram header are called
formal parameters.
• Subprogram call statements must include the name of
the subprogram and a list of parameters (actual
parameters) to be bound to the formal parameters of
the subprogram.

22
Parameters
• In most languages, the binding of actual parameters to
formal parameters is done by position
•  The first actual parameter is bound to the first formal
parameter and so forth.
• Such parameters are called positional parameters.
• keyword parameters are value when passed into
function , are identified by specific parameter name
• Eg in piton
Def team (name, project):

Calling function
team(project=“HRM”, name=“Abebe”);
23
Procedures and Functions
• They are considered as process abstractions
• A function is a subprogram that returns a value and a function (or
function call) can be evaluated as a component of an expression.
Consider a function f(x):
a = b + f(x) is valid
• A procedure is a subprogram that does not return a value
• Any useful work that is done by a procedure is through changes to
external data, including files and arguments
private sub add(a as integer , b as integer, c as integer)
c=a+b
End Sub
Dim x, y, z As Integer
add(x, y, z)

24
Inheritance
• Code reuse (main advantage of inheritance)
• Abstract data types, with their encapsulation and access
controls are candidates for code reuse
• Problems with reusing Abstract Data Types
1. Features and capabilities of the existing type may not be
quite right for the new use; The old type requires at least
some minor modifications.
Person doing the modification should understand part,
if not all, of the existing code.
2. The type definitions are all independent and are at the
same level
Many problems have categories of objects that are
related, both as siblings and as parents and children

25
Inheritance
• Inheritance offers a solution to both the modification and
program organization problem.
• With inheritance, a new abstract data type
• Can inherit the data and functionality of some existing type
• Is allowed to modify some of those entities
• Can add new entities
Reuse is greatly facilitated without requiring changes
to the reused abstract data type.
• Programmers can begin with an existing abstract data type and
design a modified descendant of it to fit a new problem
requirement
• Inheritance provides a framework for the definition of
hierarchies of related classes that can reflect the descendant
relationships in the problem space.
26
Inheritance
• The abstract data types in object-oriented languages are
usually called classes and Class instances are called objects.
• Basic terminologies in OOP
• Class
• Object
• Derived Class / Subclass
• Parent Class / Superclass
• Methods
• Messages

27
Inheritance
• Simple example of inheritance
• Suppose we have a class named Vehicles, which has variables for
year, color, and make.
• A natural specialization, or subclass, of this would be Truck, which
could inherit the variables from Vehicle, but would add variables
for hauling capacity and number of wheels.

28
Polymorphism
• An important concept helped much for dynamic binding

• Without polymorphism concept, method binding was done


statically.

• Polymorphism includes the following concepts:


• Operator overloading
• Function name overloading
• Templates

29
Polymorphism
• Operator overloading
• A+B  5+3 2.3+8.6 obj1+obj2 (+ is overloaded)
• The binding is done when the values for the two variables
are known (at run time)

• Function name overloading


• print(obj)  print(5) print(6.5) print(employee)
• The implementation detail of the print() functions are
different.
the binding with each implementation is done at run
time

30
Polymorphism
• Avoid creating different subprograms that implement
the same algorithm on different types of data:
Example: C++ templates

31
5.2 Sequence Controls

32
Sequence controls-Introduction

• Ordering is fundamental to most models of


computing.
• It determines what should be done first, what second,
and so forth, to accomplish some desired task.
• Seven ordering principal categories:
1.Sequencing: Statements are to be executed in a
certain specified order.
2.Selection: Depending on some run-time
condition, a choice is to be made among two or
more statements or expressions (examples: if,
switch statements)
33
Sequence controls-Introduction
3. Iteration: A given fragment of code is to be executed
repeatedly, either a certain number of times or until
a certain run-time condition is true (while, do..while)
4. Procedural abstraction: A potentially complex
collection of control constructs (a subroutine) is
encapsulated in a way that allows it to be treated as
a single unit.
5. Recursion: An expression is defined in terms of itself;
the computational model requires a stack on which
to save information about partially evaluated
instances of the expression.

34
Sequence controls-Introduction
6. Concurrency: Two or more program fragments are to be
executed/evaluated “at the same time,” either in parallel on
separate processors or interleaved on a single processor in a
way that achieves the same effect
7. Non-determinacy: The ordering or choice among
statements or expressions is deliberately left unspecified,
implying that any alternative will lead to correct results.
Some languages require the choice to be random, or fair, in
some formal sense of the word.
Sequencer: is a construct that transfers control to some other
point in the program, which is called the sequencer’s
destination

35
Implicit and Explicit sequence controls
• Implicit Sequence controls
Are sequence control-structures those defined by the
language to be in effect unless modified
• Example: - Arithmetic expressions
7+5+6-7*3Precedence and Associativity properties which
are defined during language design time
- Sequential statements
begin
statement_1;
statement_2;

statement_n;
end 36
Implicit and Explicit sequence controls
• Explicit Sequence controls
• Sequence control structures that the programmer
may optionally use to modify the implicit sequence of
operations defined by the language
• Example:
• Conditional statements
• Iterations
• Parenthesis

37
Levels of Sequence controls
• Expressions: computing expressions using precedence
rules and parentheses

• Statements: sequential execution, conditional and


iteration statements. (if…else, while, for)

• Subprograms: transfer control from one program to


another. (subprogram calls)

38
Expression-level (Arithmetic)
• Precedence rules and Associativity
• Most operators are either infix or prefix (some languages
have postfix)
• Order of evaluation is determined by operator
precedence and associativity
• What is the result for: 3 + 4 * 5 + 6
• Possible answers:
• 41 = ((3 + 4) * 5) + 6
• 47 = 3 + (4 * (5 + 6))
• 29 = (3 + (4 * 5)) + 6 = 3 + ((4 * 5) + 6)
• 77 = (3 + 4) * (5 + 6)
• Therefore, It depends on the precedence of operators and
associativity rules of a given language 39
Expression-level (Arithmetic)
• Infix, postfix and prefix notations

• Infix: operator appears between two operands


((a-b)/c)*((d+e)-f)

• Postfix: operator appears after its two operands


((a-b)/c)*((d+e)-f)  ab-c/de+f-*

• Prefix: operator appears before its two operands


((a-b)/c)*((d+e)-f)  */-abc-+def

40
Statement-level sequence control
• Selection Statements
• These are the commands which allow the specification
of alternative paths that the competition can take.
• They depend on the satisfaction of specific conditions.
• Iterative Statements
• These allow the repetition of a given command for a
predefined number of times, or
• until the satisfaction of specific conditions.
• Unconditional branching
• Commands which use the goto/jump construct are
grouped in this category
41
Statement-level sequence control
• Selection Statements
• Provides the means of choosing between two or more
execution paths
• Two general categories
Two-way selection
n-way or multiple selection
Two-way selection

42
Two-way selection: Design issue
• The design issues for two-way selectors can be summarized
as follows:
• What is the form and type of the expression that
controls the selection?
• How are the then and else clauses specified
• How should the meaning of nested selectors be
specified
• Control expressions are specified in parentheses if the then
reserved word is not used to introduce the then clause, as in
the C-based languages
• In those cases where the then reserved word is used,
there is less need for the parentheses, so they are often
omitted
43
Two-way selection: Design issue
if (expression) if expression then
statement statement
else else
statement statement

• An interesting problem arises when two-way selection


constructs can be nested. Consider the following Java-like code:

This construct can be interpreted in two different


ways, depending on whether the else clause is
matched with the first then clause or the second.

44
n-way selection
• Example: if..elseif…else and switch statements

45
Iterative statements
• An iterative statement is one that causes a statement
or collection of statements to be executed zero, one,
or more times – usually called loops
• It can be
A. Counter Controlled loops
• Example: for loop

B. Logically Controlled loops


• In many cases, collections of statements must be
repeatedly executed, but the repetition control is
based on a Boolean expression rather than a
counter.
• Example: while and do…while loops
46
Iterative statements
C. User-located control mechanism
• In some situations, it is convenient for a programmer to
choose a location for loop control other than the top or
bottom of the loop body.
• As a result, some languages provide this capability.
• Examples: break, continue and break label

Similar to continue in
c++ and java

47
Iterative statements
D. Unconditional branching (the goto keyword)
• Transfers execution control to a specified location in
the program.
• The unconditional branch, or goto, is the most
powerful statement for controlling the flow of
execution of a program’s statements.
• However, using the goto carelessly can lead to
serious problems
• can make programs very difficult to read (spaghetti
code), and as a result, highly unreliable and costly
to maintain.

48

You might also like