4.3.1 Programming Paradigms
4.3.1 Programming Paradigms
3 Further programming
1
Programming paradigms
• A programming paradigm is a fundamental style
of programming.
• Each paradigm will support a different way of
thinking and problem solving.
• Paradigms are supported by programming
language features.
• Some programming languages support more than
one paradigm.
• There are many different paradigms, not all
mutually exclusive.
2
Different programming paradigms
• Low-level programming paradigm
• Imperative programming paradigm
• Object-oriented programming paradigm
• Declarative programming paradigm
3
Low-level programming paradigm
• The features of low-level programming
languages give us the ability to manipulate the
contents of memory addresses and registers
directly and exploit the architecture of a given
processor.
• We solve problems in a very different way
when we use the low-level programming
paradigm than if we use a high-level
paradigm.
4
Processor instruction set
5
Processor instruction set
6
Processor instruction set
7
Processor instruction set
8
In the assembly code in this chapter:
• ACC denotes the Accumulator.
• IX denotes the Index Register.
• # denotes immediate addressing.
• B denotes a binary number, e.g. B01001010.
• & denotes a hexadecimal number, e.g. &4A.
• <address> can be an absolute address or a
symbolic address.
9
Symbolic addresses
• A label is a symbolic name for the memory location
that it represents .
– You can treat it like a variable name.
• When writing low-level programs, we can give absolute
addresses of memory locations.
– This is very restrictive, especially if we want to change the
program by adding extra instructions.
• Writing low-level instructions using symbolic addresses
(labels), allows us to think at a higher level.
– The assembler will allocate absolute addresses during the
assembly process
10
Problem-solving and assembly-
language programs
• When writing a solution to a problem using
low-level programming, we need to break
down the problem into simple steps that can
be programmed using the instruction set
available.
• One approach is to think in terms of the basic
constructs we discussed for high-level
languages.
11
Assignment
12
Selection
13
Repetition
14
Absolute and relative addressing
• An absolute address is the numeric address of
a memory location.
• A program using absolute addresses cannot be
loaded anywhere else in memory.
• Some assemblers produce relative addresses,
so that the program can be loaded anywhere
in memory.
15
Absolute and relative addressing
• Relative addresses are addresses relative to a
base address, for example the first instruction
of the program.
• When the program is loaded into memory the
base address is stored in a base register (BR).
• Instructions that refer to addresses then use
the value in the base register, modified by the
offset.
16
Absolute and relative addressing
• For example, STO [BR] + 10 will store the
contents of the accumulator at the address
calculated from (contents of the base
register)+ 10.
17
Absolute and relative addressing
18
Absolute and relative addressing
• It is very important that, at the end of the
program, control is passed back to the operating
system.
• Otherwise the binary pattern held in the next
memory location will be interpreted as an
instruction.
• If the content of that memory location does not
correspond to a valid instruction, the processor
will crash.
• The instruction END signals the end of the
program instructions.
19
Indirect addressing
• Indirect addressing is useful if the memory
address to be used in an instruction is
changed during the execution of the program.
20
Writing a program for a simple queue
• At the top level, we can write the problem
using structured English:
21
Queue processing
22
Queue processing
• Note that the value shown in Table above at the
memory locations labelled HEADPTR and TAILPTR
is the address of the start of the memory
locations reserved for the queue.
• As values are added to the queue, the TAILPTR
value will increase to point to the memory
location at the end of the queue data.
• When a value is taken from the queue, the
HEADPTR value will increase to point to the
memory location at the head of the queue data.
23
Summary
• A problem to be solved must be broken down
into simple steps that can be programmed
using the processor's given instruction set.
24
Summary
• Processing includes:
– arithmetic: adding, incrementing, decrementing
– comparison: equal or not equal
– bitwise operations: AND, OR, XOR, shifting
– output to screen.
25
Summary
• To set a value in the accumulator it can be:
– input from the keyboard
– created using immediate addressing
– loaded from a memory location using direct,
relative, indirect or indexed addressing.
• An address can be absolute (a number) or
symbolic (a label).
26
Imperative programming paradigm
• Imperative programming involves writing a
program as a sequence of explicit steps that are
executed by the processor.
• An imperative program tells the computer how to
get a desired result, in contrast to declarative
programming where a program describes what
the desired result should be.
– Note that the procedural programming paradigm
belongs to the imperative programming paradigm.
– There are many imperative programming languages,
Pascal, C and Basic to name just a few.
27
Object-oriented programming
paradigm
• The object-oriented paradigm is based on objects
interacting with one another.
• These objects are data structures with associated
methods.
• Many programming languages that were originally
imperative have been developed further to support the
object oriented paradigm.
– Examples include Pascal (under the name Delphi or Object
Pascal) and Visual Basic (the .NET version being the first
fully object-oriented version).
– Newer languages, such as Python and Java, were designed
to be object-oriented from the beginning.
28
Object-oriented programming
paradigm
• Procedural programming groups related
programming statements into subroutines.
• Related data items are grouped together into
record data structures.
• To use a record variable, we first define a
record type.
• Then we declare variables of that record type.
29
Object-oriented programming
paradigm
• OOP goes one step further and groups together
the record data structure and the subroutines
that operate on the data items in this data
structure.
• Such a group is called an 'object'.
• The feature of data being combined with the
subroutines acting on the data is known as
encapsulation.
• To use an object, we first define an object type.
An object type is called a class.
30
Example of using a record
• A car manufacturer and seller wants to store
details about cars. These details can be stored
in a record structure.
31
Example of using a record
• We can write program code to access and
assign values to the fields of this record .
– For example:
32
Example of using a record
• We can call this procedure from anywhere in
our program. This seems a well-regulated way
of operating on the data record .
– However, we can also access the record fields
directly from anywhere within the scope of
ThisCar:
33
Classes in OOP
• The idea behind classes in OOP is that
attributes can only be accessed through
methods written as part of the class definition
and validation can be part of these methods.
• The direct path to the data is unavailable.
34
Classes in OOP
• Attributes are referred to as 'private'.
• The methods to access the data are made
available to programmers, so these are
'public'.
• Classes are templates for objects.
• When a class type has been defined it can be
used to create one or more objects of this
class type.
35
Classes in OOP
• Attributes: the data items of a class
• Methods: the subroutines of a class
• Object: an instance of a class
36
Classes in OOP
• The first stage of writing an object-oriented
program to solve a problem is to design the
classes.
• This is part of object-oriented design.
• From this design, a program can be written
using an object-oriented programming (OOP)
language.
37
Advantages of OOP over procedural
languages
• The advantage of OOP is that it produces
robust code.
• The attributes can only be manipulated using
methods provided by the class definition.
• This means the attributes are protected from
accidental changes.
38
Advantages of OOP over procedural
languages
• Classes provided in module libraries are
thoroughly tested .
• If you use tried and tested building blocks to
construct your program, you are less likely to
introduce bugs than when you write code
from scratch.
39
Designing classes and objects
• When designing a class, we need to think
about the attributes we want to store.
• We also need to think about the methods we
need to access the data and assign values to
the data of an object.
40
Designing classes and objects
• A data type is a blueprint when declaring a
variable of that data type.
• A class definition is a blueprint when
declaring an object of that class.
• Creating a new object is known as
'instantiation'.
41
Designing classes and objects
• Any data that is held about an object must be
accessible, otherwise there is no point in
storing it.
• We therefore need methods to access each
one of these attributes.
• These methods are usually referred to as
getters.
– They get an attribute of the object.
42
Designing classes and objects
• When we first set up an object of a particular
class, we use a constructor.
• A constructor instantiates the object and
assigns initial values to the attributes.
43
Designing classes and objects
• Any properties that might be updated after
instantiation will need subroutines to update
their values.
– These are referred to as setters.
• Some properties get set only at instantiation.
– These don't need setters.
• This makes an object more robust, because
you cannot change properties that were not
designed to be changed.
44
Creating a class
• See pages 378-379 Computer science book
45
Instantiating a class
• To use an object of a class type in a program
the object must first be instantiated . This
means the memory space must be reserved to
store the attributes.
46
Using a method
• To call a method in program code, the object
identifier is followed by the method identifier
and the parameter list.
47
Inheritance
• The advantage of OOP is that we can design a
class (a base class or a superclass) and then
derive further classes (subclasses) from this base
class.
• This means that we write the code for the base
class only once and the subclasses make use of
the attributes and methods of the base class, as
well as having their own attributes and methods.
• This is known as inheritance and can be
represented by an inheritance diagram
48
Inheritance
• Inheritance: all attributes and methods of the
base class are copied to the subclass
49
Implementing a library system
Consider the following problem:
• A college library has items for loan.
• The items are currently books and CDs.
• Items can be borrowed for three weeks.
• If a book is on loan, it can be requested by
another borrower.
50
Table 27.02 shows the information to
be stored.
51
Implementing a library system
• There are some items of data that are
different for books and CDs. Books can be
requested by a borrower. For CDs, t he genre
is to be stored.
52
• We can define a class LibraryItem and derive a
Book class and a CD class from it.
• We can draw the inheritance diagrams for the
LibraryItem, Book and CD classes as in Figure
27.03.
53
• Analysing the attributes and methods
required for all library items and those only
required for books and only for CDs, we arrive
at the class diagram in Figure 27.04.
54
• A base class that is never used to create
objects directly is known as an abstract class.
LibraryItem is an abstract class.
55
Declaring a base class and derived
classes (subclasses) in Python
• See page 386 ( Computer Science A-level)
56
Instantiating a subclass
• Creating an object of a subclass is done in the
same way as with any class
57
Using a method
• Using an object created from a subclass is
exactly the same as an object created from
any class.
58
Polymorphism
• The constructor method of the base class is
redefined in the subclasses.
• The constructor for the Book class calls the
constructor of the LibraryItem class and also
initialises the IsRequested attribute.
• The constructor for the CD class calls the
constructor of the LibraryItem class and also
initialises the Genre attribute.
59
Polymorphism
• The PrintDetails method is currently only defined
in the base class.
• This means we can only get information on the
attributes that are part of the base class.
• To include the additional attributes from the
subclass, we need to declare the method again .
• Although the method in the subclass will have
the same identifier as in the base class, the
method will actually behave differently.
• This is known as polymorphism.
60
Polymorphism
• Polymorphism: the method behaves
differently for different classes in the hierarchy
61
• The way the programming languages re -
define a method varies.
• The code shown here includes a call to the
base class method with the same name.
• You can completely re-write the method if
required .
62
Garbage collection
• When objects are created they occupy
memory.
• When they are no longer needed, they should
be made to release that memory, so it can be
re -used.
• If objects do not let go of memory, we
eventually end up with no free memory when
we try and run a program.
• This is known as 'memory leakage'.
63
64
Containment (aggregation)
We have other kinds of relationships between
classes.
• Containment means that one class contains other
classes.
– For example, a car is made up of different parts and
each part will be an object based on a class.
– The wheels are objects of a different class to the
engine object.
– The engine is also made up of different parts.
Together, all these parts make up one big object.
65
Containment (aggregation)
• Containment: a relationship in which one
class has a component that is of another class
type
66
Using containment
• A college runs courses of up to 50 lessons. A
course may end with an assessment. Object
oriented programming is to be used to set up
courses.
67
68
• Assuming that all attributes for the Lesson and
Assessment class are set by values passed as
parameters to the constructor, the code for
declaring the Lesson and Assessment classes
are straightforward.
69
70
Here is simple test programs to check
if it works.
71
Summary
• A class has attributes (declared as private) and
methods (declared as public) that operate on
the attributes. This is known as encapsulation.
• A class is a blueprint for creating objects.
• An object is an instance of a class.
• A constructor is a method that instantiates a
new object.
72
Summary
• A class and its attributes and methods can be
represented by a class diagram.
• Classes (subclasses) can inherit from another
class (the base class or superclass). This
relationship between a base class and its
subclasses can be represented using an
inheritance diagram.
73
Summary
• A subclass has all the attributes and methods of
its base class. It also has additional attributes
and/or methods.
• Polymorphism describes the different behaviour
of a subclass method with the same name as the
base class method.
• Containment is a relationship between two
classes where one class has a component that is
of the other class type. This can be represented
using a containment diagram.
74
Declarative Programming
• In declarative programming, the programmer
can simply state what is wanted having
declared a set of facts and rules.
• Prolog is a logic programming language widely
used for artificial intelligence and expert
systems.
• We now look at how this works using
examples of Prolog scripts.
75
Prolog basics
• There are three basic constructs in Prolog:
facts, rules and queries.
• The program logic is expressed using clauses
(facts and rules). Problems are solved by
running a query (goal).
76
Prolog basics
• A collection of clauses is called a 'knowledge
base'. Writing a Prolog program means writing
a knowledge base as a collection of clauses.
We use the program by writing queries.
77
Prolog basics
• A clause is of the form:
– Head : - Body.
78
Prolog basics
• Prolog has a single data type, called a 'term'. A
term can be:
– an atom, a general-purpose name with no
inherent meaning that always starts with a lower
case letter
– a number, integer or float (real)
– a variable, denoted by an identifier that starts
with a capital letter or an underscore(_)
– a compound term, a predicate, consisting of an
atom and a number of arguments in parentheses.
79
Prolog basics
• The arguments themselves can be compound
terms .
• A predicate has an arity (that is, the number
of arguments in parentheses).
• Prolog is case sensitive.
80
Prolog
• In order to do this, we shall use the following
facts for example:
81
Prolog
• Remember that variables must start with an
uppercase letter; constants start with a
lowercase letter.
– Suppose we ask
• male(X)
82
Prolog
• Prolog starts searching the database and finds
male(charnjit) matches male(X) if X is given
the value charnjit.
– We say that X is instantiated to charnjit.
– Prolog now outputs:
• X = charnjit
83
Prolog
• Prolog then goes back to the database and
continues its search. It finds male(jaz) so
outputs:
– X = jaz
84
Prolog
• And again continues its search. It continues in
this way until the whole database has been
searched. The complete output is:
– X = charjit
– X = jaz
– X = tom
– No
**The last line means that there are no more
solutions.
85
Prolog
• The query male(X) is known as a goal to be
tested.
• That is, the goal is to find all X that satisfy
male(X).
• If Prolog finds a match, we say that the search
has succeeded and the goal is true.
• When the goal is true, Prolog outputs the
corresponding values of the variables.
86
Prolog
• Now we shall add the rule:
– father(X,Y) :- parent(X,Y), male(X).
87
Prolog
• The database now looks like this:
88
Prolog
• Suppose our goal is to find the father of
rajinder. That is, our goal is to find all X that
satisfy:
– father(X, rajinder)
89
Prolog
• In the database and the rule the components
female, male, parent and father are called
predicates and the values inside the
parentheses are called arguments.
• Prolog now looks for the predicate father and
finds the rule:
– father(X,Y) :- parent(X,Y), male(X)
90
Prolog
• In this rule, Y is instantiated to rajinder and
Prolog starts to search the database for:
– parent(X,rajinder)
91
Prolog
• If X is instantiated to jane, Prolog now uses
the second part of the rule:
– male(X)
• with X = jane. That is, Prolog’s new goal is
male(jane) which fails. Prolog does not give up
at this stage but backtracks to the match
– parent(jane, rajinder)
92
Prolog
• and starts again, from this point in the
database, to try to match the goal
– parent(X, rajinder)
• This time, Prolog finds the match:
– parent(charnjit, rajinder)
• with X instantiated to charnjit. The next step is
to try to satisfy the goal
– male(charjit)
93
Prolog
• This is successful so
– Parent(charnjitm rajinder) and male(charjit)
• Are true. Thus father(charnjitm rajinder) is
true and Prolog returns
– X = charnjit
• Prolog continues to see if there are any more
matches. Since there aren’t any more
matches, Prolog outputs:
– No
94