You are on page 1of 28

OBJECT ORIENTED PROGRAMMING

Definition
Object-oriented programming (OOP) is a programming paradigm that uses objects (data
structures consisting of data fields and methods) to design applications and computer
programs.
OOP may include features such as data abstraction, encapsulation, messaging, modularity,
polymorphism and inheritance.
Many modern programming languages now support OOP, at least as an option.
Note:
A programming paradigm is a fundamental style of computer programming (compare with a
methodology, which is a style of solving specific software engineering problems).
Paradigms differ in the concepts and abstractions used to represent the elements of a
program (such as objects, functions, variables, constraints, etc.), and the steps that compose
a computation (assignment, evaluation, continuations, data flows, etc.).
Evolution of object oriented programming
1. The terms “objects” and “oriented” seem to make their first appearance at
Massachusetts Institute of Technology (MIT) in the late 1950s and early 1960s. As early as
1960, “object” could refer to identified items (LISP “atoms” in the LISP programming
language which is the second oldest programming language in use today) with properties
(attributes).
2. Another early MIT example was Sketchpad language created by Ivan Sutherland in 1960 –
61; in his dissertation about Sketchpad, Sutherland defined notions of “object” and
“instance” (with the class concept covered by “master” or “definition”) albeit specialized to
graphical interaction.
3. An MIT ALGOL version, AED-0, linked data structures (“plexes” in that dialect) directly
with procedures, prefiguring what were later termed “messages”, “methods” and “member
functions”.
Note: ALGOL is a language that is as old as LISP; it is the forerunner of PASCAL and C
languages in addition to SIMULA.
4. Objects as a formal concept in programming were introduced in the 1960s in SIMULA 67,
a major revision of SIMULA I, a programming language designed for discrete event
simulation, created by Ole-Johan Dahl and Kristen Nygaard of the Norwegian Computing
Centre in Oslo. SIMULA introduced the notion of classes and instances or objects (as well as
subclasses, virtual methods, co-routines and discrete event simulation) as part of an explicit
programming paradigm. The language also used automatic garbage collection that had been
invented earlier for the functional programming language LISP. SIMULA was used for

1 © Mr. Munene
physical modelling, such as models to study and improve the movement of ships and their
content through cargo ports.
The ideas of SIMULA 67 influenced many later languages, including SMALLTALK, derivatives
of LISP (CLOS), OBJECT PASCAL AND C++.
5. The SMALLTALK language, which was developed at Xerox PARC (by Alan Kay and others)
in the 1970s, introduced the term object-oriented programming to represent the pervasive
use of objects and messages as the basis for computation.
SMALLTALK creators were influenced by the ideas introduced in SIMULA 67, but SMALLTALK
was designed to be a fully dynamic system in which classes could be created and modified
dynamically rather than statically as in SIMULA 67.
6. In the 1970s, Kay’s SMALLTALK work had influenced the LISP community to incorporate
object-based techniques that were introduced to developers via the LISP machine.
Experimentation with various extensions to LISP (like LOOPS and FLAVORS) introducing
multiple inheritance and mixins) eventually led to the Common LISP Object System (CLOS, a
part of the first standardized object-oriented programming language, ANSI Common LISP),
which integrates functional programming and object-oriented programming and allows
extension via a Meta-object protocol.
7. Object-oriented programming developed as the dominant programming methodology in
the early and mid-1990s when programming languages supporting the techniques became
widely available. These included:
(i) Visual FoxPro 3.0
(ii) C++
(iii) Delphi
Its dominance was further enhanced by the rising popularity of graphical user interfaces,
which rely heavily upon object-oriented programming techniques. An example of a closely
related dynamic GUI library and OOP language can be found in the COCOA frameworks
on Mac OS X, written in Objective-C, an object-oriented, dynamic messaging extension to C
based on SMALLTALK.
Note: Object-oriented features have been added to many existing languages from that time
including ADA, BASIC, FORTRAN, PASCAL and others. Adding these features to languages
that were not initially designed for them often led to problems with compatibility and
maintainability of code.
8. Recently, a number of languages have emerged that are primarily object-oriented yet
compatible with procedural methodology. These include:
(i) Python
(ii) Ruby

