Professional Documents
Culture Documents
Object-Oriented Analysis and Design Course Book: Aron Trauring Class 2 April 12th, 2005
Object-Oriented Analysis and Design Course Book: Aron Trauring Class 2 April 12th, 2005
Object-Oriented Analysis and Design Course Book: Aron Trauring Class 2 April 12th, 2005
Aron Trauring
Class 2 April 12th, 2005
Class Agenda
9:00-12:30 Core OO Concepts from a Programming Perspective Python - Part II (Presentation)
12:30-1:30 Lunch
1:30-3:15 Introduction to the UML
3:15-5:00 Object-Oriented Analysis/Design and Use Cases
Instructor
Aron Trauring CEO, Zoteca
Email: atrauring@zoteca.com
Personal Website: http://aronst.org/
Zoteca Corporate Website: http://www.zoteca.com/
FOSS Resources: http://www.fourm.info/
NYSIA - CISDD
NYSIA - CISDD
print phone[Aron]
phone[Aron] = 9174966776
print phone[Aron]
Functions
def square(x):
return x*x
print square(3)
def modifylist(x,y):
x[0] = y
q = [1,2,3]
print q[0]
modifylist(q,5)
print q[0]
def nomodify(r):
r = 1
s = 5
print s
nomodify(s)
print s
joe = square
print joe(3)
#
#
#
#
Assign to name.
Shared class data
Methods
Per-instance data
NYSIA - CISDD
Class Objects
Provide default behavior and serve as instance factories
Python class statement is an executable statement (not a declaration) run from top to bottom
When reached and run, it generates a new class object and assigns it to the name in the class
header
Assignments inside class statements make class attributes
After running a class statement, class attributes are accessed by name qualification: object.name
Attributes of a class object record state information and behavior, to be shared by all instances
created from the class
Function def statements nested inside a class generate methods, which process instances
Instance Objects
Instances represent concrete items in your programs domain
Each instance object inherits class attributes and gets its own namespace
Instance objects start out empty, but inherit attributes that live in the class object they were
generated from
Inside class method functions, the first argument (called self by convention) references the
instance object being processed
Assignments to attributes of self create or change data in the instance, not the class
Mini Exercise 1
Basic Namespace
>>>
>>>
>>>
>>>
>>>
?
>>>
>>>
>>>
>>>
?
>>>
?
>>>
?
NYSIA - CISDD
NYSIA - CISDD
>>> s2.OneGlob
?
>>> One.OneGlob
?
>>> s1.OneGlob
?
Key Ideas
Conceptual: Classes serves as template for instance provide default behavior and serve as
instance factories
Protocol: Methods can be for Class or Instance
Implementation: Scope of both data and methods can be local to Class or to Instance
Inheritance Benefit of Objects
Set of attributes passed to descendants
Conceptual Is-A Relationship Defines sets of responsibilities down the tree
Protocol (Interface) Customization / Specialization Sub-classes can replace, provide or extend behaviors of parent classes
Implementation Code reuse
object.attribute
object is derived from a class instantiation
attribute is a name found by a search in object and all its ancestors
Search algorithm: find the first occurrence of attribute by looking in object, and all classes
above it
Inheritance objects linked into a class tree are the union of all the attributes defined in
all their tree parents (ancestors), all the way up the tree
In Python, this is literal: it builds up trees of linked objects with code, and really does climb
this tree at runtime searching for attributes, every time we say object.attribute
Multiple inheritance left to right search
NYSIA - CISDD
Mini Exercise 2
NYSIA - CISDD
def myresign(self):
print "I resign you SOB"
class PizzaRobot(Chef):
def __init__(self, name):
Chef.__init__(self, name)
def work(self):
print self.name, "makes pizza"
if __name__ == "__main__":
bob = PizzaRobot(bob)
print bob
bob.work( )
bob.giveRaise(0.20)
print bob; print
print "Work:"
for klass in Employee, Chef, Server, PizzaRobot:
obj = klass(klass.__name__)
obj.work( )
print ; print "Resign:"
joe = Server(joe)
joe.resign()
$ python employees.py
<Employee: name=bob, salary=50000>
bob makes pizza
<Employee: name=bob, salary=60000.0>
Work:
Employee does stuff
Chef makes food
Server interfaces with customer at counter 1
PizzaRobot makes pizza
Resign:
I resign you SOB
Python code allows you to quickly build a working model of domain layer
Protocol Classes are Customized by Inheritance
giveRaise in inherited from the base Employee super-class and can be used in all sub-classes
work is replaced (over-ridden) in each of the sub-classed employees
work is extended in the Server sub-class by adding the counter parameter
Employee delegates resign which is provided by Server
Implementation Code Reuse
PizzaRobot trivial to implement
New types of employees can be added with minimal amount of coding
Aron Trauring - Zoteca
NYSIA - CISDD
10
NYSIA - CISDD
a=3
a
b=a
b
b=spam
b
a
b=a
b
a=spam
b
c
a = b = 3
a = 4
print a, b
Built-in Types
Object Type
Number
Strings
Tuples
Lists
Dictionaries
Files
Examples
3.1415, 1234, 999L, 3+4j
spam, "guidos"
(1,spam, 4, U)
[1, [2, three], 4]
{food: spam, taste: yum}
text = open(eggs, r).read( )
Category
Immutable
Immutable Sequence
Immutable Sequence
Mutable Sequence
Mutable Mapping
Lists are ordered collections of other objects, and indexed by positions that start at 0.
Dictionaries are collections of other objects that are indexed by key instead of position.
Aron Trauring - Zoteca
11
NYSIA - CISDD
Both dictionaries and lists may be nested, can grow and shrink on demand, and may contain
objects of any type
Mutability means applying a method
Built-in Types and Classes
In modeling at any level, there is no distinction between types and classes
In Python, built-in types and defined classes operate in an identical fashion
In Python, built-in types may be sub-classed
Smaller conceptual gap in implementing the Domain Layer
Mini Exercise 4
>>>
>>>
>>>
[1]
>>>
>>>
[4]
>>>
4 3
>>>
>>>
7
name = []
name.append(1)
name
name[0] = 4
name
print a, b
c = a + b
c
12
NYSIA - CISDD
Mini Exercise 5
>>> class One(object):
def AMethod1(self):
print "this is a Class One method"
class Two(object):
def AMethod1(self):
print "this is a Class Two method"
c1=One()
c2=Two()
>>> c1.AMethod1()
?
>>> c2.AMethod1()
?
>>> for C in c1,c2:
C.AMethod1()
?
Implementation Polymorphism Overloading Operators and Operations
Operator overloading lets classes intercept normal Python operations
Classes can overload all Python expression operators
Classes can also overload operations: printing, calls, qualification, etc.
Overloading makes class instances act more like built-in types
Overloading is implemented by providing specially named class methods ( of form __method__)
All operator overloading methods are optional
__init__ constructor (object creation operation) tends to appear in most classes
__repr__ (print operation) often appears - see employee example
It is still all about delegating responsibility
Encapsulation Benefits
Hiding
Conceptual Composition Has-a-Relationship
Protocol (Interface) hiding implementation details
Implementation Properties hide accessors attributes
13
NYSIA - CISDD
14
NYSIA - CISDD
Protocol Encapsulation
class Processor(object):
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
def process(self):
while 1:
data = self.reader.readline( )
if not data: break
data = self.converter(data)
self.writer.write(data)
def converter(self, data):
assert 0, converter must be defined
Processor is a protocol container
reader and writer objects passed as parameters what or how is read or written is hidden
from Processor
Converter is delegated through inheritance (assertion raises exception if there is no provider)
How conversion takes place is hidden from Processor
from streams import Processor
class Uppercase(Processor):
def converter(self, data):
return data.upper( )
if __name__ == __main__:
import sys
Uppercase(open(3spam.txt), sys.stdout).process(
15
NYSIA - CISDD
$ cat spamup.txt
SPAM
SPAM
SPAM!
Can also pass in arbitrary objects wrapped up in classes that define the required input and output
method protocols
>>> from converters import Uppercase
>>>
>>> class HTMLize:
...
def write(self, line):
...
print <PRE>%s</PRE> % line[:-1]
...
>>> Uppercase(open(spam.txt), HTMLize( )).process(
<PRE>SPAM</PRE>
<PRE>SPAM</PRE>
<PRE>SPAM!</PRE>
We get uppercase conversion (by inheritance) and HTML formatting (by composition), even though
Processor knows nothing about either
Code reuse all we had to code here was the HTML formatting step; the rest is free
The power of frameworks
Implementation Encapsulation
>>> class Rectangle(object):
def __init__(self):
self.width=0
self.height=0
self.area=0
def setSize(self,size):
self.width, self.height = size
def getSize(self):
self.area = self.width * self.height
return self.width, self.height, self.area
size = property(getSize, setSize)
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5, 50)
>>> r.size = 150, 100
>>> r.width
150
>>> r.size
(150, 100, 15000)
Hides implementation details of Rectangles accessor methods
Size looks like a normal attribute
Can change implementation without effecting using code
16
NYSIA - CISDD
17
NYSIA - CISDD
18
NYSIA - CISDD
Use Cases
A technique for capturing the functional requirements of a system
Describing the typical interactions between the users of a system and the system itself
Provide a story or narrative of how a system is used
Near unanimous consent that they should be text based
UML provides diagram but does not mandate
Sample Use Case Text
19
NYSIA - CISDD
20
NYSIA - CISDD
Class Diagrams
Most widely UML diagrams
Subject to the greatest range of modeling concepts.
Describes the types of objects in the system and the various kinds of static relationships that
exist among them
Show the properties and operations of a class and the constraints that apply to the way objects
are connected
21
NYSIA - CISDD
22
NYSIA - CISDD
Sequence Diagrams
Interaction diagrams describe how groups of objects collaborate in some behavior
Sequence diagram is most typical form
Goes hand in hand with Class diagrams
Captures the behavior of a single scenario
Shows a number of example objects and the messages that are passed between these objects
within the use case
Sample Sequence Diagram
23
NYSIA - CISDD
Communication Diagrams
A kind of interaction diagram (alternative to Sequence diagrams)
Emphasize the data links between the various participants in the interaction
Allows free placement of participants, allows you to draw links to show how the participants
connect, and use numbering to show the sequence of message
Collaboration diagrams in UML 1.x
Sample Communication Diagram
24
NYSIA - CISDD
Package Diagrams
A package is a grouping construct that allows you to take any construct in the UML and group
its elements together into higher-level units
Most common use to group classes
In a UML model, each class is a member of a single package.
Packages can also be members of other packages
Correspond to programming language constructs such as Packages in Python
Each package represents a namespace
Every class must have a unique name within its owning package
25
NYSIA - CISDD
26
NYSIA - CISDD
Activity Diagrams
A technique to describe procedural logic, business process, and work flow
Similar to flowcharts,
Support parallel behavior
27
NYSIA - CISDD
28
NYSIA - CISDD
State Diagrams
Describe the behavior of reactive systems
System enters and exits states based on events and actions
In pure software systems mostly for GUI or asynchronous networking
Useful for embedded systems
Sample State Diagram
29
NYSIA - CISDD
30
NYSIA - CISDD
Simple Example
Dice Game: player rolls two die. If the total is seven, they win; otherwise, they lose
Requirements Use Case:
Play a Dice Game: A player picks up and rolls the dice. If the dice face value total
seven, they win; otherwise, they lose
Domain Model visualization of concepts in the real-world domain through a set of diagrams
Conceptual Class Diagram
31
NYSIA - CISDD
32
NYSIA - CISDD
33
NYSIA - CISDD
34
NYSIA - CISDD
35
NYSIA - CISDD
Guidelines
Root Goal focus on real goal not mechanism to achieve them log in vs identification and
authentication
Essential Style Writing keep the UI out; focus on intent
Focus on user intentions and system responsibilities
1. Administrator identifies self
2. System authenticates identity
Not concrete actions
1. Administrator enters user id and password in dialog box(see Figure 2)
2. System authenticates Administrator
3. System display the edit users window (see Figure 3)
Write tersely
Black-Box Use Cases focus on responsibilities not internal workings
Take Actor and Actor-Goal perspective do the right thing
How to find Use Cases
1. Choose the SUD boundary
2. Identify the primary actors
3. Identify the goals for each primary actor
4. Define use cases that satisfy user goals
Useful Use Cases
Boss Test (User Goal) What have you been doing all day?
Logging In Bad
Negotiating a Supplier Contract Good
Size Test (Sub-function) not too small
Enter an Item ID Bad
Authenticate User Good
36
NYSIA - CISDD
Comment
Verb-Noun structure
System Under Design
User Goal or Sub-function
Calls on the SUD to deliver its services
Who cares about this use case and what do they want?
What must be true on start worth telling readers?
What must be true on successful completion worth telling readers?
A typical, unconditional happy path scenario of success
Alternative scenarios of success or failure
Related non-functional requirements
Varying I/O methods and data formats
Influences investigation, testing and timing of implementation
Such as Open Issues
Level
User-Goal Level to fulfill the goals of the primary Actor
Sub-function Level sub-steps required to support a User Goal (e.g. Pay by Credit)
Sub-function may be shared by several regular use cases
Stake-holders What Should Be in Use Case?
SUD is contract between stake-holders
Use Case gives behavioral part of contract
Captures all and only behaviors relating to stake-holder interests
Preconditions
Not tested in use case
Assumed to be true
Implies successful completion of a scenario from another use case
Main Success Scenario
Leave conditional and branching to extensions
Typical success path that satisfies the interests of the stake-holders
Capitalize Actors names
Number each step
Put repeat statement after steps to be repeated
37
NYSIA - CISDD
38
NYSIA - CISDD
39
NYSIA - CISDD