Download Object-Oriented Programming: Understanding Modularity and UML Diagrams and more Papers Computer Science in PDF only on Docsity!
Object-Oriented Paradigm
CS350/SE
Fall, 2008
Software Design
–Find a Solution
Consider the example of an instructor at a
conference. People in your class have another
class to attend following yours, but don’t know
where it is located. You are responsible to
make sure everyone knows how to get to the
next class.
A Natural Solution
1.Get a list of people in the class
2. For each person on this list, do the following:
1. Find the next class he or she is taking
2. Find the location of that class
3. Find the way to get from your classroom to
the next person’s class
4. Tell the person how to get to his or her next
class.
A Natural Solution
To do this would require the following
procedures:
1. A way of getting the list of people in the class
2. A way of getting the schedule for each person
in the class.
3. A program that gives someone directions
from your classroom to any other classroom
4. A control program that works for each person
in the class and does the required steps for
each person
Is that reality?
Probably not.
More likely, you would post directions to go
from this classroom to all other classrooms and
then tell everyone in the class what you did and
to use the directions to go to their next class.
This is a philosophical difference. It’s a shift in
responsibility.
Shift In Responsibility
First Method: Responsibility is solely with the
instructor, thus you, thus leads to insanity.
Second Method: Responsibility is divided
amongst others.
What happens if requirements
change?
Say have a new type of student, aka a grad
student.
FIRST METHOD: The control program would
have to be modified to distinguish grad students
from undergrad students.
SECOND METHOD: People are responsible for
themselves, therefore the change would be
localized to a routine for the new duty of the grad
student.
The control program does not change!
The Object-Oriented Paradigm
Centered on the concept of the object.
What is an object?
–Traditionally: data with method.
–Better Definition: Things responsible for
themselves.
OO Elements –Classes/Objects
Abstract classes define what other, related
classes can do.
These “other” classes are classes that
represent a particular type of related behavior.
Such a class is called a concrete class.
Therefore, UndergradStudent and
GraduateStudent would be concrete classes.
The relationship between an
OO Elements--Relations
The relationship between an
UndergradStudent and a Student class is called
a is-a relationship.
An is-a relationship is a form of inheritance.
Abstract classes act as placeholders for other
concrete classes.
Abstract classes define the methods their
derived classes must implement.
The Object-Oriented Paradigm
Three levels of accessibility:
- Public – Anything can see it
- Protected – Only objects of this class and
derived classes can see it
- Private – Only objects from this class can see
it
The Object-Oriented Paradigm
Encapsulation is not just about data, it’s about any kind of hiding!
In our previous examples, the type of student is in essence hidden from the control program (in essence, because it has to instantiate it and thus know what type of object it is).
This encapsulation is known as polymorphism.
Polymorphism can be defined as the ability to refer to different derivation of a class in the same way, but getting the behavior appropriate to
Does OO ease programming?
doesn’t necessarily make the initial coding
easier.
Instead, it reduces the effort to maintain code in
the long run.
This should not be trivialized
–writing a program that works the first time is
easy.
–writing a program that continues to meet the
needs of its users is quite another challenge.
Many bugs originate with changes to code.
Why do programs fail in the “real
world”?
Most of you should have had some co op experience and therefore a taste of the real world. In academics the problem
- you are solving is usually clearly laid out.
- Expectations are well defined. This is not the case in the real world. While a program can fail because:
- Technological problems
- Incompetent Programmers
- Poor Management
- Poor Development Tools The #1 reason projects fail is poor requirements gathering.
The Reality
Why are requirements poor?
- Requirements are incomplete
- Requirements are often wrong
- Requirements (and users) are misleading
- Requirements do not tell the whole story This happens for a lot of reasons and they are often classified as the dreaded communication problems. While one tries to document requirements completely and properly, the reality is, for many reasons you will not achieve a perfect set of requirements. If you do not have good requirements, how can programmers possibly be expected to develop an application that meets the needs of the end user. The reality is, requirements always change.
How do you handle change?
Example of change: bug is discovered!
We really do not spend much time fixing the
bug
Instead, we spend a lot of time:
- Discovering how the code works
- Finding the bug
- Taking time to avoid unwanted side effects when
we correct the code
Software Modularity
Examples:
A math library of routines to support
trigonometry is weak or strong cohesion?
An object calls another objects method with 8
parameter method is tight or loose coupling?
The main goal (almost not evident) of design is to minimizeThe main goal (almost not evident) of design is to minimize The main goal (almost not evident) of design is to minimizeThe main goal (almost not evident) of design is to minimize couplingcoupling couplingcoupling and maximizeand maximizeand maximizeand maximize cohesioncohesioncohesioncohesion....
Coupling is the level of interdependency between a method andCoupling is the level of interdependency between a method andCoupling is the level of interdependency between a method andCoupling is the level of interdependency between a method and itsitsitsits environmentenvironmentenvironmentenvironment, (other methods, objects and classes),, (other methods, objects and classes),, (other methods, objects and classes),, (other methods, objects and classes),
while Cohesion is the level of uniformity of the method goal.while Cohesion is the level of uniformity of the method goal.while Cohesion is the level of uniformity of the method goal.while Cohesion is the level of uniformity of the method goal.
Yourdon, E.; Constantine, L L. (1979).
Structured Design: Fundamentals of a
Discipline of Computer Program and
Systems Design, copyright 1979 by
Prentice-Hall, Yourdon Press.
The Unified Modeling Language
The Unified Modeling Language (UML)
A standard language for
- specifying, visualizing, constructing, and
documenting the artifacts of software systems,
- business modeling and other non-software
systems.
The UML represents
- a collection of best engineering practices
- that have proven successful in the modeling of
large and complex systems.^1
The UML helps project teams
- communicate, explore potential designs,
- validate the architectural design of the software.
The UML Diagrams
Use Case Diagram
Class Diagram
Interaction Diagrams
- Sequence Diagram
- Collaboration Diagram
State Diagram
Activity Diagram
Physical Diagrams
- Component Diagram
- Deployment Diagram
The Use Case Diagram
The State Diagram
The Activity Diagram
The Class Diagram –A Class
Attributes
Class Name
Operations
The Class Diagram –Association
Multiplicity
Many valued Mandatory
The Class Diagram –
Implementation Inheritance (Generalize/Specialize)
The Class Diagram –
Interface Inheritance (Specifies/Redefines/Realizes)
The Class Diagram
–Other Major Relations
Dependencies (Use/Creates)
Aggregation
Composition
The Maze Game UML
UML Tools
Proprietary
- Rational Rose
- Visio
- OmniGraffle
Open Source
- Dia (http://live.gnome.org/Dia)
- Eclipse MDT UML
(http://www.eclipse.org/modeling/mdt/downloads/
?project=uml2)
- BOUML (http://bouml.free.fr)
- ArgoUML (http://argouml.tigris.org)
References
UML Distilled by Martin Fowler
http://www.holub.com/goodies/uml
How it works…!
Java is independent only for one reason:
- Only depends on the Java Virtual Machine
(JVM),
- code is compiled to bytecode , which is
interpreted by the resident JVM,
- JIT (just in time) compilers attempt to
increase speed.
Object-Oriented
Java supports OOD
- Polymorphism
- Inheritance
- Encapsulation
Java programs contain nothing but definitions and instantiations of classes
- Everything is encapsulated in a class!
Java Advantages
Portable - Write Once, Run Anywhere
Security has been well thought through
Robust memory management
Designed for network programming
Multi-threaded (multiple simultaneous tasks)
Dynamic & extensible (loads of libraries)
- Classes stored in separate files
- Loaded only when needed
Basic Java Syntax
Primitive Types and Variables
boolean, char, byte, short, int, long, float, double etc.
These basic (or primitive) types are the only types
that are not objects (due to performance issues).
This means that you don’t use the new operator to
create a primitive variable.
Declaring primitive variables:
float initVal; int retVal, index = 2; double gamma = 1.2, brightness boolean valueOk = false;
Initialisation
If no value is assigned prior to use, then the
compiler will give an error
Java sets primitive variables to zero or false
in the case of a boolean variable
All object references are initially set to null
An array of anything is an object
- Set to null on declaration
- Elements to zero false or null on creation
Declarations
int index = 1.2; // compiler error
boolean retOk = 1; // compiler error
double fiveFourths = 5 / 4; // no error!
float ratio = 5.8f; // correct
double fiveFourths = 5.0 / 4.0; // correct
1.2f is a float value accurate to 7 decimal places.
1.2 is a double value accurate to 15 decimal places.
All Java assignments are right associative
int a = 1, b = 2, c = 5
a = b = c
System.out.print(
“a= “ + a + “b= “ + b + “c= “ + c)
What is the value of a, b & c Done right to left: a = (b = c);
Assignment
Relational Operators
== Equal (careful)
!= Not equal
>= Greater than or equal
<= Less than or equal
> Greater than
< Less than
If… else
The if … else statement evaluates an expression and
performs one action if that evaluation is true or a
different action if it is false.
if (x != oldx) {
System.out.print(“x was changed”); } else { System.out.print(“x is unchanged”); }
Nested if … else
if ( myVal > 100 ) { if ( remainderOn == true) { myVal = mVal % 100; } else { myVal = myVal / 100.0; } } else { System.out.print(“myVal is in range”); }
else if
Useful for choosing between alternatives:
if ( n == 1 ) { // execute code block # } else if ( j == 2 ) { // execute code block # } else { // if all previous tests have failed, execute code block # }
A Warning…
WRONG!
if( i == j )
if ( j == k ) System.out.print( “i equals k”); else System.out.print( “i is not equal to j”);
CORRECT! if( i == j ) { if ( j == k ) System.out.print( “i equals k”); } else System.out.print(“ i is not equal to j”); // Correct!
The switch Statement
switch ( n ) {
case 1:
// execute code block
break;
case 2:
// execute code block
break;
default:
// if all previous tests fail then
//execute code block
break;
The for loop
Loop n times for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n- } Nested for: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } }
while loops
while(response == 1) {
System.out.print( “ID =” +
userID[n]);
n++;
response = readInt( “Enter “);
What is the minimum number of times the loop
is executed?
What is the maximum number of times?
myArray has room for 8 elements
the elements are accessed by their index
in Java, array indices start at 0
myArray = 3 6 3 1 6 3 4 1
0 1 2 3 4 5 6 7
Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory,
labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
Assigning Values
refer to the array elements by index to store values in
them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Iterating Through Arrays
for loops are useful when dealing with arrays:
for (int i = 0; i <
myArray.length; i++) {
myArray[i] = getsomevalue();
Arrays of Objects
So far we have looked at an array of primitive types.
- integers
- could also use doubles, floats, characters…
Often want to have an array of objects
- Students, Books, Loans ……
Need to follow 3 steps.
Declaring the Array
1. Declare the array
private Student studentList[];
- this declares studentList
2 .Create the array
studentList = new Student[10];
- this sets up 10 spaces in memory that can
hold references to Student objects
3. Create Student objects and add them to the
array: studentList[0] = new
Student("Cathy", "Computing");
Java Methods & Classes
Classes ARE Object Definitions
OOP - object oriented programming
code built from objects
Java these are called classes
Each class definition is coded in a
separate .java file
Name of the object must match the
class/object name