2 © Mr. Munene
(iii) Visual Basic.NET (VB.NET) – Designed for Microsoft’s .NET platform.
(iv) C# (pronounced ‘c-sharp’)
(v) Java (developed by Sun Microsystems)
VB.NET and C# are probably the most commercially important recent object-oriented
languages. They both support cross-language inheritance, allowing classes defined in one
language to subclass classes defined in the other language.
Developers usually compile Java to bytecode, allowing Java to run on any operating system
for which a Java VIRTUAL MACHINE is available.
VB.NET and C# make use of the Strategy pattern to accomplish cross-language inheritance,
whereas Java makes use of the Adapter pattern.
Just as procedural programming led to refinements of techniques such as Structured
programming, modern object-oriented software design methods include refinements such
as the use of:
(i) design patterns
(ii) design by contract, and
(iii) modelling languages (such as UML)

3 © Mr. Munene
PROGRAMMING PARADIGMS
1. Non-structured programming
- Non-structured programming is the historically earliest programming paradigm capable of
creating Turing-complete algorithms. It is often contrasted with structured
programming paradigms, including procedural, functional, and object-
oriented programming.
- Unstructured programming has been heavily criticized for producing hardly-
readable ("spaghetti") code and is sometimes considered a bad approach for creating major
projects. However, it has been praised for the freedom it offers to programmers and has
been compared to how Mozart wrote music.
- There are both high and low level programming languages that use non-structured
programming. These include:
(i) early versions of BASIC (such as MSX BASIC and GW-BASIC)
(ii) JOSS
(iii) FOCAL
(iv) MUMPS
(v) TELCOMP
(vi) COBOL
(vii) machine-level code
(viii) early assembler systems
(ix) assembler debuggers
(x) some scripting languages such as MS-DOS batch file language.
Basic concepts
A program in a non-structured language usually consists of sequentially ordered commands,
or statements, usually one in each line. The lines are usually numbered or may have labels:
this allows the flow of execution to jump to any line in the program.
Non-structured programming introduces basic control flow concepts such as loops, branches
and jumps. Although there is no concept of procedures in the non-structured paradigm,
subroutines are allowed. Unlike a procedure, a subroutine may have several entry and exit
points and a direct jump into or out of subroutine is (theoretically) allowed. This flexibility
allows realization of coroutines.
There is no concept of local variables in non-structured programming, but labels and
variables can have a limited area of effect (for example, a group of lines). This means there
is no (automatic) context refresh when calling a subroutine, so all variables might retain
their values from the previous call.

4 © Mr. Munene
The depth of nesting also may be limited to one or two levels.

Data types
Non-structured languages allow only basic data types, such as numbers, strings and arrays.
The introduction of arrays into non-structured languages was a notable step forward,
making stream data processing possible despite the lack of structured data types.

2. Procedural programming
-Procedural programming is a programming paradigm, derived from structured
programming, based upon the concept of the procedure call. Procedures, also known as
routines, subroutines, or functions, simply contain a series of computational steps to be
carried out. Any given procedure might be called at any point during a program's execution,
including by other procedures or itself.
- The major procedural programming languages include:
(i) Fortran (first published in 1960)
(ii) ALGOL (1960)
(iii) COBOL (1960)
(iv) BASIC (1960)
(v) Pascal (1970s)
(vi) C (1970s)
(vii) Ada (released in 1980)
(ix) Go (an example of a more modern procedural language, first published in 2009).

Comparison with object-oriented programming


- The focus of procedural programming is to break down a programming task into a
collection of variables, data structures, and subroutines, whereas in object-oriented
programming it is to break down a programming task into data types (classes) that associate
behavior (methods) with data (members or attributes).
- The most important distinction is that while procedural programming uses procedures to
operate on data structures, object-oriented programming bundles the two together, so an
"object", which is an instance of a class, operates on its "own" data structure.
- Nomenclature varies between the two, although they have similar semantics:

5 © Mr. Munene
PROCEDURAL OBJECT-ORIENTED
procedure method
record object
module class
procedure call message

