全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:1451
推到 Plurk!
推到 Facebook!

Object-Oriented Design - A recipe for success

 
conundrum
尊榮會員


發表:893
回覆:1272
積分:643
註冊:2004-01-06

發送簡訊給我
#1 引用回覆 回覆 發表時間:2004-02-15 04:23:25 IP:61.64.xxx.xxx 未訂閱
Object-Oriented Design - A recipe for success Object-Oriented Design - A recipe for success Henri Fournier _________________________________________________________________________ Introduction In this session, we will look into the past to appreciate why good design is so important. Old and new techniques will then be compared to demonstrate why the Object-Oriented (OO) approach is better than the Function-Oriented approach. Finally, we will go through a step-by-step process designing an Automated Teller Machine (ATM). Features and techniques from several different OO methodologies will be used to achieve our goal. Here are the key concepts we will be exploring: • Use Case - What is it? Why do I need it? • Object Modeling Technique (OMT) - What is a dynamic model? How does it help? • Class, Responsibility, Collaboration (CRC) - How do I find classes? Then what? All the current OO methodologies have strengths and weaknesses. We will use the strengths of one to make up for the weaknesses of another. The end result will be a compound Object-Oriented Design (OOD) methodology, which will make system implementation almost trivial. Then it will be clear that the investment in OOD will pay for itself many times over. The scope of this presentation will be limited to OOD. The material covered here will be applicable to system design whether you plan to use CA-Visual Objects, CA-Clipper (with Class(y), High Class, etc.) or any other OO language. The Appetizer Time to change Before we begin, I would like to take you back in time a bit, three hundred and seventy years to be exact. The year is 1625 and King Gustav of Sweden has just commissioned the building of the Vasa, the grandest flagship ever [Love-93]. Hendrick Hybertszoon, a master shipwright from Holland, met with the King to discuss the requirements. Hybertszoon built a scale model of the ship, and the King approved the design. There were no written specs. Hybertszoon was told only that the ship was to be approximately 108 feet in length. The King later extended this to 120 feet. After learning of the Danish King's new flagship, King Gustav decided that the Vasa would also have a third gun deck and that it would be ready to sail several months ahead of schedule. The keel was lengthened and the hull was replanked, but there was no room for the extra 130 tons of rock that would have to be added to the planned 120 tons of ballast. The ballast problem was ignored since nobody could come up with a solution that would allow the project to meet the new deadline. Testing the seaworthiness of the craft consisted of having thirty sailors run from one side of the ship to the other repeatedly. To prevent any further delays, the ship was approved even though it nearly tipped on the third iteration of the test. One day in August 1628, the Vasa set sail on her maiden voyage. At about one mile from the harbor, the Vasa's sails caught a modest gust of wind. The ship rolled over and sank. Forty-six years later, King Karl XI commissioned the building of the Kronan (a larger version of the original Vasa design). After four years of service, the ship turned too tightly while engaged in battle, flooded the third gun deck and sank. Eight hundred sailors were lost. The lessons drawn from the Vasa and the Kronan's tragic end: • specifications were not written or formalized, leading to an ad-hoc approach to the design • the design was grossly inadequate, a "fly by the seat of your pants" approach • implications of the change requests were not explained to the customer • test results were ignored in order to meet the deadline • time was wasted on trivial ornate details rather than the soundness of the ship • some design techniques may have worked in the past, they might not work today • the designer did not say NO when the customer asked for something stupid Design, who needs it? Today, as in the past, many programmers and independent developers are used to developing small to medium sized systems for their clients without any formal design stage. More often than not, the development cycle goes from a few sketches on a napkin to writing code using your favorite editor. The design is written and modified in the programmer's head as the coding progresses. I am sure some of you have done this; I know I have. So, if we have been successful in the past, why all the hoopla about design now? Most developers are moving to Windows, whether they want to or not. This entails moving into a Graphical User Interface (GUI). Although this environment can be much more intuitive and appealing to our clients, it adds a lot of complexity to our programming efforts. Another big change we have to deal with is event driven applications. We no longer control the flow of our applications; the user does. Again, this adds a tremendous amount of complexity to our code. As if that were not enough, throw in the rapid rate of change in technology, our client's ever changing needs, business re-engineering, etc. and we are in big trouble. However, there is hope. There is a way to manage all this complexity and change. The answer is Object-Oriented Technology (OOT). You can also benefit from OOT even if you are not moving to Windows yet. Why Object-Oriented Technology? Most software written to date was written in COBOL, FORTRAN, C and Assembler. Why switch now? Why should we use Object-Oriented Design and Programming? Well, there are many reasons, most of which you must have already heard: faster development, code reuse, more robust applications, easier to maintain, etc. But, the short answer is: because we have to! Our clients are demanding more robust, more flexible, more complicated Windows applications, which behave like all other Windows applications. The only way we can meet their demands and stay profitable is by going Object-Oriented. "Object-Oriented Technology provides inherent organization and discipline in writing software systems. It is a great framework for translation of concepts and ideas to actual implementation. The effort and cost of development and maintenance using OOT more than offsets the effort and cost of learning the technology." - Dana Kammerscard (Artecon, Inc.) OO has been around for a long time; even before we had computers. If biologists had used a function driven approach to species classification, then our world might look quite different. All things that can swim would be categorized as fish. All things that can fly would be birds, and so on. Instead, humans, whales and bats are classified as mammals because of the characteristics (attributes and behaviors) we share as mammals. We are objects of the human class. The human class is a subclass of the mammal class. We have been modeled this way, because it is a more natural view of the world. OOT is a much more design intensive process than traditional approaches. Sam Adam's adage: "Objects make good designers better, and mediocre designers obvious." An OOD translates well into code; an invoice in the design specs is an invoice in the source code. This has an added benefit that the developers and the users can speak the same language. The process of design is not just to "figure out how to solve the problem," but also to progressively and efficiently disclose the solution to others. Something old, something new OK! Time for a real life example. Suppose you had to design a system similar to the Windows File Manager. If a user highlights a file in a directory and selects File - Open, the traditional code might look like this: DO CASE CASE cFileType == FT_TXT OpenText(cFileName) CASE cFileType == FT_DBF OpenDB(cFileName) CASE cFileType == FT_BMP OpenBMP(cFileName) . . . ENDCASE The equivalent OO code would look like this: oFile:open() Which do you prefer? Now imagine a year later you have to add functionality for a new file type called ZIP. With the traditional approach, you would have to write the new functions (NewZip, OpenZip, SaveZip, PrintZip, etc.) and then search for all occurrences of the file type CASE statement and add an option to each one. You would then have to re-test the entire system for unexpected side effects. With the OO approach, you would review the FILE class in your original OOD. You would then create a ZIP subclass with the required methods (New, Open, Save, Print, etc.). That's all. Also, only the new subclass would need to be tested, because none of the existing system has been changed. The Main Course In order to properly design a software system, the designer must have or have access to domain knowledge. That is, an understanding of what he is designing and why he is designing it. To illustrate how OOD is applied, I have chosen like many authors, to design an Automated Teller machine (ATM) for this reason. As most, if not all, of us are familiar with the functionality of ATMs, the need for explicit domain knowledge is satisfied. Designing an Automated Teller Machine (ATM) The Moneybags Bank approaches your company and offers you an armored truck full of money to develop the software for an ATM system. You wipe the dollar signs from your eyes and ask them for their system requirements. They provide you with a short written description: “We require an interactive system which will allow our customers to withdraw, deposit and transfer money as well as query their account balance. Security is paramount, therefore each customer will be issued a plastic card with a magnetic strip. The data on the card will consist of a unique card number and a Personal Identification Number (PIN). A valid card must be inserted into the ATM and the matching PIN must be entered to grant a customer access to the system. A receipt should be printed at the end of all transactions.” Then they casually mention that they want it yesterday since their competition has a head start. Also, the government has canceled their R&D grant so the armored truck is not quite full. System Requirements Our first step along the development path is the system requirements. We use this as our starting point in order to gain a thorough understanding of our client's needs. Our job is to find the purpose, mission and goals of the system to be constructed while uncovering all known constraints, whether they be physical, environmental, financial, etc. The requirements may be written or verbal, but all too often they are incomplete and/or inaccurate. This part of the development process is actually more analysis than design. We are trying to determine what the problem is rather than how to solve it. Picture a couple who have decided to build an addition onto their home because they need the extra space. They are not yet sure of the size or the look or how much money they are willing to spend. Local by-laws might even prevent them from building it. They will not have a clear understanding of what can be constructed until they meet with an architect or contractor. The same can be said of our customers. They usually arrive without: • a clear idea of what they want built, • an understanding of the available construction technology, • sufficient time to accomplish the desired project, or • adequate resources to construct their "vision". The Moneybags Bank's system requirements are not exactly all encompassing. How can we improve the system requirements as provided or write them from scratch? Use Case Figure 1: The ATM Machine To help us with this task, I introduce to you the use case (For a complete understanding of Object-Oriented Software Engineering (OOSE) and the use case driven approach, I recommend the book by Ivar Jacobson [Jacobson-92]). A use case is just what it sounds like: it is a way to use the system. All the steps and interactions to perform a single task between an actor and the system form one use case. An actor can be a user, a remote sensing device, another computer, or any other external influence on our system. Sketches of the user interface may help during the development of use cases. A visual representation, as depicted in Figure 1, may enhance the users’ ability to envision how the system will be used. Developing use cases is a mental exercise. A user might find it helpful to simply close her eyes and picture herself using the system. To illustrate, we have the following Cash Withdrawal use case example from our ATM specifications: Example: Cash Withdrawal use case A Normal Course A greeting message is waiting on the display: • The customer inserts his card into the ATM • The ATM reads the code from the magnetic strip on the card and checks to see if it is valid • The ATM prompts the customer for his PIN Waiting for PIN: • The customer enters his PIN using the numeric keypad • The ATM verifies the PIN • The ATM prompts the customer to select a type of transaction Waiting for transaction type: • The customer selects "cash withdrawal" using the menu keypad • The ATM sends the card number and the PIN to the bank system which returns the customer’s account information • The ATM prompts the customer to select an account Waiting for the customer to decide: • The customer selects an account using the menu keypad • The ATM prompts the customer to enter an amount Waiting for the amount: • The customer keys the amount to be withdrawn using the numeric keypad • The ATM sends a request for the withdrawal of the amount from the specified account to the bank system • The bills are prepared to be dispensed. • The card is ejected from the ATM to the customer • The ATM displays a message "Remove card or press 'OK' to begin another transaction" Waiting for the customer to decide: • The customer removes the card • The bills are dispensed to the customer • A receipt of the transaction is printed Alternative Courses The card is invalid: • If the card is invalid because the magnetic strip on the card is not readable or it is of the wrong type, then the card is ejected with a beep Incorrect PIN: • If the PIN is incorrect, a message will be displayed to the customer, who is given two more chances to enter the correct PIN Not allowed to withdraw: • If the bank system does not accept the withdrawal, a message informing the customer is displayed in 10 seconds and the card is ejected The customer does not remove the card, but presses 'OK': • The bills are dispensed to the customer • The ATM prompts the customer to select a type of transaction Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. The Normal Course describes a use case where everything goes according to plan. However, if something goes wrong, an error occurs or a mistake is made, we must be prepared to deal with the situation. These special cases are listed in the Alternative Courses. As we develop more use cases for depositing, transferring and balance inquiry, we notice many similarities between them. All types of transactions will have to go through the card validation process. So, we abstract the common behavior and create a new use case. Now, the use cases for withdrawal, deposit, transfer and balance inquiry all inherit the card validation use case. The proposed ATM system is much clearer now, but we have ignored one of our actors. The Bank System that we interact with to process transactions is an external influence on our system. We should develop use cases for these interactions. The following use cases describe our entire ATM system: Cash Withdrawal use case A Normal Course Use Card Validation use case Waiting for transaction type: • The customer selects "cash withdrawal" using the menu keypad • Use Bank Info use case • The ATM prompts the customer to select an account Waiting for the customer to decide: • The customer selects an account using the menu keypad • The ATM prompts the customer to enter an amount Waiting for the amount: • The customer keys the amount to be withdrawn using the numeric keypad • Use Bank Withdrawal use case • The bills are prepared to be dispensed. • The card is ejected from the ATM to the customer • The ATM displays a message "Remove card or press 'OK' to begin another transaction" Waiting for the customer to decide: • The customer removes the card • The bills are dispensed to the customer • A receipt of the transaction is printed Alternative Courses Not allowed to withdraw: • If the bank system does not accept the withdrawal, a message informing the customer is displayed in 10 seconds and the card is ejected The customer does not remove the card, but presses 'OK': • The bills are dispensed to the customer • The ATM prompts the customer to select a new type of transaction Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. Cash deposit use case A Normal Course Use Card Validation use case Waiting for transaction type: • The customer selects "cash deposit" using the menu keypad • Use Bank Info use case • The ATM prompts the customer to select an account Waiting for the customer to decide: • The customer selects an account using the menu keypad • The ATM prompts the customer to enter an amount Waiting for the amount: • The customer keys the amount to be deposited using the numeric keypad • The ATM displays a message "Insert deposit envelop into slot" • The ATM opens the deposit slot and pulls in the deposit envelope • Use Bank Deposit use case • The card is ejected from the ATM to the customer • The ATM displays a message "Remove card or press 'OK' to begin another transaction" Waiting for the customer to decide: • The customer removes the card • A receipt of the transaction is printed Alternative Courses Deposit not inserted into the deposit slot: • If the ATM does not receive the deposit envelope, a message informing the customer is displayed in 10 seconds and the card is ejected The customer does not remove the card, but presses 'OK': • The ATM prompts the customer to select a new type of transaction Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. Cash transfer use case A Normal Course Use Card Validation use case Waiting for transaction type: • The customer selects "cash transfer" using the menu keypad • Use Bank Info use case • The ATM prompts the customer to select a source account Waiting for the customer to decide: • The customer selects the source account using the menu keypad • The ATM prompts the customer to select a target account Waiting for the customer to decide: • The customer selects the target account using the menu keypad • The ATM prompts the customer to enter an amount Waiting for the amount: • The customer keys the amount to be transferred using the numeric keypad • Use Bank Transfer use case • The card is ejected from the ATM to the customer • The ATM displays a message "Remove card or press 'OK' to begin another transaction" Waiting for the customer to decide: • The customer removes the card • A receipt of the transaction is printed Alternative Courses Not allowed to withdraw: • If the bank system does not accept the withdrawal from the source account, a message informing the customer is displayed in 10 seconds and the card is ejected The customer does not remove the card, but presses 'OK': • The ATM prompts the customer to select a new type of transaction Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. Balance Inquiry use case A Normal Course Use Card Validation use case Waiting for transaction type: • The customer selects "balance inquiry" using the menu keypad • Use Bank Info use case • The ATM prompts the customer to select an account Waiting for the customer to decide: • The customer selects the an account using the menu keypad • Use Bank Balance Inquiry use case • The balance is displayed to the customer • The card is ejected from the ATM to the customer • The ATM displays a message "Remove card or press 'OK' to begin another transaction" Waiting for the customer to decide: • The customer removes the card • A receipt of the transaction is printed Alternative Courses The customer does not remove the card, but presses 'OK': • The ATM prompts the customer to select a new type of transaction Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. Card Validation use case A Normal Course A greeting message is waiting on the display: • The customer inserts his card into the ATM • The ATM reads the code from the magnetic strip on the card and checks to see if it is valid • The ATM prompts the customer for his PIN Waiting for PIN: • The customer enters his PIN using the numeric keypad • The ATM verifies the PIN • The ATM prompts the customer to select a type of transaction Alternative Courses The card is invalid: • If the card is invalid because the magnetic strip on the card is not readable or it is of the wrong type, then the card is ejected with a beep Incorrect PIN: • If the PIN is incorrect, a message will be displayed to the customer, who is given two more chances to enter the correct PIN Cancel: • The customer can cancel the transaction at any time (by pressing ‘Cancel’) when he is asked for some information. This will result in an ejection of the card and the end of the transaction. Bank Info use case A Normal Course Waiting for request: • The ATM sends the card number and the PIN to the bank system • The customer’s account information is returned Bank Withdrawal use case A Normal Course Waiting for request: • The ATM sends a request for the withdrawal of the amount from the specified account to the bank system • A confirmation is returned Alternative Courses Not allowed to withdraw: • An error code is returned Bank Deposit use case A Normal Course Waiting for request: • The ATM sends a request for the deposit of the amount to the specified account to the bank system • A confirmation is returned Bank Transfer use case A Normal Course Waiting for request: • The ATM sends a request for the transfer of the amount from the specified source account to the specified target account to the bank system • A confirmation is returned Alternative Courses Not allowed to withdraw: • An error code is returned Bank Balance Inquiry use case A Normal Course Waiting for request: Figure 2: Event trace for Withdrawal use case • The ATM sends a request for the balance from the specified account to the bank system • The balance is returned to the ATM Now that we have defined the proposed system through use cases, we can rewrite the original system requirements. However, this step is optional and would be for documentation purposes only. The use cases give a strong platform upon which to base our design. Object Modeling Technique (OMT) OMT consists of three different models: the object model, the dynamic model and the functional model. We will focus our attention on the dynamic model (for a complete understanding of the Object Modeling Technique, I recommend the book by James Rumbaugh [Rumbaugh-91]). Each author has his or her own terminology when referring to OOD. Rumbaugh refers to use cases as scenarios. Rumbaugh states, “A model is an abstraction of something for the purpose of understanding it before building it. Abstraction is a fundamental human capability that permits us to deal with complexity.” Many designers build models for various reasons. Aeronautical engineers and car designers build scale models for wind-tunnel testing. Architects build models of whole cities in order to show off their proposed structures. Does it not make sense that software developers also build models to show their clients before undertaking development projects? The dynamic model represents the flow of control, interactions and sequencing of operations in a system. Our first step in developing a dynamic model is drawing what Rumbaugh refers to as an event trace. An event trace is a visual representation of a use case. It shows the sequencing of events between the key objects. You should draw an event trace for each use case, including alternative courses, to note the sequence of events in the ATM system. Figure 2 illustrates an event trace for a withdrawal transaction. From all the event traces, we can draw an event flow diagram. The diagram in Figure 3 summarizes all the events. The three squares represent our main objects from the event trace. The arrows between them represent the event flow. Next to each of the arrows is a list of events without regard for sequence. Figure 3: Event flow diagram for ATM Figure 4: State diagram for ATM The final step in building the dynamic model is the state diagram. A state is an abstraction of the attribute values of an object, and specifies the response of the object to input events. A state diagram relates events and states, as illustrated in Figure 4. We start with the event trace diagram for the ATM system. A state is drawn as a rounded box with an optional name and event is drawn as an arrow labeled with the event name. This completes the analytical phase. Through use cases and a dynamic model we have gained a clear understanding of what we need to design. Now we begin the design process. Class, Responsibility, Collaboration (CRC) For a complete understanding of the CRC method and the responsibility driven approach, I highly recommend the book by Rebecca Wirfs-Brock [Wirfs-Brock-90]. The text is easy to read and comprehend. If you have not read any OO books, this should be your first. This section contains excerpts and highlights from her text. We can now begin what Wirfs-Brock refers to as the exploratory phase. What is a class? A class is a blueprint. It allows us to describe the generic behavior of a set of objects, and to then create objects that behave in that manner when we need them. Objects that behave in a manner specified by a class are called instances of that class. How do I find classes? Read through the use cases carefully and extract all the noun phrases. You now have your first list of candidate classes. Wirfs-Brock lists the following guidelines for choosing candidate classes: • Model physical objects, such as disks or printers on the network. • Model conceptual entities that form a cohesive abstraction, such as a window on a display, or a file. • If more than one word is used for the same concept, choose the one that is most meaningful in terms of the rest of the system. • Be wary of the use of adjectives. If the use of the adjective signals that the behavior of the object is different, then make a new class. • Be wary of sentences in the passive voice, or those whose subjects are not part of the system. Sentences written in the passive voice have implied subjects, although no noun phrase appears on the page. • Model categories of classes. • Model known interfaces to the outside world, such as the user interface, or interfaces to other programs or the operating system. • Model the values of attributes of objects, but not the attributes themselves. What is an abstract class? An abstract class springs from a set of classes that share a useful attribute. If behavior is shared by several classes, you should design an abstract superclass to capture that shared behavior in one place. Subclasses can inherit the behavior from their abstract superclass. Here is the initial list of noun phrases which have been extracted from the ATM use cases: greeting message available accounts display account customer amount ATM amount to be withdrawn code specified amount magnetic strip specified account card confirmation PIN error code numeric keypad bills type of transaction receipt of the transaction wrong type withdrawal beep 10 seconds message ‘OK’ two more chances new type of transaction correct PIN cash deposit transaction amount to be deposited time deposit slot ‘Cancel’ deposit envelope some information transfer funds end of transaction source account transaction type target account cash withdrawal specified source account menu keypad specified target account request amount to be transferred Bank System balance inquiry customer's account information balance From this initial list, you will find some obvious classes, some obvious nonsense and some noun phrases you are not quite sure about. To reduce this list to a more manageable size, we enter into the elimination phase. Elimination phase Firstly, eliminate all redundant phrases in favor of the more accurate descriptive one (appearing in parentheses): code (PIN) type of transaction (transaction) correct PIN (PIN) transaction type (transaction) customer's account information (account) available accounts (menu) amount to be withdrawn (amount) specified amount (amount) specified account (account) new type of transaction (transaction) amount to be deposited (amount) source account (account) target account (account) specified source account (account) specified target account (account) amount to be transferred (amount) Secondly, eliminate any noun phrase describing things outside the system, which the system has no control over: customer magnetic strip card Bank System bills receipt of the transaction deposit envelope Thirdly, eliminate noun phrases that are attributes of classes rather than classes: amount (attribute of Transaction) balance (attribute of Account) Lastly, eliminate anything that is ambiguous or that adds no value to our design: wrong type time some information end of transaction Some noun phrases may be too specific or misleading, so we rename them: greeting message and message (rename to User Message) beep (rename to Tone) two more chances (rename to Attempts) ‘Cancel’ (rename to Cancel Keypad) cash withdrawal (rename to Withdrawal Transaction) Confirmation and Error Code (rename to Return Code) 10 seconds (rename to Time Out) ‘OK’ (rename to OK Keypad) cash deposit (rename to Deposit Transaction) transfer funds (rename to Funds Transfer) After the elimination phase, we are left with the following list of candidate classes and some obvious superclasses: Account ATM Attempts Deposit Slot Display Keypad Cancel Keypad Menu Keypad Numeric Keypad OK Keypad Menu PIN Request Return Code Time Out Tone User Message Transaction Balance Inquiry Deposit Transaction Funds Transfer Withdrawal Transaction Now that we have classes, it is time to introduce the Class, Responsibility, Collaboration (CRC) card. A CRC card is most often made from a 4 x 6 inch index (recipe) card, although you can use whatever is convenient. Write the class name, superclass (if any) and all subclasses (if any) on the front of the card. Divide the remainder of the card into two columns(see Table 1). On the left side, enter the responsibilities and on the right side enter the collaborators. At the top of the back of the card, enter a brief description of the class (see Table 2). The description might help identify missing responsibilities later and will be useful during class documentation as well. Divide the remainder of the back of the card into two columns. On the left side, enter the attributes and on the right side enter the behaviors. The cards are used because they are
系統時間:2024-07-02 15:36:01
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!