Presentation is loading. Please wait.

Presentation is loading. Please wait.

COS 240 Object-Oriented Languages 5.1 Object-Oriented Design Object-oriented thinking begins with object-oriented design.

Similar presentations


Presentation on theme: "COS 240 Object-Oriented Languages 5.1 Object-Oriented Design Object-oriented thinking begins with object-oriented design."— Presentation transcript:

1 COS 240 Object-Oriented Languages 5.1 Object-Oriented Design Object-oriented thinking begins with object-oriented design

2 “Let there be no doubt that Object-Oriented Design (OOD) is fundamentally different from traditional structured design approaches: it requires a different way of thinking about decomposition and it produces software architectures that are largely outside the realm of the structured design culture.” Grady Booch, 1994 SE guru (UML luminary and author) “ Object-Oriented Analysis and Design with Applications”

3 Where to start?

4 As emphasized previously, the most important aspect of O- OP is the creation of a “universe” of largely autonomous (i.e. independent), but still yet interacting objects. But how does one come up with such a system? One answer is a design technique driven by the determination and delegation of responsibilities. The technique described is termed Responsibility- Driven Design (RDD). Other techniques are available – see COS 315 “Software Engineering”

5 Programming in the Small and Programming in the Large The difference between the development of individual projects and more sizable (real-world) software systems is often described as programming in the small versus programming in the large. Programming in the Small One programmer understands everything from top to bottom. Major problem is the development of algorithms.

6 Programming in the Large System is developed by large team of programmers Major problems are management of details and communication between programmers and between their respective software subsystems. Really good design methodologies are required for large, complex real-world problems.

7 Basis for Design Early software development methodologies (those popular before the advent of object-oriented techniques) concentrated on ideas such as characterizing the basic data structures, and/or the overall structure of function calls, often within the creation of a formal specification of the desired application. But structural elements (data structures and functions) of the application can be identified only after a considerable amount of problem analysis. However, a design technique based on behaviour can be applied from the very beginning of a problem analysis.

8 Responsibility-Driven Design (RDD), developed by Wirfs- Brock, is an object-oriented design technique that is driven by an emphasis on behaviour at all levels of development. A low-tech approach to identifying object responsibilities. Software development with RDD: 1.Analyze problem – use scenarios to “capture” behaviour of real-world objects. 2.Record behaviour on CRC cards. 3.Design software objects. 4.Code 5.Test program

9 Responsibility-Driven Design A design technique that has the following properties: - Can deal with an ambiguous and incomplete specification (Description of what functionality is required from the program to be developed). - Naturally flows from analysis to solution. - Easily integrates with various aspects of software development.

10 An Simple Example - the IIKH Imagine you are the chief software engineer in a major computing firm. The president of the firm rushes into your office with a specification for the firm’s next PC-based product. It is drawn on the back of a dinner napkin (as all the best designs are. Not!) Briefly, the Intelligent Interactive Kitchen Helper (IIKH) will replace the box of index cards of recipes that may be used in a kitchen.

11 Abilities of the IIKH Here are some of the things a user can do with the IIKH: Browse a database of recipes Add a new recipe to the database Edit or annotate an existing recipe Plan a meal consisting of several courses Scale a recipe for some number of users Plan a longer period of meals, say a week Generate a grocery list that includes all the items in all the menus for a period

12 Characterization by Behaviour Just as an class is characterized more by behaviour than by representation, the goal in using Responsibility- Driven Design is to first characterize the application by its behaviour – analysis of problem domain. First capture the behaviour of the entire application. Then refine this into behavioural descriptions of the individual parts (We “capture” the functionality of the software). Then map the behavioural descriptions into code.

13 At first sight, from the problem description, we can see the need for - “something” to manage a recipe database - “something” to plan meals However, we need to analyze the problem in more detail to see if we have missed anything – we usually have! E.g. from experience, we can see that the user will need some form of menu screen to choose one of the various options.

14 Working Through Scenarios A major technique we use to uncover the desired behaviour is to “walk through” “application scenarios”.  Pretend we have already a working application and “walk through” the various uses of the system. Establish the “look and feel” of the system. Make sure we have uncovered all the intended uses. Develop descriptive documentation. Create the high-level software design.

