v2-02-ooadcoursebookclass2
DESCRIPTION
sffdfTRANSCRIPT
-
Object-Oriented Analysis and Design Course Book
T++ Technical Skills Training Program
CUNY Institute for Software Design & Development (CISDD)
New York Software Industry Association (NYSIA)
Aron Trauring
Class 2 April 12th, 2005
1
-
T++ OOA/D Course Course Book Day 2
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: [email protected]
Personal Website: http://aronst.org/
Zoteca Corporate Website: http://www.zoteca.com/
FOSS Resources: http://www.fourm.info/
Aron Trauring - Zoteca 2 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Core OO Concepts from a Programming Perspective Python
Part II
Basics
Assignments
Control Structures/Blocks
Input/Output
Lists
Dictionaries
Assignment:
x = 42
x, y, z = 1, 2, 3
Control Structures/Blocks:
if x > 5:print "The value is ok"
for x in [1,2,3,4,5]:print "This is iteration number ",x
for value in range(10):print value
x = 10while x >= 10:
print "x is not negative"x = x -1
Input/Output:
x = input("Please enter a number: ")print "The square of that number is ", x*x
Lists:
name = ["Aron", "Trauring"]print name[0],name[1]name[0] = "Joe"print name[0],name[1]list = [1,2,3,4,5]print list[0:2]
Dictionaries:
phone = { "Aron" : 9174966240. "Anna" : 9174967890, "Boris" : 9174967777 }
Aron Trauring - Zoteca 3 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
print phone[Aron]phone[Aron] = 9174966776print 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 = 5print snomodify(s)print s
joe = squareprint joe(3)
Class as Namespace Abstraction
Classes can be viewed as a tool for defining names (i.e., attributes) that export data and logic to
clients
Conceptual Abstract Data Type
Protocol (Interface) data and associated operations
Implementation scope
Python Class Namespace
class (superclass,...): # Assign to name.data = value # Shared class datadef method(self,...): # Methods
self.member = value # Per-instance data
Aron Trauring - Zoteca 4 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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 theinstance object being processed
Assignments to attributes of self create or change data in the instance, not the class
Mini Exercise 1
Basic Namespace
>>> class One(object): pass>>> c1 = One()>>> c1.name = Joe>>> c1.country = "US">>> c1.name?>>> c2 = One()>>> c2.name = Moe>>> c2.phone = "2122121111">>> c2.name?>>> c2.country?>>> c1.name?
Class as Record Defining Data
Aron Trauring - Zoteca 5 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
>>> class One(object):def __init__(self,name,country):
self.name=nameself.country=country
>>> c1 = One(Joe,USA)>>> c2 = One(Moe,France)>>> c2.phone = 2121111111>>> c1.name?>>> c1.phone?>>> c1.country?>>> c2.country?>>> c2.phone?
Class Data Scope and Methods
>>> class Spam(object):numinstances = 0def __init__(self):
Spam.numinstances += 1def SpamOrder(self,servings):
while servings:print "Spam"
servings -= 1def printNuminstances():
print "Number of Spammers: ", Spam.numinstancesprintNuminstances = staticmethod(printNuminstances)
>>> s1 = Spam()>>> s1.SpamOrder(5)?>>> s2 = Spam()>>> s3 =Spam()>>> Spam.printNuminstances()?
Scope Issues
>>> class One(object):OneGlob = 50def __init__(self,name,country):
self.name = nameself.country = country.
>>> s1 = One(Joe,"USA")>>> s2 = One("Moe","France")>>> s1.OneGlob?>>> s2.OneGlob?s2.OneGlob=45
Aron Trauring - Zoteca 6 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
>>> 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 ex-
tend 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 classesabove it
Inheritance objects linked into a class tree are the union of all the attributes defined inall 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 climbthis tree at runtime searching for attributes, every time we say object.attribute
Multiple inheritance left to right search
Aron Trauring - Zoteca 7 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Mini Exercise 2
I1.x and I2.x both find x in ?
I1.y and I2.y both find y in ?
I1.z and I2.z both find z in ?
I1.w and I2.w both find w in ?
I2.name finds name in ?
Conceptual Is-A Relationship
class Employee(object):def __init__(self, name, salary=0):
self.name = nameself.salary = salary
def giveRaise(self, percent):self.salary = self.salary + (self.salary * percent)
def work(self):print self.name, "does stuff"
def resign(self):self.myresign()
def __repr__(self):return "" % (self.name, self.salary)
class Chef(Employee):def __init__(self, name):
Employee.__init__(self, name, 50000)def work(self):
print self.name, "makes food"
class Server(Employee):def __init__(self, name, counter=1):
Employee.__init__(self, name, 40000)self.counter = counter
def work(self):print self.name, "interfaces with customer at counter", self.counter
Aron Trauring - Zoteca 8 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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) # Make a robot named bob.print bob # Runs inherited __repr__bob.work( ) # Run type-specific action.bob.giveRaise(0.20) # Give bob a 20% raise.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
bob makes pizza
Work:Employee does stuffChef makes foodServer interfaces with customer at counter 1PizzaRobot 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 9 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Polymorphism Benefit of Objects
Many forms
Conceptual Delegation of responsibility down the tree each Employee sub-type defineshis/her own work
Protocol (Interface) many forms of methods for same operation (depends on instance)
Implementation overloading operators or operations
Python is Dynamically and Strongly Typed
Separation between Object (Type) and Variable (Name)
Objects have fixed types
Variables (names) are merely references (pointers) to objects (mathematical model of a variable).
Variables (names) have no fixed type they can reference any object
All Python Objects Have
Unique identity (an integer, returned by id(x)) which cant be changed
Type (returned by type(x)) which cant be changed
Some content which may or may not be changeable (mutable)
Some Python Objects Have
Zero or more methods
Zero or more names
Methods that allow you to change the contents of the object (modify it in place, that is)
Methods that allow you to access the contents, not change it
Python Names
Not really properties of the object, and the object itself doesnt know what its called
An object can have any number of names, or no name at all
Names live in namespaces
Assignments change references and modify namespaces, not objects
Aron Trauring - Zoteca 10 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Python Names and Objects
A name (variable) like V is created when it is first assigned a value by your code
The assignment also creates a reference between (binds) the name in the namespace and the
object
Future assignments change the already-created name to have a new reference
All names (variables) must be explicitly assigned before they can be used; use of unassigned
variables results in an exception
When names are made to reference new objects, Python also reclaims the old object, if it is not
reference by any other name (or object). (Garbage Collection)
For efficiency purposes some objects are cached (zero-named objects)
Mini Exercise 3
>>> 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 Examples Category
Number 3.1415, 1234, 999L, 3+4j Immutable
Strings spam, "guidos" Immutable Sequence
Tuples (1,spam, 4, U) Immutable Sequence
Lists [1, [2, three], 4] Mutable Sequence
Dictionaries {food: spam, taste: yum} Mutable Mapping
Files text = open(eggs, r).read( )
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
-
T++ OOA/D Course Course Book Day 2
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
>>> name = []>>> name.append(1)>>> name
[1]>>> name[0] = 4>>> name
[4]>>> print a, b4 3>>> c = a + b>>> c
7
name[] is just a method call
a + b is just a method call
Protocol Polymorphism
Some OOP languages define polymorphism to mean overloading functions based on the type
signatures of their arguments
Python Polymorphism is a more powerful and dynamic concept it is responsibility based not
data hiding based
Based on object interfaces, not types
Because attributes are always resolved at runtime, objects that implement the same protocols
are interchangeable
Clients dont need to know what sort of object is implementing a method they call
Python Polymorphism Implements The Three Levels of Flexibility
1. Conceptual Objects responsible for own behavior
2. Protocol (Interface) Control program can talk to different objects as if they were the same
3. Implementation Control program doesnt need to be aware of the internal behaviors that lead
to desired outcome
Aron Trauring - Zoteca 12 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 13 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Conceptual Encapsulation Composition
from employees import PizzaRobot, Server
class Customer(object):def __init__(self, name):
self.name = namedef order(self, server):
print self.name, "orders from", server, "at counter", server.counterdef pay(self, server):
print self.name, "pays for item to", server, "at counter", server.counter
class Oven(object):def bake(self):
print "oven bakes"
class PizzaShop(object):def __init__(self):
self.server = Server(Pat, 2) # Embed other objects.self.chef = PizzaRobot(Bob) # A robot named bobself.oven = Oven( )self.cashier = Server(Matt, 1)
def order(self, name):customer = Customer(name) # Activate other objects.customer.order(self.server) # Customer orders from server.self.chef.work( )self.oven.bake( )customer.pay(self.cashier)
if __name__ == "__main__":scene = PizzaShop( ) # Make the composite.scene.order(Homer) # Simulate Homers order.print ...scene.order(Shaggy) # Simulate Shaggys order.
Homer orders from at counter 2Bob makes pizzaoven bakesHomer pays for item to at counter 1...
Shaggy orders from at counter 2Bob makes pizzaoven bakesShaggy pays for item to at counter 1
Composition has to do with components: parts of a whole
Composition also reflects the has-a relationships between parts
Pizzashop contains servers, oven, robochef
Pizzashop controls how contained objects react to Customer through delegation
Aron Trauring - Zoteca 14 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Protocol Encapsulation
class Processor(object):def __init__(self, reader, writer):
self.reader = readerself.writer = writer
def process(self):while 1:
data = self.reader.readline( )if not data: breakdata = 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 hiddenfrom 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 sysUppercase(open(3spam.txt), sys.stdout).process( )
Uppercase gets processing logic through inheritance how it is done is hidden
reader and writer methods also hidden from Uppercase
spamSpamSPAM!
$ python converters.pySPAMSPAMSPAM!
To process different sorts of streams, pass in different sorts of reader and writer objects to theclass construction call
>>> import converters>>> prog = converters.Uppercase(open(spam.txt), open(spamup.txt, w))>>> prog.process( )
Aron Trauring - Zoteca 15 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
$ cat spamup.txtSPAMSPAMSPAM!
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 %s % line[:-1]...
>>> Uppercase(open(spam.txt), HTMLize( )).process( )SPAMSPAMSPAM!
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=0self.height=0self.area=0
def setSize(self,size):self.width, self.height = size
def getSize(self):self.area = self.width * self.heightreturn 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.width150>>> r.size(150, 100, 15000)
Hides implementation details of Rectangles accessormethods
Size looks like a normal attribute
Can change implementation without effecting using code
Aron Trauring - Zoteca 16 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Introduction to the Unified Modeling Language
What is the UML
The UML is a family of graphical notations, backed by single meta-model, that help in
describing and designing software systems, particularly software systems built using the
object-oriented (OO) style.
Martin Fowler
Object Management Group standard Version 2.0
Set of diagrams which are formally defined (meta-model)
Targeted at OO A/D
Ways of Using UML
Sketch
Blueprint
Programming Language
UML as Sketch
Help informally communicate some aspects of a system explorative
Selectivity only select important issues
Short sessions: minutes, hours depending on scope
Collaborative focus on communication not completeness or correctness
Forward engineering sketch UML diagrams before you write code
Reverse engineering builds a UML diagram from existing code
UML as Blueprint
Completeness definitive
Forward engineeringWaterfall approach incompatible with agile, iterative methods
Reverse engineering useful as documentation, or graphic window into the code
Round-trip CASE tools
Some code generation
UML as Programming Language
UML compiled into executable code
Early versions of C++ gave C code
iLogix STATEMATE
Model Driven Architecture (MDA) standard approach to UMLPL
An alternative abstraction
Aron Trauring - Zoteca 17 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Modeling Three System Perspectives
1. Conceptual Domain of Study Domain Model Analysis (UML)
2. Protocol(Interface) Domain Layer Design (UML/Python)
3. Implementation Software Layer Programming (Python)
Keep in Mind
As sketchers, meta-model and exact syntax is not crucial
Informal usage might not comply with standards (v1.3 vs v2.0)
Be agile do the least amount of modeling work necessary
True measure of success: Working Code that Meets Customer Needs
Use other modeling tools CRC, Python, other diagram types
UML History
70s Structured Programming Gurus
80s OO Gurus
1980-1995 Graphic Modeling Wars
Three Amigos Booch, Jacobson and Rumbaugh
Rational Systems (now owned by IBM)
Competitors dragged in OMG
Version 1.0 January 1997
Rational is trying to sell you something
UML Diagram Types
Static Structure Diagrams
Dynamic Behavior Diagrams
Model both simultaneously
Different meaning at different levels
Aron Trauring - Zoteca 18 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 19 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Sample Use Case Diagram
Aron Trauring - Zoteca 20 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 21 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Sample Class Diagram
Aron Trauring - Zoteca 22 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 23 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 24 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 25 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Sample Package Diagram
Aron Trauring - Zoteca 26 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Activity Diagrams
A technique to describe procedural logic, business process, and work flow
Similar to flowcharts,
Support parallel behavior
Aron Trauring - Zoteca 27 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Sample Activity Diagram
Aron Trauring - Zoteca 28 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 29 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Object-Oriented Analysis/Design and Use Cases
What Is Analysis and Design?
Analysis emphasizes an investigation of the problem and requirements, rather than a solution
Usually qualified requirements analysis, object analysis
OOA emphasizes finding and describing the objects (concepts) in the problem domain
Design emphasizes a conceptual solution that fulfills the requirements, rather than its imple-
mentation
Usually qualified database design, object design
OOD emphasizes defining software objects and how they collaborate to fulfill the requirements
OOP implementing the design
Why Analysis and Design?
Goal: Do the right thing (analysis), and do the thing right (design)
Success criteria: working code [do the thing right] which meets customer needs [do the thing
right]
Focus of OO Analysis and Design
Object-Oriented Analysis and Design
Anarchistic Model - OO is about Those Who Know, Decide
Desert Island Skill Ability to skillfully assign responsibilities to software components
Doing it right determines flexibility, robustness, maintainability, and re-usability of software
components
How Much Analysis and Design?
All methods and techniques apply to all processes differ by how much not that there are stages
Waterfall/SDLC Finish analysis, then design and only then implement predictive model
Unified Process Iterate, although spend some time doing the right thing up front analysis
- before doing the thing right
Extreme Programming Working code is the way to ensure you will do the right thing mini-
mal up-front A & D
Three Steps of Every Iteration
1. Domain Model the concepts, attributes, and associations that are considered noteworthy
static and behavioral
2. Domain Layer software objects and their collaborations (protocols, interfaces) Static and
Behavioral
3. Software Implementation
Aron Trauring - Zoteca 30 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Domain Layer inspired by the real world domain model
Protocol Class Diagram and Interaction Diagram
Aron Trauring - Zoteca 31 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Software Implementation Inspired by domain layer
UML probably not
import random
class Die(object):def __init__(self):
faceValue = 0def setFaceValue(self):
self.FaceValue = random.randrange(1,6)def getFaceValue(self):
return self.FaceValueFaceValue = property(getFaceValue, setFaceValue)
class DiceGame(object):def __init__(self):
self.die1 = Die()self.die2 = Die()
def Roll(self):return self.die1.FaceValue + self.die2.FaceValue
Class in the Three Perspectives
Conceptual Die a real-world die
Protocol Die software data type
Aron Trauring - Zoteca 32 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Implementation Die Python (Java,C++,C#) Class
Case Study 1 Point of Sale System (POS)
Information System Architectural Layers
User Interface thin layer, little responsibility
Application Logic and Domain Objects heart of the system
Technical Services usually application-independent and reusable across several systems
Aron Trauring - Zoteca 33 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Case Study 1 NextGen Point of Sale (POS) System [Lahrman]
A POS system is a computerized application used (in part) to record sales and handle payments; it
is typically used in a retail store. It includes hardware components such as a computer and bar code
scanner, and software to run the system. It interfaces to various service applications, such as a third-
party tax calculator and inventory control. These systems must be relatively fault-tolerant; that is,
even if remote services are temporarily unavailable (such as the inventory system), they must still be
capable of capturing sales and handling at least cash payments (so that the business is not crippled).
A POS system increasingly must support multiple and varied client-side terminals and interfaces.
These include a thin-client Web browser terminal, a regular personal computer with something like a
Java Swing graphical user interface, touch screen input, wireless PDAs, and so forth.
Furthermore, we are creating a commercial POS system that we will sell to different clients with
disparate needs in terms of business rule processing. Each client will desire a unique set of logic
to execute at certain predictable points in scenarios of using the system, such as when a new sale
is initiated or when a new line item is added. Therefore, we will need a mechanism to provide this
flexibility and customization.
The NextGen case study primarily emphasizes the problem domain objects, allocating responsibilities
to them to fulfill the requirements of the application.
Case Study 2 Monopoly Game [Lahrman]
The idea of the game is to buy and rent or sell properties so profitably that one becomes the wealthiest
player and eventual Monopolist. Starting from "GO" move Tokens around the Board according to
throw of Dice. When a Players Token lands on a space not already owned, he may Buy it from the
Bank: otherwise it is Auctioned off to the Highest Bidder. The object of Owning Property is to Collect
Rents from Opponents stopping there. Rentals are greatly increased by the erection of Houses and
Hotels, so it is wise to build them on some of your Lots. To raise more money Lots may be mortgaged
to the Bank. Community Chest and Chance spaces give the draw of a Card, instructions on which
must be followed. Sometimes players land in Jail! The game is one of shrewd and amusing trading
and excitement.
Official Monopoly Rules http://richard_wilding.tripod.com/monorules.htm
Aron Trauring - Zoteca 34 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
What are Use Cases?
Not specifically OO but first step in every analysis
Use cases are little structured stories about the system
In XP they are short stories called User Stories
In SDLC they are Dickens novels
Describe a set of scenarios, that is interactions, between the user and a system, related to a
specific user goal
Key Terms
Actor something with behavior,: a person (identified by role), computer system, or organization
Scenario specific sequence of actions and interactions between actors and the system under
discussion (SUD)
Use Case collection of related success and failure scenarios that describe actors using a system
to support a goal
Informal Example
Handle Returns
Main Success Scenario: A customer arrives at a checkout with items to return. The
cashier uses the POS system to record each returned item ...
Alternate Scenarios:
If the customer paid by credit, and the reimbursement transaction to their credit account
is rejected, inform the customer and pay them with cash.
If the item identifier is not found in the system, notify the Cashier and suggest manual
entry of the identifier code (perhaps it is corrupted).
If the system detects failure to communicate with the external accounting system, ...
Why Use Cases
Story telling is oldest tool of human communication
Customer can write or be involved in writing use cases
Forms the basis of discussion between customer and design teams
Emphasis on customer goals and perspective do the right thing
How Much Detail?
Brief One paragraph. Early stages of analysis (all you do for XP)
Casual Multiple paragraphs
Fully Dressed architecturally significant and high-value use cases only (in UP)
Only working code matters\
Aron Trauring - Zoteca 35 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
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
Aron Trauring - Zoteca 36 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Use Case Format
Use Case Section Comment
Use Case Name Verb-Noun structure
Scope System Under Design
Level User Goal or Sub-function
Primary Actor Calls on the SUD to deliver its services
Stake-holders and Interests Who cares about this use case and what do they want?
Preconditions What must be true on start worth telling readers?
Success Guarantee (Postconditions) What must be true on successful completion worth telling readers?
Main Success Scenario A typical, unconditional happy path scenario of success
Extensions Alternative scenarios of success or failure
Special Requirements Related non-functional requirements
Technology & Data Variations List Varying I/O methods and data formats
Frequency of Occurrence Influences investigation, testing and timing of implementation
Miscellaneous 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
Aron Trauring - Zoteca 37 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Three Kinds of Steps
1. An interaction between actors (may be SUD) System presents receipt to Customer
2. A validation (usually by system) Cashier verifies...
3. A state change by the system System records sale
Extensions
All the rest of the success and failure scenarios
Numbering keys back to Main branch
Main:
...
3. Cashier enters item identifier
...
Extensions:
...
3a. Invalid Identifier: [Identify Condition]
1. System signals error and rejects entry [Response/Handling]
...
Write the condition as something that can be detected by system or actor
Condition can arise in a range of steps
At end of extension handling merge back with main scenario unless indicated otherwise
Complex extensions may be included in separate use case (indicate branch by underlining name)
Condition that can occur during any step is indicated by *a
*a. At any time, system fails:
Special Requirements
Non-functional requirements Language Internationalization
Quality attribute (performance, reliability, usability) Systemmust respond within 30 seconds
Constraint Touch Screen on LCD: text must be visible from 1 meter
Related to specific use case
May be gathered together later
Technology and Data Variations List
Technical variations on how things are done bar code reader vs. keyboard entry
Variations in data schemes UPC or ISBN data formats
Early constraints try to avoid if possible
Aron Trauring - Zoteca 38 NYSIA - CISDD
-
T++ OOA/D Course Course Book Day 2
Exercise - Use Cases
The class breaks into groups of 4-5 people. Each group will create a use case for Process Sale and Play
Monopoly Game. Allocate more time for the former. One person from each group will present to the
class, and we will alternate between the two problem domains.
Aron Trauring - Zoteca 39 NYSIA - CISDD