3. Modular programming
- Modular programming (also known as top down design and stepwise refinement) is a
software design technique that increases the extent to which software is composed of
separate, interchangeable components called modules by breaking down program functions
into modules, each of which accomplishes one function and contains everything necessary to
accomplish this.
- Conceptually, modules represent a separation of concerns and improve maintainability by
enforcing logical boundaries between components.
- Modules are typically incorporated into the program through interfaces. A module
interface expresses the elements that are provided and required by the module.
- Languages that formally support the module concept include:
Ada,
Algol,
BlitzMax,
C#,
Clojure,
COBOL,
D,
Dart,
eC,
Erlang
Elixir,
F,
F#,
Fortran,
Go,
Haskell,

6 © Mr. Munene
IBM/360 Assembler,
IBM i Control Language (CL),
IBM RPG, Java,
MATLAB,
ML,
Modula,
Modula-2,
Modula-3,
Morpho,
NEWP,
Oberon,
Oberon-2,
Objective-C,
OCaml,
several derivatives of Pascal (Component Pascal, Object Pascal, Turbo Pascal, UCSD Pascal),
Perl,
PL/I,
PureBasic,
Python,
Ruby,
Rust,
JavaScript,
Visual Basic .NET
WebDNA.
Conspicuous examples of languages that lack support for modules are C, C++ and Pascal (in
its original form).
As of 2014, modules have been proposed for C++; modules were added to Objective-C
in iOS 7 (2013); and Pascal was superseded by Modula and Oberon, which included modules
from the start, and various derivatives that included modules.
JavaScript has had native modules since ECMAScript 2015.

7 © Mr. Munene
Modular programming can be performed even where the programming language lacks
explicit syntactic features to support named modules, like, for example, in C. This is done by
using existing language features, together with, for example, coding
conventions, programming idioms and the physical code structure.
Software tools can create modular code units from groups of components. Libraries of
components built from separately compiled modules can be combined into a whole by using
a linker.
Key aspects
(i) When creating a modular system, instead of creating a monolithic application (where
the smallest component is the whole), several smaller modules are built (and
usually compiled) separately so that, when composed together, they construct
the executable application program. A just-in-time compiler may perform some
of this construction “on-the-fly” at run time. This makes modular designed
systems, if built correctly, far more reusable than a traditional monolithic design,
since all (or many) of these modules may then be reused (without change) in
other projects.
(ii) Modular programming also facilitates the breaking down of projects (through “divide
and conquer”) into several smaller projects. Theoretically, a modularized
software project will be more easily assembled by large teams, since no team
members are creating the whole system, or even need to know the system as a
whole.
History
Traditional programming languages have been used to support modular programming since
at least the 1960s.
Exactly where modularized programming ends and Dynamically Linked Libraries or Object-
oriented programming starts in this context is subjective. It might be defined as the natural
predecessor of OOP, or an evolutionary step beyond it.
Advantages of Modular programming
(i) Several programmers can work on individual programs at the same time, thus
making development of a program faster.
(ii) It’s easier to debug, update and modify programs.
(iii) It leads to a structured approach as a complex problem can be broken into simpler
tasks. This strategy of developing a program is, therefore, very advantageous.

4. Object-oriented programming
OOP is a programming paradigm that uses objects (data structures consisting of data fields
and the methods that act on the data) to design applications and computer programs.

