CS 541 Lecture -*- Outline -*- * Object-oriented design: a way to think about organizing programs This is a discussion of strategy, for a discussion of tactics, see the smalltalk (or C++) units under programming recall that the goal is ease of change: esp. enhancements, should be easy also want to promote reuse (but prehaps best not to design for generality unless have examples of different problems that need it) Q: what are the main tools we can use? objects, messages (protocols, polymorphism), inheritance ------------------------------------------ QUESTIONS FOR OO DESIGN 1. How to identify classes of objects? 2. How to partition responsibilities among the classes/objects in a system? 3. How to judge designs? ------------------------------------------ something of current practice 1. take inspiration from domain model, also for standard patterns 2. use information hiding principles to put responsibilities with the data (make data smart, see below) 3. How well they can withstand change, usually based on low coupling and high cohesion. ** Finding objects and classes using domain model for inspiration This assumes we've done requirements analysis (e.g., using use cases)... Adapted from Larman's book "Applying UML and Design Patterns", Ch. 10 ------------------------------------------ FINDING OBJECTS AND CLASSES DRAW INSPIRATION FROM A DOMAIN MODEL Def: a *domain model* is a description of real-world concepts and data They don't contain: - software artifacts - responsibilities (methods) ------------------------------------------ ------------------------------------------ CONCEPTUAL CLASSES INSPIRE SOFTWARE CLASSES Domain Model: |-----------| |---------| | Payment |1 Pays-for 1| Sale | |-----------|-----------------|---------| | amount | | date | |-----------| | time | |---------| Inspires Design Model: |-------------| |-----------| | Payment |1 Pays-for 1| Sale | |-------------|<----------->|-----------| | amount:Money| | date:Date | |-------------| | startTime:| | getBalance()| |-----------| |-------------| | getTotal()| | ... | |-----------| ------------------------------------------ Q: Why do this? - because it eases understanding, maps to existing concepts better "chunked" is less likely to change ------------------------------------------ CONCEPTUAL CLASS CATEGORY LIST (From Larman) Use a conceptual class category list: - physical or tangible objects - specifications, designs, descriptions of things - places - transactions - transaction line items - roles of people - containers of other things - things in a container - other (computer) systems - abstract noun concepts - organizations - events - processes (often not concepts...) - rules and policies - catalogs - records of finance, work, and contracts - financial instruments and services - manuals, documents, books ------------------------------------------ ... - physical or tangible objects Register, Airplane - specifications, designs, descriptions of things ProductSpecification, FlightDescription - places Store, Airport - transactions Sale, Payment, Reservation - transaction line items SalesLineItem - roles of people Cashier, Pilot - containers of other things Bin, Airplane - things in a container Item, Passenger - other (computer) systems CreditPaymentAuthorizationSystem, AirTrafficControl - abstract noun concepts Hunger, Acrophobia - organizations SalesDepartment, AirlinePilotsAssoc - events Sale, Payment, Meeting, Flight, Crash - processes (often not concepts...) SellingAProduct, BookingASeat - rules and policies RefundPolicy, CancellationPolicy - catalogs ProductCatalog, PartsCatalog - records of finance, work, and contracts Receipt, Ledger, EmploymentContract, MaintenanceLog - financial instruments and services LineOfCredit, Stock - manuals, documents, books DailyPriceCheckList, RepairManual ** Overall architecture ------------------------------------------ LAYERED ARCHITECTURE Use 3 layers: User Interface |--------------------| Application Logic |--------------------| Services Never let a lower layers depend on higher ones. ------------------------------------------ Q: Why? The higher ones vary more quickly. ** Advice for partitioning responsibilities *** Use information hiding principles to minimize coupling and cohesion, to hide data ------------------------------------------ ASSIGNMENT OF RESPONSIBILITIES (Larman, Ch. 16) Information Expert: "Assign responsibility to the class ... that has information needed to fulfill the responsibility" Creator: Assign responsibility for creating an object to a class that must interact with it anyway. Protected Variations: For "points of predicted variation or or instability; assign responsibilities to create a stable interface around them." Indirection: To avoid direct coupling between objects, have an intermediate object mediate their interactions. ------------------------------------------ Following design patterns is another good way to proceed. *** design heuristics **** for ADTs ------------------------------------------ BASIC DESIGN HEURISTICS (from Riel's book "OO Design Heuristics") - Reuse existing classes if possible. - All data should be hidden in its class - A class should capture exactly one key abstraction - Keep related data and behavior in one class - Do not create god classes/objects - Distribute system intelligence among the classes and objects. Make methods "smart". ------------------------------------------ ------------------------------------------ 2 KINDS OF "GOD CLASS" Behavioral c1 <-get_x()- [ GOD ] -set_q()-> c4 / \ / \ get_y() set_result() / \ v v c2 c3 Data Structural c1 -get_x()-> [ GOD ] <-set_q()- c4 ^ ^ / \ get_y() set_result() / \ / \ c2 c3 ------------------------------------------ aka the "swiss army knife" or "winebego" class The first often happens when you try to write a procedural program The second often happens when you try to migrate from a legacy system Moral: try to distribute intelligence, but not too much. Other examples: phone networks, "one item restraunt" vs grocery store, application package vs. programming langauge want something that raises the level of the langauge higher, not perfectly general perhaps, but more useful. Q: what higher-level operations could we have on bank accounts, instead of just balance and balance: ? **** for inheritance ------------------------------------------ DESIGN HEURISTICS FOR INHERITANCE (from Riel's book "OO Design Heuristics") - Use inheritance only for behavioral subtypes - Do not NO-OP an inherited method - Factor common data and behavior upwards - Use polymorphism instead of explicit case analysis (type tests are bad) - When given a choice between inheritance and containment, use containment. - If you should inherit, try to inherit from some existing framework class. ------------------------------------------ ** how to evaluate designs (low coupling, high cohesion) ------------------------------------------ MAIN EVALUATION PRICIPLES Want to minimize the effects of change Def: *coupling* is the degree to which Def: *cohesion* is the degree to which ------------------------------------------ ... one module depends on another ... the parts of a module depends each other Q: What values of these indicate that changes will be localized to small areas of code? ==> low coupling, high cohesion Want to minimize coupling and maximize cohesion. There will always be some coupling and some lack of cohesion ** examples *** MVC example ------------------------------------------ MODEL, VIEW, CONTROLLER (MVC) PATTERN (layered architecture) |------------| |------------| | View | | Controller | |------------| |------------| | coordinates| | menu | | morph | | | |------------| |------------| | render() | | keyPress() | | transform()| | click() | | ... | | | |------------| |------------| | * | 1 | | | renders | controls | | | 1 | 1 |-------------------| | Model | |-------------------| | problemData | |-------------------| | compute() | | notify() | |-------------------| ------------------------------------------ In practice, the View and Controller classes are sometimes the same (a UI class). *** Lottery simulation example **** Use cases ------------------------------------------ LOTTERY SIMULATION USE CASES The Lottery: The State Agency opens the lottery and announces the prize, rules, and fee. Many Customers buy tickets. The State Agency closes the lottery. The state agency chooses the winning sequence of numbers. The Customers redeem their winnings. Customer Buys a Ticket: The Customer selects a sequence of numbers (at random). The Customer tells the numbers to the State Agency, and pays a fee. The State Agency which takes the fee and records the chosen numbers, giving the Customer a ticket as a receipt. Customer Redeems Winnings: The Customer is notified of the winning sequence of numbers. The Customer checks its tickets, and shows the winning tickets to the State Agency. The State Agency pays the customer their winnings. Customer Leaves the Simulation: The customer runs out of money. Customer Enters the Simulation: A new customer with a given amount of money enters the simulation. ------------------------------------------ **** Domain model ------------------------------------------ CONCEPTUAL CLASS DIAGRAM |--------------| 1 Buys * |-------------| | Customer |----------| Ticket | |--------------| |-------------| | cash: Money | |seq: Numbers | |--------------| |-------------| | * | | pays | | 1 |--------------------------| | Lottery | |--------------------------| | receipts: Money | | prize: Money | | selected: Bag of Numbers | | open: Boolean | |--------------------------| ------------------------------------------ **** CRC cards ---------------------------------- LottoCustomer | --- | remember how much | willing to lose | play lottery some # | Lottery of times | Lottery | --- | pick winning ticket | WinningTicket | UniformDiscrete tell how much ticket | has won | Ticket | --- | hold 7 distinct | integers | WinningTicket | --- | (as in Ticket) | tell number of matches| Ticket to a Ticket | UniformDiscrete | --- | remember how many to | pick from | give set of distinct | numbers of a size ---------------------------------- **** CRC cards on back (implementation design) data values (representation of state) minimize access to data (need to know basis) ** exercises *** ATM banking machine problem: design program ATM machine to allow withdrawal and deposits. *** A kitchen management system. Track recepies and what food is on hand produce menus & grocery list.