15 Example: Simple Browsing Scenario Walkthrough Alice Smith sits down at her computer and starts the IIKH. When the program begins, it displays a graphical image of a recipe box, and identifies itself as the IIKH, product of IIKH Inc. Alice presses the Enter button to begin. In response to the key press, Alice is given a choice of a number of options. She selects to browse the recipe index, looking for a recipe for salmon that she wishes to prepare for dinner the next day. She enters the keyword salmon, and is shown in response a list of various recipes. She remembers seeing an interesting recipe that used the herb dill as a flavouring. She refines the search, entering the words salmon and dill. This narrows the search to two recipes. She selects the first. This brings up a new window in which an attractive picture of the finished dish is displayed, along with the list of ingredients, preparation steps, and expected preparation time. After examining the recipe, Alice decides it is not the recipe she had in mind. She returns to the search result page, and selects the second alternative. Examining this dish, Alice decides this is the one she had in mind. She requests a printing of the recipe, and the output is spooled to her printer. Alice selects “quit” from a program menu, and the application quits.

16 Software Components A software component is simply an abstract design entity with which we can associate responsibilities for different tasks. May eventually be turned into a class, a method, or something else. In general, Any component should have a small well-defined set of responsibilities - called cohesion Any component should interact with other components to the minimal extent possible - called coupling

17 Various types of cohesion and coupling have been identified – see COS 315. Cohesion and coupling are two good measures of the quality of a program. (Later!)

18 CRC Cards Having identified components, we need to document them. Components are most easily described using CRC cards. CRC = Component, Responsibility, Collaborator A CRC card records the name, responsibilities, and collaborators (i.e. interactions) of an component. A CRC card is inexpensive, erasable, physical

19 A CRC card is nothing more than a 3x5 index card, on which the analyst writes—in pencil—the name of a class (at the top of the card), its responsibilities (on one half of the card), and its collaborators (on the other half of the card). One card is created for each class identified as relevant to the scenario. As the team members walk through the scenario, they may assign new responsibilities to an existing class, group certain responsibilities to form a new class, or (most commonly) divide the responsibilities of one class into more fine-grained ones and perhaps distribute these responsibilities to a different class.

20

21 What/Who Cycle – Identifying Components First identify what activity needs to be performed next. Then answer the question who (i.e. which component) performs that action. Any activity to be performed by the program must be assigned as a responsibility to some component. Start with high-level design – general “overview” of how software should function. Then, step-by-step, add more details – Stepwise Refinement

22 Development of the IIKH - The Greeter Component The first component is the Greeter component. When the application is started, the Greeter puts an informative, friendly welcome window (the greeting) on the screen. And offers the user the choice of several different actions - Browse the database of recipes. - Add a new recipe. - Edit or annotate a recipe. - Review a plan for several meals. - Create a plan of meals. Many of the details concerning exactly how this is to be done can be ignored for the moment.

23 Activities are associated with the recipe database and a menu plan – need to create components for these.

24 The Recipe Database Component Ignoring the planning of meals for the moment, next explore the Recipe Database component. Responsibilities: - Must maintain the database of recipes. - Must allow the user to browse the database. - Must permit the user to edit or annotate an existing recipe. - Must permit the user to add a new recipe. Needs to interact with recipe component.

25 Responsibilities of the Recipe component Can make the recipe itself into an “active” entity – the Recipe component. It maintains information, but also performs tasks. Maintains the list of ingredients and transformation algorithm. Must know how to edit these data values. Must know how to interactively display itself on the output device. Must know how to print itself.

26 Can add other actions later (ability to scale itself, produce and integrate ingredients into a grocery list, and so on).

27 The Planner Component Returning to the Greeter, we start a different scenario. e.g. Planning a meal - This leads to the description of the Planner component. Permits the user to select a sequence of dates for planning a meal. Permits the user to edit an existing plan. Associates with a Date component.

28 The Date Component The Date component holds a sequence of meals for an individual date. User can edit specific meals. User can annotate information about dates (“Christmas Dinner”, and so on). Can print out grocery list for entire set of meals.

29 The Meal Component The Meal component holds information about a single meal. Allows user to interact with the recipe database to select individual recipes for meals. User sets number of people to be present at meal, and recipes are automatically scaled. Can produce grocery list for entire meal, by combining grocery lists from individual scaled recipes.

