Object Oriented Programming (OOP)

oatmealbrothersSoftware and s/w Development

Nov 18, 2013 (3 years and 11 months ago)

115 views

Object Oriented Programming (OOP)
1

OOP was developed in response to the growing complexity of programs, and the
growing size of programming teams. The original imperative style starts to fall apart
because the complexity of the task becomes hard to
manage. Fortunately OOP and
design principles still make sense for our small programs...



“Imperative” languages are the oldest and
most common. They are structured a lot
like a cooking recipe, data structures
(ingredients) at the start, then code
implem
enting the algorithms
(instructions).

“OO” languages are better for large
complex tasks (and teams) because they
group specific data and the algorithms
that work on it into well managed
stru
c
tures called objects.


All the cooks share one kitchen


chaos!

Each cook in their own small kitchen.


Y11 programs were written in Visual
Basic.Net, an OO Object Oriented
language but they didn’t explicitly use
OOP. The design of the programs was
simple imperative style.

Y13 programs must be explicitly OO (but
only t
he basic OO concepts).



In the language of OOP an object is a way of organising data and the processes /
algorithms that operate on the data into a coherent whole. Objects can be thoug
ht of
as "entities"
having state (the values of the data) and behaviou
r (the actions /



1
Material for CS4HS Anthony Robins & Sandy Garner Christchurch, December 2012, University of
Otago, http://www.cs.otago.ac.nz/staffpriv/anthony/cs4hs.html


algorithms performed by its methods).

For example:

A playing card object’s state might be the rank of the card (Ace, for example), the suit
of the card, and whether it’s face up or not
.

We call the things we use to keep track of an
object’s state that object’s

fields

Although there are some cases where keeping an object’s state hidden makes sense,
there are also plenty of times where something outside the object needs to know its
state. For the playing card example, we’re probably go
ing to need to know the rank
and suit of the card and whether or not its face up.

Because it’s so common for us to need
to access an object’s state
, C# enables us to
do that easily through
properties

By behaviour of an object we mean what actions the obje
ct can take. What can we ask
it to do, or what can we do to it?

For the card object
, we’ll want to flip it over, so we
need the card object to do that for us.

We call the things we use to specify an object’s behaviour that object’s
methods.


Objects are ma
de from
classes
. A class is some code that we write which defines and
groups

related data (data fields / instance variables) and methods. An object is an
implementation of the class in the computer’s memory when the program runs. There
are usually two (main) kinds of objects:

(1) Class objects: There is one and only one class obje
ct for each class in the
program. This includes built in / library classes and the ones that we write for
ourselves. Class objects serve as a kind of “blueprint” for creating instance objects.

(2) Instance objects: We make instance objects out of class obj
ects, we can make as
many as we like. Instance objects are the “typical” objects of OOP, the ones we
usually make to represent aspects of the task or its solution (the “entities” or “agents”
discussed above).

Example in C Sharp (
C#)

The following code decl
ares a class with single data instance variable / data field, a
constructor (method used to make instance objects) and an ordinary method.


class

Person


{


//create a single data field


string

name;



//the constructor method (in
itialise field(s))


public

Person(
string

n)


{


name = n;


}


//another method


public

void

show()


{


Console
.WriteLine(
"My name is "

+ name);


}


}

In the main method we can make two

instances of the class (using
constructor), and call the show method on each instance.


static

void

Main(
string
[] args)


{


Person

p1 =
new

Person
(
"Tom"
);


Person

p2 =
new

Person
(
"Sue"
);


p1.show();



p2.show();


Console
.ReadLine();


}

The Output is:


My name is Tom


My name is Sue

At this point the objects in the program include a single class object
Person
and two instances of Person called
p1
and
p2
.

Summary of
Vocabulary of OOP
2

What sometimes puts people off from working with objects is the tendency to use big
words to refer to perfectly ordinary concepts.
Here is a

short vocabulary list:

class
the recipe or blueprint for creating an object

object
a thing


instantiate
the action of creating an object from a class

method
a function that belongs to an object

property
a variable that belongs to an object

The class is a blueprint

a set of instructions for how to create an object. It isn’t a real
object

it just describes o
ne.


Encapsulation


The point of OOP is to put into classes the data and methods that “belong together”
(represent a logical chunk of the task that the program is about).

We represent the main aspects of the task with classes. The more self
-
contained and
robust those classes are (the easier to move between programs) the better we have
done our job.

There is lots of OO terminology and theory relating to ideas of good OO

design, but

the term used in the Standard is encapsulation. It’s a fuzzy concept, a
combination of
two closely related ideas, that the programmer should (1) bundle together data and
the methods operating on it (into classes / objects), and (2) restrict access to some
data or methods.





2

(2011). Home
-

PHP Master: Write Cutting
-
Edge Code
-