8 © Mr. Munene
Overview
- Simple, non-OOP programs may consist of a long ‘list’ of statements (or commands).
More complex programs will often group smaller sections of these statements into
functions or subroutines each of which might perform a particular task. With designs
of this sort, it is common for some of the program’s data to be global i.e. accessible
from any part of the program. As programs grow in size, allowing any function to
modify any piece of data means that bugs can have wide-reaching effects.
- In contrast, the object-oriented approach encourages the programmer to place data
where it is not directly accessible by the rest of the program. Instead, the data is
accessed by calling specially written functions, commonly called methods, which are
either bundled in with the data or inherited from class objects. These act as the
intermediaries for retrieving or modifying the data they control. The programming
construct that combines data with a set of methods for accessing and managing that
data is called an object.
- An object offers simple-to-use, standardized methods for performing particular
operations on its data, while concealing the specifics of how those tasks are
accomplished. In this way alterations can be made to the internal structure or
methods of an object without requiring that the rest of the program be modified.
This approach can also be used to offer standardized methods across different types
of objects. For example, several different types of objects might offer print methods.
Each type of object might implement the print method in a different way reflecting
the different kinds of data each contains, but all the different print methods might
be called in the same standardized manner e.g. dot notation, from elsewhere in the
program. These features become especially useful when more than one programmer
is contributing code to a project or when the goal is to reuse code between projects.
- OOP therefore focuses on data rather than processes, with programs composed of
self-sufficient modules (classes), each instance of which (object) contains all the
information needed to manipulate its own data structure (member). This is in
contrast to modular programming which focuses on the function of a module, rather
than specifically the data, though equally providing for code reuse, and self-sufficient
reusable units of programming logic, enabling collaboration through the use of
linked modules (subroutines). This more conventional approach tends to consider
data and behavior separately.
- An object-oriented program may thus be viewed as a collection of interacting
objects, as opposed to the conventional model, in which a program is seen as a list of
tasks (subroutines) to perform. In OOP, each object is capable of receiving messages,
processing data and sending messages to other objects. Each object can be viewed
as an independent “machine” with a distinct role or responsibility. The actions (or
methods) on these objects are closely associated with the object.
- SIMULA (1967) is generally accepted as the first language to have the primary
features of an object-oriented language. SMALLTALK (1972 to 1980) is arguably the

9 © Mr. Munene
canonical example and the one with which much of the theory of object-oriented
programming was developed.
- Concerning the degree of object-orientation, the following distinctions can be made
in object-oriented languages:
(i) Languages called pure OO languages because everything in them is treated
consistently as an object, from primitives such as characters and punctuation,
all the way to whole classes, prototypes, blocks, modules etc. They were
designed specifically to facilitate, even enforce, OO methods. Examples:

PYTHON

RUBY

SCALA

SMALLTALK

EIFFEL

EMERALD

JADE

SELF

(ii) Languages designed mainly for OO programming, but with some procedural
elements. Examples:

JAVA

C++

C#

DELPHI/OBJECT PASCAL

VB.NET.

10 © Mr. Munene
(iii) Languages that are historically procedural languages, but have been
extended with some OO features. Examples:

PHP

PERL,

VISUAL BASIC (DERIVED FROM BASIC)

MATLAB

COBOL 2002

FORTRAN 2003

ABAP

ADA 95

PASCAL.

(iv) Languages with most of the features of objects (classes, methods,


inheritance) but in a distinctly original form. Examples:

OBERON (OBERON-1 OR OBERON-2).

(v) Languages with abstract data type support which may be used to resemble
OO programming, but without all features of object-orientation. This
includes object-based and prototype-based languages. Examples:

JAVASCRIPT

LUA

MODULA-2

CLU.

(vi) Chameleon languages that support multiple paradigms, including OO.

TCL stands out among these for TclOO, a hybrid object system that supports
both prototype-based programming and class-based OO.

11 © Mr. Munene
PS:

An object-oriented program will usually contain different types of objects,


each type corresponding to a particular kind of complex data to be managed
or perhaps to a real-world object or concept such as a bank account, a hockey
player or a bulldozer.

A program might well contain multiple copies of each type of object, one for
each of the real-world objects the program is dealing with. For instance,
there could be one bank account object for each real-world account at a
particular bank. Each copy of the bank account object would be alike in the
methods it offers for manipulating or reading its data but the data inside
each object would differ reflecting the different history of each account.

Merits and demerits of OOP (Object Oriented Programming)

Merits

1. Through inheritance, we can eliminate redundant code and extend the use of
existing classes.

2. The code is easier to organize and maintain.

3. Code is easier to re-use.

4. The code is easier to read and understand.

5. Chances of logic errors are reduced.

6. We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.

7. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.

8. It is possible to have multiple objects to coexist without any interference.

9. It is possible to map objects in the problem domain to those objects in the program
i.e. objects in the program can represent actual objects in real life.

10. It is easy to partition the work in a project based on objects.

11. The data-centered design approach enables us to capture more details of a model
in an implementable form.

12. Object-oriented systems can be easily upgraded from small to large systems.

