Upload
bang-trinh
View
216
Download
0
Embed Size (px)
DESCRIPTION
1-OO-Basics
Citation preview
29/09/2012
OO - Basics
29/09/2012 2
Introduction to Object Orientation Topics
Object technologies
Basic Principles of Object Orientation
Basic Concepts of Object Orientation
Strengths of Object Orientation
Object-oriented programming
OOP means developing software based on objects
In OOP, the data and the programming logic (the
code/functions), are both encapsulated in the object
Data and code encapsulated (combined) in an object
Procedural or structural programming focused
mainly on functions
In procedural programming, the data and the operations
that manipulate the data (the code) are separate
Data is separate from the programming logic (the
code/functions)
Object-orientation puts the focus on the
combination of function and data 3
Evolution of general-purpose programming languages
Machine code (1940s and 1950s)
Dependent on hardware architecture
No distinction between of executable instructions and data
Assembler code (1950s1970s)
Relocatable code - no fixed addresses in code but still
hardware-specific
Branch or link instructions led to spaghetti code
Executable instructions and data still
Programmable in modules with link-load to create
executable whole
4
Evolution of general-purpose programming languages
Third generation (1960s to 1990)
Compiler translate high level languages such as Fortran,
PL1, COBOL, RPC, C and many more to assembled code
Source is platform dependent, executable code is hardware
specific
Separation of code and data
Subprograms/subroutines/functions/methods
Interpreted languages (1980 to 1990)
Just-in-time translation from source to executable code
BASIC, LISP, APL, APL and many more
5
Evolution of programming styles
Third generation languages enabled coding
practices aimed at improving code quality,
reliability, readability and maintainability
Procedural:
Sequential execution
Conditional execution, loops, go to or branch to alter flow of
control
Subroutine call and return
Structured:
Decompose functionality into callable subprograms
Replace go to with nested blocks of code
Extensive use of subroutine call and return
6
Evolution of programming styles
Modular programming:
Group subroutines with related functionality in to modules
Object oriented
Paradigm shift to reusable objects with data and behavior
Service oriented
Paradigm shift to reusable objects with data and behavior
7
Some object-oriented programming languages
Simula and Simula 67 (1960s)
Early precursor to OO
Smalltalk (1970s to 1990s)
Pure OO language in part derived in part from Simula
Introduced message passing metaphor, class hierarchies
Distinctive integrated development environment with
visual coding
8
Some object-oriented programming languages
C++ (1980s to 1990s)
A hybrid of C grammar with object constructs added to the
language
Difficult to master: often used like C
Very difficult to implement an efficient compiler
Java (1990s to present day)
Architectural neutral interpreted OO language from Sun
Microsystems
Syntax similar to C++, but greatly simplified
Evolved into dominant programming platform
9
Why object-oriented programming?
Object-oriented programming enables:
A natural way of thinking
About the problem domain, not about processes and procedures.
Ability to support change:
Adapt to changing requirements
Adopt new, better, or cheaper technology with minimal impact
Manage the extensibility of a system
Code reuse
Not just copy, paste and then edit
Use existing as is and build upon it
Creation of code that can be maintained and updated
10
Considering data and function
Procedural approach:
Data and function are handled separately.
No common way to access data can be enforced easily.
Object-oriented approach:
Data and function are combined in objects.
Function becomes the behavior of objects.
The use of an object only requires knowledge of the
function names.
This hiding the data and methods (functions) inside objects
is called encapsulation.
11
The procedural approach to data and function
12
The OO approach to data and function
13
Approaches to modeling and coding
Procedural approach
Model only the business processes or the data or each separately.
The two are not modeled together.
The concept of the business and the pieces of the business are lost.
The solution becomes just a collection of functions.
OO approach
Model the business: Both structure and process.
Allows for better communication from user to analyst to designer to
programmer because they are all speaking of the business.
Allows the ability to more easily capture changes to the structure and to
the process.
14
Modeling and coding example
Requirement:
Model withdrawing money from a savings account.
Procedural approach
Identify where the data is stored.
List the algorithmic steps necessary.
Object approach
Identify what objects are involved.
Example: Bank, savings account, teller and transaction
Show how these objects interact to:
Enforce business rules for withdrawals.
Decrement the balance. 15
Code reuse is a key benefit of OOP
Procedural
Hard to identify opportunities to reuse code because of the lack of
encapsulation
Reusability happens at the procedural level
Objects
Reuse of code, writing functions once and using them again in other
objects (similar to procedural).
Reuse of objects or a set of objects, since these are business objects
they can be reused throughout the enterprise.
Reuse of function names or sets of function names, in the procedural
approach multiple functions cannot have the same name, however with
objects, a function name can be reused for different objects with
different implementations.
16
Code reuse is limited in procedural code
17
OOP facilitates reuse of code
18
OOP facilitates reuse of objects
19
OOP facilitates reuse of names
20
Communication in the development team
Procedural approach
Differences documents and styles of working are used during system
analysis, design, and programming.
Each stage ends with a milestone or sign off.
The resulting throw it over the wall approach can lead to
miscommunication.
Object-oriented approach
The same language is used for analysis, design, implementation
The language is objects
It is often written visually in the Unified Modeling Language (UML)
This leads to better communication between analyst, designer and
programmer.
21
Benefits provided by objects
22
29/09/2012 23
Object Orientation
En
cap
sula
tio
n
Ab
stra
ctio
n
Hie
rarc
hy
Mo
du
lari
ty
Basic Principles of Object Orientation
29/09/2012 24
What Is Abstraction?
The essential characteristics of an entity that
distinguishes it from all other kinds of entities.
Defines a boundary relative to the perspective of
the viewer.
Is not a concrete manifestation, denotes the ideal
essence of something.
29/09/2012 25
Salesperson
Not saying
Which
salesperson
just a salesperson
in general!!!
Customer Product
Manages Complexity
What is Abstraction?
29/09/2012 26
What Is Encapsulation?
Improves Resiliency
Hides implementation from clients.
Clients depend on interface.
29/09/2012 27
Encapsulation
"Encapsulation is a mechanism used to hide the data, internal structure, and implementation details of an object. All interaction with the object is through a public interface of operations." (Craig Larman)
A boundary exists around each object; the boundary encapsulates the objects characteristics (data elements) and behaviors (functionality).
The reason for hiding features is to:
(1) keep users from touching parts of the object they shouldnt touch;
(2) allows creator of the object to change the objects internal working without affecting the users of the object.
29/09/2012 28
Order Processing
System
Billing
Order
Entry
Order
Fulfillment
Manages Complexity
What is Modularity?
The breaking up of something complex into
manageable pieces
Helps people understand complex systems.
29/09/2012 29
Decreasing
abstraction
Increasing
abstraction
Asset
RealEstate
Savings
BankAccount
Checking Stock
Security
Bond
Elements at the same level of the hierarchy
should be at the same level of abstraction
What is Hierarchy?
Levels of abstraction
29/09/2012 30
Basic Concepts of Object Orientation
Object
Class
Attribute
Operation
Interface (Polymorphism)
Component
Package
Subsystem
Relationships
29/09/2012 31
Informally, an object represents an entity, either
physical, conceptual, or software
Physical entity
Conceptual entity
Software entity
Truck
Chemical Process
Linked List
What is an Object?
29/09/2012 32
A More Formal Definition
An object is a concept, abstraction, or thing with
sharp boundaries and meaning for an application
An object is something that has:
State
Behavior
Identity
A real live object
33
A person object
34
29/09/2012 35
OO Principle: Abstraction
What is a Class?
A class is a description of a group of objects with
common properties (attributes), behavior
(operations), relationships, and semantics
An object is an instance of a class
A class is an abstraction in that it:
Emphasizes relevant characteristics
Suppresses other characteristics
What is necessary to define a class
Name
The class name needs to specify what the abstraction is
capturing. The name of the class should:
Be singular Clearly identify the concept
Not be too vague or general Be short and concise
List of data elements
The pieces of data that need to be captured for the
abstraction.
List of messages
The messages (and their implementation, methods) that the
abstraction can receive.
36
29/09/2012 37
a + b = 10
Class
Course
Properties
Name
Location
Days offered
Credit hours
Start time
End time
Behavior
Add a student
Delete a student
Get course roster
Determine if it is full
Sample Class
29/09/2012 38
Representing Classes in the UML
A class is represented using a rectangle with three
compartments:
The class name
The structure (attributes)
The behavior (operations)
Professor
- name
- employeeID : UniqueId
- hireDate
- status
- discipline
- maxLoad
+ submitFinalGrade()
+ acceptCourseOffering()
+ setMaxLoad()
+ takeSabbatical()
+ teachClass()
29/09/2012 39
Classes of Objects
How many classes do you see?
The difference between a class and a table
40
29/09/2012 41
Object
s Clas
s
Professor Smith
Professor Jones
Professor
The Relationship Between Classes and Objects
A class is an abstract definition of an object
It defines the structure and behavior of each object in
the class
It serves as a template for creating objects
Objects are grouped into classes
29/09/2012 42
What Is an Attribute?
An attribute is a named property of a class that describes
the range of values that instances of the property may
hold.
A class may have any number of attributes or no attributes
at all.
Attributes
Student
- name
- address
- studentID
- dateOfBirth
29/09/2012 43
What Is an Operation?
A service that can be requested from an object to effect
behavior. An operation has a signature, which may restrict
the actual parameters that are possible.
A class may have any number of operations or none at all.
Operations
Student
+ get tuition() + add schedule() + get schedule() + delete schedule() + has prerequisites()
29/09/2012 44
What Is Polymorphism?
Manufacturer A Manufacturer B
Manufacturer C
OO Principle:
Encapsulation Remote Control
The ability to hide many different implementations behind
a single interface.
29/09/2012 45
Polymorphism
Occurs with inheritance.
Different subclasses may have different implementations of the identical operations
Allows you to treat an object as the base class, rather than as a specific inherited type.
Programmer doesnt have to keep track of the specific subclasses, the system selects the correct operation based on the object type.
Accomplished at run time using dynamic binding.
lets you substitute objects that have identical interfaces for each other at run-time.
29/09/2012 46
Tube
Pyramid
Cube
Shape
Draw
Move
Scale
Rotate
Realization relationship (stay tuned for realization relationships)
What is an Interface?
Interfaces formalize polymorphism
Interfaces support plug-and-play architectures
29/09/2012 47
Interface
How do you get an object to do useful work for you?
Objects are known only through their interfaces
Every object presents an interface to the world.
Interface determines what you can get an object to
do.
Represent a "contract" with other objects.
Communicate with objects by sending messages to
them; an objects interface is the set of messages
an object will respond to.
29/09/2012 48
A package is a general purpose mechanism for
organizing elements into groups
A model element which can contain other model
elements
Uses
Organize the model under development
A unit of configuration management
Package Name OO Principle:
Modularity
What is a Package?
29/09/2012 49
A combination of a package (can contain other
model elements) and a class (has behavior)
Realizes one or more interfaces which define its
behavior
OO Principles: Encapsulation and Modularity
Subsystem Name
Interface Interface
Realization Subsystem
What is a Subsystem?
29/09/2012 50
A non-trivial, nearly independent, and replaceable
part of a system that fulfills a clear function in the
context of a well-defined architecture
A component may be
A source code component
A run time components or
An executable component
Source File
Name
OO Principle:
Encapsulation
What is a Component?
Component
Name Component
Interface
Executable
Name
29/09/2012 51
Component
Name
Design Model Implementation Model
Component Name Component
Interface
Component
Interface
OO Principles: Encapsulation and Modularity
Subsystems and Components
Components are the physical realization of an
abstraction in the design
Subsystems can be used to represent the
component in the design
29/09/2012 52
Relationships
Association
Aggregation
Dependency
Generalization
Realization
ConsoleWindow
Window
open() close() move() display() handleEvent()
Event
DialogBox Control
association generalization
29/09/2012 53
Professor University Works for
Class
Association
Association
Name
Relationships: Association
Models a semantic connection among classes
29/09/2012 54
Relationships: Association Aggregation
To model a whole/part relationship, use
aggregation.
Aggregation represents a has-a or is a part-
of relationship, meaning that an object of the
whole has objects of the part. [Martin Fowler]
Company Department * 1
29/09/2012 55
Association: Multiplicity and Navigation
Student Schedule 1 0..*
Multiplicity
Navigation
Multiplicity defines how many objects participate in a relationships
Specified for each end of the association
Associations are bi-directional by default, but it is often desirable to restrict navigation to one direction
If navigation is restricted, an arrowhead is added to indicate the direction of the navigation
29/09/2012 56
Packag
e
ClientPackage SupplierPackage
Client Supplier Class
Dependency
relationship Client Supplier
Dependency
relationship
Componen
t
Relationships: Dependency
A relationship between two model elements where a change
in one may cause a change in the other
E.g. Class A depends on class B: method of A manipulates objects of B
in the parameters, local variables, or return types
29/09/2012 57
Tube
Pyramid
Cube
Shape
Draw
Move
Scale
Rotate
Realization relationship (stay tuned for realization relationships)
Relationships: Realization
29/09/2012 58
Inheritance
[Martin Fowler]
Shape origin
draw() erase() move() setColor() getColor()
Circle
draw() erase()
Square
draw() erase() move()
29/09/2012 59
Polymorphism
[Martin Fowler]
Goose
move()
Penguin
move()
FlockManager
reLocate()
Bird
move()
29/09/2012 60
Airplane Helicopter Wolf Horse
FlyingThing Animal
Bird
multiple
inheritance
Use multiple inheritance only when needed, and
always with caution !
Example: Multiple Inheritance
A class can inherit from several other classes
29/09/2012 61
Inheritance leverages the similarities among classes
What Gets Inherited?
A subclass inherits its parents attributes,
operations, and relationships
A subclass may:
Add additional attributes, operations, relationships
Redefine inherited operations (use caution!)
Common attributes, operations, and/or
relationships are shown at the highest applicable
level in the hierarchy
29/09/2012 62
Truck
tonnage
GroundVehicle
weight
licenseNumber
Car
owner
register( )
getTax( )
Person
0..*
Trailer
1 Superclass
(parent)
Subclass
generalization
size
Example: What Gets Inherited
29/09/2012 63
The Strengths of Object Technology
Provides a single paradigm
A single language used by users, analysts, designers, and implementers
Facilitates architectural and code reuse
Models more closely reflect the real world
More accurately describes corporate entities
Decomposed based on natural partitioning
Easier to understand and maintain
Provides stability
A small change in requirements does not mean massive changes in the
system under development
Is adaptive to change