SitePoint. Retrieved April 29, 2013


Why would we as programmers want to “restrict access”
to data?

To keep it safe

and

Information hiding is a very powerful technique because we can use the object without
having to know how it works internally; we can just view the object as a black box.
Why is this helpful? Because if we end up changing the i
nternals of the object later on,
we don’t break all the code that uses it.

Inside the class vs. outside the class

The theory of OOP assumes that code inside a class is all trusted and tested to work
with itself. We can have direct access to all instance va
riables / data fields. Code
inside a class looks like the code that we wrote at Year 11, we simply access the data
that we need.

But we write a class to protect data from direct access from outside the class. Because
code outside the class we don’t trust a
t all! Some other mad programmer might be
working on other classes, or this class might be moved to another program
completely, so we need to make the internal workings of this class impossible to
break. So we use features of the programming language to ke
ep the data safe. We
encapsulate the data.

A key example

Imagine a class

Person
(based e.g. on the example above) with lots of data and
methods, including an instance variable / data field called

age
.
Imagine that in the
main routine / method I have made dozens of instances, including
p2
.

If in the main routine / method (outside the class! beware!) the statement


p2.age = 21
is possible and simply updates age then we have
direct access

to
that data (the
re is no good encapsulation of age).

We might not want programmers to have direct access. It might be the case that any
time we update

age
it makes sense (in the context of the task) to update other
variables ( e.g
.
years_of_service

) or perform various ch
ecks (does the person now
qualify to vote, qualify for a pension, should we send them a letter to congratulate
them on reaching 100, and so on).

If the programmer has

direct access

from outside then none of these task constraints
can be enforced. But if th
e class

uses features of the language to

enforce good

encapsulation

then it shouldn’t be possible to

change

age
without
all the associated
changes and checks happening too.

Restrict access and make it safe. That’s how we make good,
robust
, re
-
usable
programs!

What features of the language?

So what are the “features of the language” that we use to manage access to data
(enforce good encapsulation)? The details vary, the concepts are very similar.

In C# (and Java) we make data fields private, which make
s direct access from outside
the class impossible. We manage access to data via special methods called

get
methods
(getters, accessors)

and

set methods

(setters, mutators).


Think of it this way:
get means to read, set means to write.


Changing age from th
e main method might look like this

p2.setAge(21)
with the

setAge
method implementing constraints and checks.

Encapsulation Example

1


Start a new Console Application called encapsulation1.

Paste this code in

(it contains the Main program and a Calculate Retail class)
:

using

System;

using

System.Collections.Generic;

using

System.Linq;

using

System.Text;


namespace

enscapulation

{


public

class

CalculateRetail


{


public

decimal

wholesalePrice = 500.00m;





public

decimal

RetailPrice()


{


return

wholesalePrice*1.50m;


}


}


class

Program


{


static

void

Main(
string
[] args)


{


CalculateRetail

myAccount =
new

CalculateRetail
();


decimal

myPrice = myAccount.RetailPrice();


decimal

theWholesalePriceis = myAccount.wholesalePrice;


/* This Main method can access the retail price and the wholesaleprice and it can


manipul
ate the wholesale price because the wholesalePrice is declared public */


Console
.WriteLine(myPrice);


Console
.WriteLine(
"the wholesale price is "

+theWholesalePriceis);


Console
.ReadLine();


}


}

}


Run the
program.

We get


The
CalculateRetail
class’ fields are able to be seen and manipulated. Not ideal if you
don’t want
“customers” to be able to find out the mark up from wholesale to retail.


In your code in the
line
public

decimal

wholesalePrice = 500.00m;
change the accessor
modifier
,
public

to

private
.


We now get this error message:

'enscapulation.CalculateRetail.wholesalePrice' is inaccessible due to its protection
level
.

This means other classes cannot see (or access) the whol
esalePrice.

Remove these lines:


decimal

theWholesalePriceis = myAccount.wholesalePrice;


Console
.WriteLine(
"the wholesale price is "

+theWholesalePriceis);



Adjust your code to:


public

class

CalculateRetail


{


private

decimal

wholesalePrice = 500.00m;





public

decimal

RetailPrice()


{


return

wholesalePrice*1.50m;


}


}


class

Program


{


static

void

Main(
string
[] args)


{


CalculateRetail

myAccount =
new

CalculateRetail
();


decimal

myPrice = myAccount.RetailPrice();



/* This Main method can calculate the retail price via the public


* "RetailPrice" method provided by the "CalculateRetail" class


* but

it cannot manipulate the value of "wholesalePrice" */


Console
.WriteLine(
"the retail price is "
+myPrice);


Console
.ReadLine();


}


}

Note:
Review (or do) Chapter on
Classes and Objects in C# .NET
in
CSharp.net pdf p277