12 © Mr. Munene
13. Message passing techniques for communication between objects make the
interface descriptions with external systems much simpler.

14. Software complexity can be easily managed.

15. Polymorphism can be implemented i.e. behavior of functions or operators or


objects can be changed depending upon the operations.

Demerits:

1. It requires more data protection.

2. Inadequate for concurrent problems

3. Inability to work with existing systems.

4. Compile time and run time overhead.

5. Unfamiliarity causes training overheads.

OBJECT ORIENTED DATABASES (OODBs)

Object oriented databases are also called Object Database Management Systems
(ODBMS). Object databases store objects rather than data such as integers, strings or real
numbers. Objects are used in object oriented languages such as Smalltalk, C++, Java and
others. Objects basically consist of the following:

 Attributes - Attributes are data which defines the characteristics of an object. This
data may be simple such as integers, strings, and real numbers or it may be a
reference to a complex object.
 Methods - Methods define the behavior of an object and are what was formally
called procedures or functions.

Therefore objects contain both executable code and data. There are other characteristics of
objects such as whether methods or data can be accessed from outside the object. We don't
consider this here, to keep the definition simple and to apply it to what an object database
is. One other term worth mentioning is classes. Classes are used in object oriented
programming to define the data and methods the object will contain. The class is like a
template to the object. The class does not itself contain data or methods but defines the
data and methods contained in the object. The class is used to create (instantiate) the
object. Classes may be used in object databases to recreate parts of the object that may not
actually be stored in the database. Methods may not be stored in the database and may be
recreated by using a class.

Comparison to Relational Databases

13 © Mr. Munene
Relational databases store data in tables that are two dimensional. The tables have rows
and columns. Relational database tables are "normalized" so data is not repeated more
often than necessary. All table columns depend on a primary key (a unique value in the
column) to identify the column. Once the specific column is identified, data from one or
more rows associated with that column may be obtained or changed.

To put objects into relational databases, they must be described in terms of simple string,
integer, or real number data. For instance in the case of an airplane. The wing may be
placed in one table with rows and columns describing its dimensions and characteristics.
The fuselage may be in another table, the propeller in another table, tires, and so on.

Breaking complex information out into simple data takes time and is labor intensive. Code
must be written to accomplish this task.

Object Persistence

With traditional databases, data manipulated by the application is transient and data in the
database is persisted (Stored on a permanent storage device). In object databases, the
application can manipulate both transient and persisted data.

When to Use Object Databases

Object databases should be used when there is complex data and/or complex data
relationships. This includes a many – to - many object relationship. Object databases should
not be used when there would be few join tables and there are large volumes of simple
transactional data.

Object databases work well with:

 CAS Applications (CASE-computer aided software engineering, CAD-computer aided


design, CAM-computer aided manufacture)
 Multimedia Applications
 Object projects that change over time.
 Commerce

Object Database Advantages over RDBMS

 Objects don't require assembly and disassembly saving coding time and execution
time to assemble or disassemble objects.
 Reduced paging
 Easier navigation
 Better concurrency control - A hierarchy of objects may be locked.
 Data model is based on the real world.
 Works well for distributed architectures.
 Less code required when applications are object oriented.

14 © Mr. Munene
Object Database Disadvantages compared to RDBMS

 Lower efficiency when data is simple and relationships are simple.


 Relational tables are simpler.
 Late binding may slow access speed.
 More user tools exist for RDBMS.
 Standards for RDBMS are more stable.
 Support for RDBMS is more certain and change is less likely to be required.

ODBMS Standards

 Object Data Management Group


 Object Database Standard ODM6.2.0
 Object Query Language
 OQL support of SQL92

How Data is Stored

Two basic methods are used to store objects by different database vendors.

 Each object has a unique ID and is defined as a subclass of a base class, using
inheritance to determine attributes.
 Virtual memory mapping is used for object storage and management.

Data transfers are either done on a per object basis or on a per page (normally 4K) basis.

Types of OODBS

1) Hybrid object oriented databases

A hybrid database is usually an object-oriented framework created to act as an


interface between an object oriented language like C++ and a relational database
manager. The hybrid manager allows the language to access the database as though
it were truly object-oriented, while leaving the database itself unchanged.