30 Postponing Decisions There are a number of decisions that must eventually be made concerning how best to let the user browse the database. For example, should the user first be presented with a list of categories, such as “Soups”, “Salads”, “Main meals”, and “Desserts”? Alternatively, should the user be able to describe keywords to narrow a search, perhaps by providing a list of ingredients, and then see all the recipes that contain those items (“Almonds”, “Strawberries”, “Cheese”), or a list of previously inserted keywords (“Ivan's favourite salad”)?

31 Should scroll bars be used or should there be simulated thumb holes in a virtual book? The important point is that such decisions do not need to be made now. Since they affect only a single component, and do not a affect the functioning of any other component, all that is necessary to continue the analysis is to assert that by some means the user can select a specific recipe. Obviously, this high-level design decision needs to be refined and all the above questions need answers. Some time!

32 Preparing for Change It has been said that all that is constant in life is the inevitability of uncertainty and change. The same is true of software. No matter how carefully one tries to develop the initial specification and design of a software system, it is almost certain that changes in the user's needs or requirements will, sometime during the life of the system, force changes to be made in the software. Software developers need to anticipate this and plan accordingly. The primary objective is that changes should affect as few components as possible.

33 Even major changes in the appearance or functioning of an application should be possible with alterations to only one or two sections of code. Try to predict the most likely sources of change and isolate the effects of such changes to as few software components as possible. The most likely sources of change are to human- computer interface.

34 Try to isolate and reduce the dependency of software on hardware. For example, the interface for recipe browsing in our application may depend in part on the hardware on which the system is running. Future releases may be ported to different platforms. A good design will anticipate this change. Reducing coupling between software components will reduce the dependence of one upon another, and increase the likelihood that one can be changed with minimal effect on the other.

35 In the design documentation, maintain careful records of the design process and the discussions surrounding all major decisions. It is almost certain that the individuals responsible for maintaining the software and designing future releases will be at least partially different from the team producing the initial release. The design documentation will allow future teams to know the important factors behind a decision and help them avoid spending time discussing issues that have already been resolved.

36 The Six Components Having walked through the various scenarios, eventually we decide everything can be accomplished using only six software components.

37 Characteristics of Components Return to the idea of a software component. There are a number of different aspects to this simple idea: - Behaviour and State - Instances and Classes - Coupling and Cohesion - Service Interface and Implementation

38 Coupling and Cohesion The separation of tasks into the groups of different components should be guided by the concepts of coupling and cohesion. Cohesion is the degree to which the tasks assigned to a component seem to form a meaningful unit. → Any component must have a small well- defined set of responsibilities. E.g. performing tasks that are related through the necessity of accessing a common data value. Well-designed programs maximize cohesion.

39 Coupling is the degree to which the ability to fulfill a certain responsibility depends upon the actions of another component. A component should interact with other components to the minimal extent possible. In particular, coupling is increased when one software component must access data values (the state) held by another component. Such situations should almost always be avoided in favour of moving a task into the list of responsibilities of the component that holds the necessary data. Well-designed programs minimize coupling.

40 Formalize the Interface - the next step The general structure of each component is identified. Components with only one behaviour may be made into methods. Components with more than one behaviour are implemented as classes with behaviour as methods. Names are given to each of the responsibilities - these will eventually be mapped on to method names. For the rest of this section, let us equate component with class.

41 Designing the Representation The task now is to transform the description of the class into a software implementation. Part of this process is designing the data structures that will be used by each class to maintain the state information required to fulfill the assigned responsibilities. It is also at this point that descriptions of behaviour must be transformed into algorithms using “pseudo-code”. These descriptions should then be matched against the expectations of each class listed as a collaborator, to ensure that expectations are fulfilled and necessary data items are available to carry out each task.

42 Pseudo-code – step before actual code Commonly used, easy to learn – mix of everyday language and programming language Three types of control structure, derived from structured programming: - Sequences of instructions - Selection of alternative instructions (or groups of instructions) - Iteration (repetition) of instructions (or groups of instructions)

43 Sequence in Pseudo-code Each instruction executed in turn, one after another E.g. get client contact name sale cost = item cost * ( 1 - discount rate ) calculate total bonus description = new description

44 Selection in Pseudo-code One or other alternative course is followed, depending on result of a test: if client contact is ’Acme’ set discount rate to 5% else set discount rate to 2% end if

45 Iteration in Pseudo-code Instruction or block of instructions is repeated –Can be a set number of repeats –Or until some test is satisfied, for example: do while there are more staff in the list calculate staff bonus store bonus amount end do

46 Implementing Components Once the design of each software class is laid out, the next step is to implement each class's desired behaviour. If the previous steps were correctly addressed, each responsibility or behaviour will be characterized by a short description (i.e. pseudo-code). The task at this step is to implement the desired activities in a computer language. If they were not determined earlier, then decisions can now be made on issues that are entirely self-contained within a single component. E.g. how best to let the user browse the database of recipes.

47 Next Step – Implement and Test Components Classic techniques, such as stepwise refinement, are used to implement each of the classes. - More and more detail is progressively added to the design and implementation of the class. Classes should be tested in isolation (so-called unit testing), making use of so-called dummy objects or mock objects (Simple dummy objects with no behaviour or with very limited behaviour) for methods external to the class under test.

48 Class A Class B Class C Example Class B is “unit” under test. Class A calls Class B; Class B calls Class C. But want to test Class B in “isolation”. Class A and Class C may not have been tested yet. But obviously, there are dependencies between Class A and Class B, and between Class B and Class C. So, replace the real Class A and Class C with “mock” objects.

49 Class A Class B Class C A mock object contains no logic other than provide the interface that the class under test requires. Class A mock object would only contain dummy calls that test out the service interface of Class B. Class C mock object would only provide a dummy service interface for Class B, and retrun dummy results if necessary.

50 In the example, it would be reasonable to start testing with the Greeter class. - To test the Greeter in isolation, mock objects are written for the Recipe Database manager and the daily Meal Plan manager. - These mock objects need not do any more than print an informative message and return. - With these, can test various aspects of the Greeter component (for example, that button presses elicit the correct response). Testing of an individual classes in this way is often referred to as unit testing.

51 Next Step - Integration Testing Classes are then progressively integrated to form a complete system. Starting from a simple base, classes are one-by-one added to the system and re-tested, again using mock objects for the as yet un-integrated parts. For example, the Greeter and the Recipe Database classes may be integrated, maintaining the mock object for the other portion. Further testing can be performed until it appears that the system as a whole is working as desired. (This is sometimes referred to as integration testing.)

52 The application is finally complete when all mock objects have been replaced with the real working classes. During integration, it is not uncommon for an error to be manifested in one class, and yet to be caused by a coding mistake in another class. Thus, testing during integration can involve the discovery of errors, which then results in changes to some of the classes. Following these changes, the affected classes should be once again tested in isolation before an attempt to reintegrate the classes, once more, into the larger system.

53 Maintenance and Evolution Software does not remain fixed after the first working version is released. Errors or bugs can be discovered and must be corrected. Requirements may change. Say as a result of government regulations, or standardization among similar products. Hardware may change. Users expectations may change. Greater functionality, more features. Often as a result of competition from similar products.

54 Better documentation may be required. A good design recognizes the inevitability of change, and plans an accommodation for these activities from the very beginning.

55 Common Design Flaws The following categories present some of the more common design flaws: - Direct modification - classes that make direct modification of data values in other classes are a direct violation of encapsulation. - Such coupling makes for inflexible designs. - Too Much Responsibility - classes with too much responsibility are difficult to understand and to use. - Responsibility should be broken into smaller meaningful classes and distributed.

56 - No Responsibility - classes with no responsibility serve no purpose. - Components with unused responsibility - Usually the result of designing software classes without thinking about how they will be used. - Misleading Names - Names should be meaningful and unambiguously indicate what the responsibilities of the class involve.

57 Documentation Besides CRC cards, it is important that the development of other documentation be performed almost from the beginning. The two most important documents are the user manual and the design documentation of the software system.

58 User Manual The user manual describes the application as seen by the user. Does not depend upon the implementation, so can be developed before the implementation. Can naturally flow from the process of walking through scenarios. Can be given to the clients to make sure the users and the implementers have the same ideas.

59 Quality You should always remember that the primary measure of quality is the degree to which your customers (clients) are satisfied with your product. Since often customers do not know exactly what it is they want, it is important to work with the client early in the development to make sure the system your are developing is the desired product. One very important way to do this is to create the user manual even before the software is written. Cohesion and coupling are the major factors in the design of high-quality software.

60 System Design Documentation Record the decisions made during the process of system design. Record the arguments for and against any major decision, and the factors influencing the final choice. Record CRC cards for the major components. Maintain a log of the design progress. Important to produce this while the ideas are fresh, not in hindsight when many details will have been forgotten. Note the code only records the outcome of decisions, not factors that lead up to decisions being made.

61 Summary Object-oriented design differs from conventional software design in that (with the RDD approach) the driving force is the assignment of responsibilities to different software components. No action will take place without an object to perform the action, and hence every action must be assigned to some member of the object community. Conversely, the behaviour of the members of the community taken together must be sufficient to achieve the desired goal. The emphasis on behaviour is a hallmark of object-oriented programming.

62 Behaviour can be identified in even the most rudimentary descriptions of a system, long before any other aspect can be clearly discerned. By constantly being driven by behaviour, responsibility- driven design moves smoothly from problem description to software architecture (i.e. organization of code) to code development to finished application.

63 Questions?

64 Questions 1. What are the key features of responsibility-driven design? 2. What are some key differences between programming in-the-small and programming in-the-large? 3. Why can a design technique based on behaviour be applied more easily to poorly-defined problems than can, say, a design approach based on data structures? 4. What is a scenario? 5. What are the basic elements of a component? 6. What is a CRC card? What do the letters stand for? 7. What is the what/who cycle? 8. Why should a user manual be developed before coding begins?

65 9. What are the major sources of change that can be expected during the lifetime of most long-lived software applications? 10. What information is conveyed by an interaction diagram? 11. What is integration testing? 12. What is software maintenance?

66 COS 240 Object-Oriented Languages 5.2. Object-Oriented Design Notation “A picture is worth a thousand words”

67 O-O program design is usually documented using a diagrammatic format – “a picture is worth a thousand words”. There is a standard set of diagrams and notations for describing classes and their interactions. - Unified Modelling Language (UML) – de facto standard for documenting O-O program designs The collection of such diagrams is called the design model.

68 Class Diagram: Class Notation Class diagram: rectangle with 3 compartments. Client companyAddress companyEmail companyFax companyName companyTelephone Class name compartment Attributes compartment Operations compartment

69 Class Diagram: Instance Notation Instance diagram FoodCo:Client companyAddress=Evans Farm companyEmail=mail@foodco.com companyFax=01589-008636 companyName=FoodCo companyTelephone=01589-008638 Object name compartment Attribute values Instances do not have operations

70 Class Diagram: Attributes Attributes are Part of the essential description of a class The common structure of what the class can ‘know’ Each object has its own value for each attribute in its class

71 Class Diagram: Links FoodCo:Client Yellow Partridge:Client Soong Motor Co:Client Grace Chia:StaffMember Carlos Moncada:StaffMember A link is a logical connection between two objects

72 Class Diagram: Associations Associations represent The possibility of a logical relationship or connection between objects of one class and objects of another If two objects can be linked, their classes have an association

73 Class Diagram: Associations StaffMember staffName staffNo staffStartDate Client companyAddress companyEmail companyFax companyName companyTelephone liaises with staffContact Association role Association Association name Direction in which name should be read

74 Class Diagram: Multiplicity Associations have multiplicity Multiplicity is the range of permitted cardinalities of an association Represent enterprise (or business) rules For example: –A bank customer may have one or more accounts –Every account is for one, and only one, customer

75 Class Diagram: Multiplicity StaffMember staffName staffNo staffStartDate Client companyAddress companyEmail companyFax companyName companyTelephone 1 0..* liaises with Multiplicities Exactly one staff member liaises with each client A staff member may liaise with zero, one or more clients

76 Class Diagram: Operations Operations are An essential part of the description of a class The common behaviour shared by all objects of the class Services that objects of a class can provide to other objects

77 Class Diagram: Operations Operations describe what instances of a class can do –Set or reveal attribute values –Perform calculations –Send messages to other objects –Create or destroy links Campaign actualCost campaignFinishDate campaignStartDate completionDate datePaid estimatedCost title checkCampaignBudget ( ) getCampaignContribution ( ) recordPayment ( ) setCompleted ( )

78 Aggregation An aggregation is a special case of association denoting a “consists of” hierarchy. The aggregate is the parent class, and the components are the children classes. 1 Exhaust System SilencerTailpipe 0..2 Denoted by a hollow diamond

79 Aggregation – group dissimilar sets of objects airplane fuselage...winglanding gear IS_PART_OF relationship è Ignore differences among the parts and concentrate on the fact that they form the whole

80 Composition A solid diamond denotes composition, a strong form of aggregation where the components cannot exist without the aggregate. 3 TicketMachine Button Denoted by a solid diamond. Assume a ticket machine that has three buttons

81 Composition and Aggregation – Need to Distinguish Example: One or more classes consists of zero or more students. Clearly not composition: –Students could be in several classes –If class is cancelled, students are not destroyed! Class Student 0..*1..*

82 Example: one meal consists of one or more ingredients. This is composition: –Ingredient is in only one meal at a time. –If you drop your dinner on the floor, you probably lose the ingredients too! Meal Ingredient 1..*1 Solid diamond signifies composition

83 Examples Was a test question! Composition Aggregation

84 Generalization Add generalization structures when - Two classes are similar in most details, but differ in some respects. May differ - In behaviour (operations or methods) - In data (attributes) - In associations with other classes

85 Generalization Generalization associations denote inheritance between classes. The children classes inherit the attributes and operations of the parent class. Generalization simplifies the model by eliminating redundancy. Button AcceptButtonCancelButton Denoted by hollow arrowhead

86 Generalization - group similar sets of objects student postgrad...secondaryundergrad IS_A relationship superclass/supertype subclass/subtype

87 Class Diagram Example

88 Question A university offers degrees to students. The university consists of faculties each of which consists of one or more departments. Each degree is administered by a single department. Each student is studying towards a single degree. Each degree requires one to 20 courses. A student enrolls in 1-5 courses (per term.) A course can be either graduate or undergraduate, but not both. Likewise, students are graduates or undergraduates but not both. Draw a class diagrams which represents the generic objects and relationships described above. Make sure to specify multiplicities for all associations shown in your diagrams.

89

90 Revision Class Diagrams A class diagram depicts classes and their interrelationships. Next slide shows the simplest possible class diagram, followed by one that contains more details.

91

92 Class relationships Classes have relationships with other classes - Objects of one class interact with objects from other classes. This relationship/interaction is termed an association. Class relationships: - Association – general - Aggregation - Compositionspecial forms of association - Generalization

93 Associations

94

95 Types of class relationships A B Class B extends class A Class C contains 1 to 4 objects of class D Factory Product creates Other kinds of relations

96 Aggregation Example: “A car consists of a chassis, an engine, wheels, and seats” The open diamond symbol ◊ denotes aggregation (which means the sum of the parts is the whole). The diamond is placed on the whole end of the line, not the parts.

97 Composition Composition is a stronger form of aggregation. Example: Every chess board consists of 64 squares

98 The chess-board relationship is a stronger form of aggregation: It is an instance of composition Composition also models the part–whole relationship but, in addition, Every part may belong to only one whole, and If the whole is deleted, so are the parts Example: A number of different chess boards. Each square can belong to only one board. If a chess board is thrown away, all 64 squares on that board go as well Composition is depicted by a solid diamond ♦

99 Generalization Inheritance is a feature of object orientation. - Inheritance is a special case of generalization. The UML notation for generalization is an open triangle. Sometimes the open triangle is labeled with a discriminator.

100 Every instance of Investment Class or its subclasses has an attribute investmentType (the discriminator). This attribute can be used to distinguish between instances of the subclasses

101 More examples

102 Need to know the different types of diagrams and their symbols.

103 Questions?


Download ppt "COS 240 Object-Oriented Languages 5.1 Object-Oriented Design Object-oriented thinking begins with object-oriented design."

Similar presentations


Ads by Google