1 / 50

More with the Coffee Machine Design Errors, Exceptions, and Streams

More with the Coffee Machine Design Errors, Exceptions, and Streams. The Coffee Machine Problem. Simplified Description: a machine that serves coffee for 35 cents, with or without sugar and/or creamer. That’s all. The Coffee Machine Problem.

jonathanv
Download Presentation

More with the Coffee Machine Design Errors, Exceptions, and Streams

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. More with the Coffee Machine DesignErrors, Exceptions, and Streams

  2. The Coffee Machine Problem Simplified Description: a machine that serves coffee for 35 cents, with or without sugar and/or creamer. That’s all.

  3. The Coffee Machine Problem Design the program that runs the machine using objects. What are the components, what are their responsibilities, and how do they collaborate to deliver this simple service: • Kim puts in a quarter and a dime and then selects a coffee.

  4. A Typical First Coffee Machine Design Cash Box • Knows amount of money put in. • Gives change. • Knows the price of coffee. • Turns the Front Panel on and off. Front Panel • Captures the selection. • Knows what to mix in each. • Tells the Mixer what to mix. Mixer • Instructs the dispensers to dispense some amount of each product. Dispensers • Knows how to dispense a fixed amount. • Knows when it is empty. • (cup, coffee powder, sugar, creamer, water)

  5. An Object Diagram for the Design

  6. A sample interaction diagram

  7. Test our design against other test scenarios: • Kim puts in a quarter and then selects a coffee. • Kim puts two quarters in and then selects a coffee. • Kim puts in a quarter, then pushes the coin return lever. • Kim puts in two quarters, walks away from the machine, and forgets to come back. • Kim buys two coffees, white with sugar. The sugar dispenser runs out of sugar after the first.

  8. Arnold Visits After five machines are installed and have been operating for a while, Arnold comes along and says, "I would like to add chicken soup, at twenty-five cents. Change the machine.“ We add to the machine one more button for chicken soup, and one more container for instant soup powder.

  9. Activity • What’s the problem with our old design for interaction between cashbox and front panel? • How do you change your software design?

  10. One design Cash Box • Knows amount of money put in. • Gives change. • Answers how much money has been put in. Front Panel • Captures the selection. • Knows the price and recipe for each selection. • Asks Cash Box how much money was put in. • Knows what to mix in each. • Tells the Mixer what to mix. Mixer • Same as before. Dispensers • Same as before.

  11. One design

  12. One Solution

  13. Arnold Visits—Again Arnold comes back a while later with a brilliant idea. He has heard that some companies use their company badges to directly debit the cost of coffee purchases from their employees’ paychecks. Arnold’s employees already have badges, so he thinks this should be a simple change. And he hates to be behind the curve. We add to the hardware a badge reader and link to the payroll system. How do you change your design?

  14. One solution Cash Box • Knows amount of money put in. • Gives change. • Accepts cash or charge. • Answers whether a given amount of credit is available. Front Panel • Same as before, but only asks Cash Box if sufficient credit is available. Mixer • Same as before. Dispensers • Same as before.

  15. Object Diagram

  16. A Sample Interaction

  17. Evolving Designs Over Time Change is unpredictable, but we can try to predict change. By considering different scenarios, we are evolving toward a design that is more flexible, more evenly balanced.  Most designers find it easier to grow a design than to create a finished design from scratch.

  18. He’s Ba-a-a-ack... People are starting to buy Starbucks’ lattes instead of Arnold’s coffees. So Arnold wants the machine modified just slightly, so that he can create a "drink of the week". He wants to be able to add new drinks and change prices any time, to match his competition. He wants to be able to add espresso, cappuccino, hot chocolate, latte, choco-latte, steamed milk, lemon-lime Kool-Aid—in short, anything that he can mix together in a cup with water. We add a couple more buttons, a milk steamer and dispenser, and some more powder dispensers to the hardware configuration. How do we change the software design?

  19. Principle of Continuity • The problem is the design violates the Principle of Continuity: • A change that is small in the business sense should be small in the program. There should be a continuity between the problem domain and the solution domain. • OOP seeks to achieve such continuity by modeling the problem domain more closely. • We have been talking about coffees and recipes, but they don't show up anywhere in our designs.

  20. A Candidate Design for the Coffee Machine

  21. Our Final Design for the Coffee Machine The class diagram is a reasonable "model" of the world. • We have product and recipe objects. Before, they were hard-coded as "constants". • Responsibilities are evenly distributed throughout the system. • Component names and component responsibilities match. With responsibilities evenly distributed, we can distribute control. Look at the decentralization in the interaction diagram!

  22. Designs that Accommodate Change The design allows Arnold to change configurations easily. • To add a product, Arnold adds a new product to the product register. • To change a price or recipe, Arnold changes a product in the register. • We now have a dynamic object: the product. The product has behavior and thus is not a static value. It rolls through the system sharing its knowledge. Using an object of this sort localizes the state and behavior of a product into one component. • We minimize communication among the other components by passing one object around that carries what needs to be known! • We have no mixer. An object with no (software) responsibility dies.

  23. Design and Change • "Clients don't know what they want until you don't give it to them." Or until they see what you do give them. And their business needs change, too, because their clients and environment change. Change is unpredictable, but we can try to predict change • By considering different scenarios, we guide the evolution of a design that is more flexible, more evenly balanced among its collaborators. Most designers find it easier to grow a design than to create a finished design from scratch.

  24. Designs that Accommodate Change Discussing the quality of a design is...            discussing the futures that it supports naturally

  25. What is the difference between an error case and an exception? • An error case is a planned event that is • an expected possibility • that can be handled by normal algorithmic behavior by the class that detects the problem. • We can use “normal” routines to “recover”

  26. What is the difference between an error case and an exception? • An exception is something that is • an “unpredictable,” rare event, • that represents a potential failure of the system, • and whose “fix” is normally unmanageable by the class that detects the problem. • It requires the “normal” routines to be given up altogether and emergency planning to take place

  27. Let’s think about this distinction… Which of the following events that might occur in a typical day are exceptions and which would you handle as a “normal” part of the day? • Your alarm clock goes off in the morning • A power failure that causes your alarm clock to stop working • Taking a shower and running out of hot water • Burning your toast • Dropping your books on the way to class • Missing lunch • School is closed because of a health department emergency • Running out of quarters for laundry? Normal Exc Normal Normal Exc Normal Exc Exc

  28. Introduction • Up until now, most of our methods were written to deal with “out of the norm” events. • How? • Error handling mixed with code that implements the logic of the method itself • But we can’t ALWAYS fix the problem, so then what: • Return a value that signals problem • But what if the return value could be a legitimate value? • Could define an instance variable to indicate success or failure

  29. Many languages allow code to define: • Method creates an exception object to describe the erroneous event • Exception handler in the calling method analyzes the exception • Takes appropriate action • Basic concepts • Exception representation and creation • Defining an exception handler • Passing control from program to handler

  30. Exceptions in Java • Exceptions represented as objects derived from the class Throwable • State maintained by Throwable object includes record of the method calls leading to the event • State determines where the problem occurred • Produces an error message that describes the problem • Exception categories: unchecked and checked

  31. Exceptions in Java (continued)

  32. Exceptions in Java (continued) • Unchecked exceptions are instances of the Error and RunTimeException classes • Represent serious system errors that a typical program should not try to handle • Checked exceptions are subclasses of the Exception class • Represent errors a typical program can handle • Java language specification requires a program to handle any checked exceptions

  33. Exceptions in Java (continued) • Handling checked exceptions • Provide handler to catch the exception • Inform the program that exception will be generated but will not be handled • Catch or declare policy • Almost all exceptions are checked exceptions • Exception classes usually defined within the package containing the corresponding class • Exception classes that deal with IO in the java.io package

  34. Exceptions in Java (continued) • By convention each exception class provides two constructors • No-argument constructor • One-parameter constructor • Takes a string and provides an error message • May need to write your own exception classes • When designing exception classes, important to consider how much information to provide

  35. Exceptions in Java (continued)

  36. Generating Exceptions • After an exception detected, program triggers exception-handling code in the program • Throwing an exception – invoking an exception handler • Throw statement raises an exception, triggers exception-handling mechanism • Syntax of the throw statement: throw exceptionObject; • Takes as an argument a reference to an object of the class Throwable

  37. Generating Exceptions (continued)

  38. Generating Exceptions (continued) • When a throw statement executed, normal program execution terminated • Exceptions that are thrown must be handled or the program terminates • First line of the stacktrace gives the name of the exception • Followed by contents of the call stack • Callstack – record of all methods called up to the point where exception thrown

  39. Generating Exceptions (continued) • When an exception is thrown, normal program execution stops • Java run-time system searches for exception handler • Search starts at the bottom of the call stack and works its way to the top • If handler found, handler code is executed, program continues • If handler not found, stack trace printed, terminates the thread where exception occurred

  40. Handling Exceptions • Enclose all statements that might throw an exception within a tryblock • Try statement monitors execution of statements within its block • Does nothing if no exceptions are thrown • If exception thrown, try statement stops executing remaining statements • Examines catchblocks that follow try block • If a match is found, catch block executed

  41. Handling Exceptions (continued)

  42. Handling Exceptions (continued) • Program continues with first executable statement following the try statement • Associating catch blocks with a try block • Catch blocks only specify exceptions that might be thrown by one of the try block statements • Catch blocks must be placed in order from most specific to most general exception type • Finallyblock listed after all catch blocks • Contains code guaranteed to execute regardless of whether an exception occurs

  43. Handling Exceptions (continued) • Finally block typically used for tasks such as closing a file • Try block defines scope like any other block in Java • Try statement and catch block should be placed in the calling method • Can account for exceptions by declaring that a method may throw an exception • List the exception in the method’s throwsclause

  44. Design Guidelines and Examples • Distinguish between special cases and exceptional cases • Special cases usually handled by the program • Exceptional cases handled by exception • Decision based in part on program specifications • Decide on the type of exception • Decide which exception to throw • Avoid forcing the programmer to examine internal state of the exception

  45. Handling Exceptions • Handling exceptions depends on situation and application • Sometimes appropriate to ignore exceptions entirely • Java requires checked exceptions be handled • Different exception may be thrown • Difficult to produce hard-and-fast rules about the best way to handle exception conditions

  46. Handling Exceptions (continued)

  47. Handling Exceptions (continued)

  48. Handling Exceptions (continued) • Design options • Write a specific catch block to handle the error condition appropriately for the application • Declare exception in a throws clause • Let calling program decide what to do with the condition • Ignore exception by writing an empty catch block • Let normal processing continue • Catch exception and handle it by throwing another exception

More Related