The hybrid design allows the object-oriented programmer to use nearly any OOP
feature that they want (much like an OODBMS), while keeping the database itself
relational. This allows the use of commercially available and supported products,
allowing the “best of both worlds” i.e. object oriented and relational.

2) Persistent object oriented databases

15 © Mr. Munene
These can be looked at as persistent object stores with a DBMS (Database
Management System). Persistence is often defined as objects (and their classes in
the case of OO) that outlive the programs that create them. Object lifetimes can be
viewed as a hierarchy, with local objects having the shortest default lifetime and
objects stored indefinitely in an OODB (which are persistent) having the longest.

Persistent object stores do not support query or interactive user interface facilities,
as found in a fully supported OODBMS.

3) Pure object oriented database

A pure object-oriented database management system (OODBMS) defines all of its


data using object-oriented data structures. There are no tables, but only objects and
groups of objects. There are no required primary keys nor any foreign keys.

An object-oriented database indicates relationships by requiring each object to


contain identifiers for the objects to which it is related. To make this work, when an
object is created, it is given a unique internal identifier. The user (a programmer or
someone working interactively) never sees this identifier.

The objects in an OO database are not required to have unique keys (the equivalent
of a primary key). However, most classes are designed with a variable to hold a
unique identifier to ensure retrieval of each specific object.

OBJECT ORIENTED PROGRAMMING CONCEPTS

1) Object
- A software unit that can contain both data and the procedures that read or
manipulate the data (the procedures being called methods).
- A student object, for example, might contain data about a student (Student ID, First
Name, Last Name, Address and so on) and instructions on how to print the student
record or the formula required to calculate a student’s tuition rates. These
instructions would then be the methods, or operators, of the student object.
- The data elements are called attributes or variables.

2) Class
- It is a “template” that defines the methods and attributes / variables of a particular
type of object.

16 © Mr. Munene
Class

Object Object Object Object


1 2 3 4

- A class describes the general properties of the thing that is being modeled.
- Individual ‘objects’ are created from the class design to depict or represent each
actual thing that is being represented.
- Objects of a class are called instances.
- Class / Object example:

17 © Mr. Munene
Car
Type: Class
Colour:
Location:
Objects
Engine:
Speed:
Car Car
Type: Ford Type: Mazda
Colour: Green Colour: Blue
Location: Newcastle Location: Sunderland
Engine: On Engine: Off
Speed: 30 MPH Speed: 0 MPH
- Objects in a class share similar methods and similar type of attributes / variable.

3) Inheritance
- Each class can have one or more lower levels called subclasses. For example, fire
truck, delivery truck and dump truck are all subclasses of the higher – level class,
truck.

Super Class

Subclasses

- The higher – level class is called a super class.

18 © Mr. Munene
- Each subclass inherits the methods and attributes in its super class e.g.

The attributes of the Car super class are: color, horsepower, number of seats.
The attributes of the Racecar subclass are: color, horsepower, number of seats, nitro.
The attributes of the Truck subclass are: color, horsepower, number of seats, trailer.
i.e. the subclasses inherit attributes from the super class.
- This concept of lower level classes inheriting methods and attributes of higher level classes
is called inheritance.

4) Encapsulation
- Encapsulation means that the internal details of an object are hidden from the
user. The user knows the method that can be requested of the object but does not
know the specifics of how the method is performed e.g. while you know how to
accelerate your car, you might not know the mechanics of how the car actually
speeds up when you push the accelerator pedal. Thus, the details of your car are
encapsulated, or hidden, from you. Because encapsulation hides details of the
object, it sometimes is called information hiding.
- Typically, only the object’s own methods can directly inspect or manipulate its
fields.

5) Polymorphism
19 © Mr. Munene
- Generally, polymorphism refers to the ability to appear in many forms. For
example, given a base class SHAPE, polymorphism enables the programmer to define
different AREA methods for any number of derived classes, such as CIRCLES,
RECTANGLES and TRIANGLES. No matter what shape an object is, applying the AREA
method to it will return the correct results.

6) Relationship
- Indicates the connection between classes. This is normally expressed in the form of
ASSOCIATION.
An ASSOCIATION is a relationship between two classes e.g. a person owns a car.

Car Person

Data Data
Owns

Methods Methods

Another example:

Car Person
Engine Status Transports Age
Gear
Speed Height

startEngine ( ) driveCar ( )
stopEngine ( ) Drives
changeGear ( )

COMPARISON OF STRUCTURED PROGRAMMING AND OBJECT ORIENTED PROGRAMMING

20 © Mr. Munene
Characteristics of Procedure-Oriented Programming

 Emphasis is on doing things.


 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

Object-Oriented Programming
 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 OOP treat data as a critical element in the program development and does not allow
it to flow freely around the system.
 It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.
 OOP allows decomposition of a problem into a number of entities called objects and
then build data functions around these objects.
 The data of an object can be accessed only by the functions associated with that
object.
 Functions of one object cannot access the functions of another object.
 Follows bottom-up approach in program design.

COMPARISON BETWEEN STRUCTURED AND OOP

This will be in terms of the programming languages Pascal (for structured programming) and
C++ (for object oriented programming).

Comparison of keywords

1. Standard (ISO 7185) Pascal keywords

 and

 array

 begin

 case

 const

 div

 do

 downto

21 © Mr. Munene
 else

 end

 file

 for

 function

 goto

 if

 in

 label

 mod

 nil

 not

 of

 or

 packed

 procedure

 program

 record

 repeat

 set

 then

 to

 type

 until

 var

 while

 with

2. ANSI C++ keywords

alignas (since C++11) do register(2)


alignof (since C++11) double reinterpret_cast
and dynamic_cast requires (since C++20)
and_eq else return
asm enum short
atomic_cancel (TM TS) explicit signed
atomic_commit (TM TS) export(1) sizeof(1)
atomic_noexcept (TM TS) extern(1) static

22 © Mr. Munene
auto(1) false static_assert (since C++11)
bitand float static_cast
bitor for struct(1)
bool friend switch
break goto synchronized (TM TS)
case if template
catch import (modules TS) this
char inline(1) thread_local (since C++11)
char16_t (since C++11) int throw
char32_t (since C++11) long true
class(1) module (modules TS) try
compl mutable(1) typedef
concept (since C++20) namespace typeid
const new typename
constexpr (since C++11) noexcept (since C++11) union
const_cast not unsigned
continue not_eq using(1)
co_await (coroutines TS) nullptr (since C++11) virtual
co_return (coroutines TS) operator void
co_yield (coroutines TS) or volatile
decltype (since C++11) or_eq wchar_t
default(1) private while
delete(1) protected xor
public xor_eq

Comparison of identifiers

Identifiers can loosely be called names.

1. Identifiers in Pascal rules

- The first character can be a letter or underscore (_) but NEVER an integer.

- Subsequent characters can be letters or digits or a mix of other characters so long as they
are not special characters. For instance a space should not be found in a valid Pascal
identifier.

- Pascal is not case-sensitive.

- Examples of valid Pascal identifiers:

program PI addStudent

23 © Mr. Munene
CalculateCircleArea age calculateAge

radius _245 Student

2. C++ Identifiers

- The following characters are legal as the first character of an identifier, or any subsequent
character:

(i) underscore sign (_)

(ii) small case letters a-z

(iii) Upper case letters A-Z

- The following characters are legal as any character in an identifier except the first:

0,1,2,3,4,5,6,7,8,9.

Comparison of Comment structure

1. Pascal comments

-Are inserted into Pascal programs by enclosing the comment within { and } braces
e.g. {this is a comment}.

Note: Comments are ignored by the computer, but are helpful to explain how the
program works to other programmers.

2. C++ comments

- A C++ comment is written in one of the following ways:

(i) The /* (slash asterisk) characters, followed by any sequence of characters


(including new lines), followed by the */ characters e.g.

/* this is a comment */

(ii) The // (two forward slashes) characters, followed by any sequence of


characters. This is commonly called a single-line comment e.g.

// this is a comment

24 © Mr. Munene
Comparison of String literals

1. Pascal string literals

- Pascal string literals are enclosed by single quotation marks (‘) e.g. ‘Hello’

- Pascal string literals can directly contain any graphic character (letters, digits
or symbols) except for the single quote character (‘).
- Pascal string literals cannot span lines i.e. no new line / carriage return
characters are allowed within single quotes.

2. C++ string literals

- The literals are enclosed by double quotation marks (“) e.g. “Hello”

- String literals may contain any graphic character from the source character
set except the double quotation mark (“), backslash (\) or newline character i.e.
the C++ string literal cannot span lines.

Comparison of Constants

1. Pascal constants

- To declare a pascal constant, the keyword const is used, followed by the


name of the constant, an equals sign, the constant’s value and then a semi-
colon e.g. const PI = 3.142;

- Once declared, the constant PI can be used freely in a Pascal program. When
the program is compiled, the compiler replaces every occurrence of the word
PI with its actual value.

2. C++ constants

- C++ has two kinds of constants; literal and symbolic.

- Literal constants are literal numbers inserted into the code e.g.

int x = 5; // 5 is a literal constant

- Symbolic constants are declared through the use of the const keyword e.g.

25 © Mr. Munene
const int AgeCalculatorValue = 122;

// AgeCalculatorValue is a symbolic constant

Comparison of Punctuators

3. Pascal punctuators

Some Pascal punctuators include:

(i) Brackets []
(ii) Parentheses ()
(iii)Comma (,)
(iv) Semicolon (;)
(v) Colon (:)
(vi) Dot (.)

4. C++ Punctuators

These are ! % ^ & * ( ) - + = { } | ~

[ ] \ ; ‘ : “ < > ? , . / #

The punctuators [ ], ( ) and { } must appear in pairs.

26 © Mr. Munene
REASONS FOR EMBRACING OOP

How is OO programming different from traditional procedural programming?

1) In traditional programming, functions are written sequentially, so that a


change in programming can affect any code that follows it. In OOP on the
other hand, code and data are merged into one indivisible item, an object. An
object can represent real world things. Ideally, information about a particular
thing should reside in only one place in a system. The information within an
object is encapsulated (or hidden) from the rest of the system.
2) For traditional programming, if a function is used multiple times in a system
(i.e. a piece of code that manages the date) it is often simply cut and pasted
into each program (i.e. a change log, order function, fulfillment system, etc.).
If a date change is needed (e.g. Y2K when the code needed to be changed to
handle four numerical digits instead of two), all these pieces of code must be
found, modified and tested. In OOP on the other hand, a system is composed
of multiple objects (i.e. date function, reports, order processing etc., see figure
below).

OBJECT SYSTEM

Date
Create
It i Orders
s 22 nd
Fe
bru
a ry
Wh 19
95
at
is
tod
ay
’s
da
te
?

Report
Customer
Profiles

Inventory

When one object needs information from another object, a request is sent
asking for specific information (for example, a report object may need to
know what today’s date is and will send a request to the date object). These

27 © Mr. Munene
requests are called messages and each object has an interface i.e. a linking
mechanism to other objects that manages messages.

3) In traditional programming, code (sequences of computer instructions) and


data (information on which the instructions operate) are kept separate.
Multiple sets of code can access and modify one set of data. One set of code
may rely on data in multiple places. Multiple sets of code and data are
required to work together. Changes made to any of the code sets and data sets
can cause problems throughout the system.

In OOP on the other hand, code and data are merged into one indivisible item
– the object. Due to this structure, data will only be accessible to specific code
and not all code. This reduces the potential for errors appearing throughout a
system when changes are made to some code or data.

So what are the advantages of object-oriented programming?

1) One of the main advantages of OO programming is its ease of modification; objects can
easily be modified and added to a system thereby reducing maintenance costs.

2) OO programming is also considered to be better at modelling the real world than is


procedural programming. It allows for more complicated and flexible interactions.

3) OO systems are also easier for non-technical personnel to understand and easier for them
to participate in the maintenance and enhancement of a system because it appeals to natural
human cognition patterns.

4) For some systems, an OO approach can speed development time since many objects are
standard across systems and can be reused. Components that manage dates, shipping,
shopping carts, etc. can be purchased and easily modified for a specific system.

28 © Mr. Munene

You might also like