Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSE 403 Object-Oriented Design Reading: Object Oriented Design Heuristics Ch. 2-3, by Authur Riel These lecture slides are copyright (C) Marty Stepp,

Similar presentations


Presentation on theme: "1 CSE 403 Object-Oriented Design Reading: Object Oriented Design Heuristics Ch. 2-3, by Authur Riel These lecture slides are copyright (C) Marty Stepp,"— Presentation transcript:

1 1 CSE 403 Object-Oriented Design Reading: Object Oriented Design Heuristics Ch. 2-3, by Authur Riel These lecture slides are copyright (C) Marty Stepp, 2007. They may not be rehosted, sold, or modified without expressed permission from the author. All rights reserved.

2 2 Chapter 2: Classes and Objects

3 3 OO design pyramid Supports hardware/software system mapping (packages) Class definitions, hierarchies, generalizations (modules) External and internal interfaces (module coupling) Data structure & algorithm design for attributes & operations (detailed design) increasing detail

4 4 OO design pyramid, cont'd.

5 5 What constitutes an object? A class is: a module (a chunk of executable code) a type definition (describes data, behavior for a type of objects) An object has: identity(memory address) state(fields) behavior(methods) public interface(user's view)

6 6 Qualities of modular software decomposable can be broken down into pieces composable pieces are useful and can be combined understandable one piece can be examined in isolation has continuity reqs. change affects few modules protected / safe an error affects few other modules

7 7 Interface and implementation public interface: data and behavior of the object that can be seen and executed externally by "client" code private implementation: internal data and methods in the object, used to help implement the public interface, but cannot be directly accessed client: code that uses your class/subsystem Example: radio public interface is the speaker, volume buttons, station dial private implementation is the guts of the radio; the transistors, capacitors, voltage readings, frequencies, etc. that user should not see

8 8 Encapsulation Heuristic 2.1: All data should be hidden within its class. encapsulation: hiding the private state and behavior within a class and its objects What benefit do we receive from encapsulation? Why not just use public fields and methods? encapsulation promotes abstraction: ability to focus on task at hand and not on specific unnecessary details if data is public, it can never be changed (it becomes part of published interface) public data exposes the client to unnecessary details about how the class is implemented example: point class with x, y vs. r, theta (fig 2.3 p14)

9 9 Dependency on clients Heuristic 2.2: Users of a class must be dependent on its public interface, but a class should not be dependent on its users. example: GradeCalculator class with 3 methods: readGradeInput computeGrades showGradeOutput if the 3 methods are not called in exactly this order, GradeCalculator code crashes! Solutions? have computeGrades or showGradeOutput call their preceding methods if that hasn't been done already combine these methods into only one public method that calls all 3 in order

10 10 Classes' protocols/interfaces Heuristic 2.3: Minimize the number of messages in the protocol of a class. example: a LinkedList class with too many methods makes it hard to find a common operation, such as merge with another linked list (in Ch. 2 paper, this was operator + ) Heuristic 2.4: Implement a minimal public interface that all classes understand. example: implement toString for all classes example: implement equals and compareTo as appropriate protocol: another word for "public interface"

11 11 Some methods should be private! Heuristic 2.5: Do not put implementation details such as common-code private functions into the public interface of a class. Heuristic 2.6: Do not clutter the public interface of a class with items that users of that class are not able to use or are not interested in using. example: LinkedList class has add and remove methods that both advance the list to the proper linked node to add/remove, then performs the operation. How should we design this? use a common helper named getNodeAt(int index) that advances the list to the proper node and returns that node make the helper getNodeAt a private method so client code does not see it and cannot call it

12 12 Minimizing public interface Some ways to minimize a class's protocol: Make a method private unless it needs to be public. Only supply getters (not setters) for fields' values if you can get away with it. example: Card object with rank and suit ( get -only) When writing a class that wraps up a data structure, don't replicate that data structure's entire API; only expose the parts you absolutely need. example: Deck class holds a list of cards, but the game only shuffles and draws the top card, so rather than having a getCard(int), add, remove, etc., just have shuffle() and drawTopCard() methods example: If your Game has an inner list or map of Players, supply just an Iterator or a getPlayerByName(String) method Use a Java interface that holds only the needed methods from the class, and then refer to your class by the interface type in client code.

13 13 Cohesion and coupling cohesion: how complete and closely related things are within your class (a good thing) Heuristic 2.8: A class should capture one and only one key abstraction. (bad) example: PokerGame class that holds all the players, holds an array representing the card deck, stores all bets and money, does the logic for each betting round... What is a better way to do it?

14 14 Coupling coupling: how much classes are connected to / depend on each other (can be a bad thing) nil coupling: no connection at all export coupling: one class depends on public interface of another overt coupling: one class uses another's innards legally (C++ friend classes, Java subclasses using protected stuff) covert coupling: using another class's inner details without permission (hard to do this in Java) Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes, that is, a class should only use operations in the public interface of another class or have nothing to do with that class.

15 15 Reducing coupling Some ways to reduce coupling: combine two classes that don't represent a whole abstraction example: Bet and Round make a coupled class an inner class example: list and list iterator example: GUI frame and event listener provide more unified communication points between subsystems, so that one subsystem does not need to communicate with every piece of another subsystem example: providing convenience methods ( newGame, reset,...) in PokerGame class so that GUI does not need to manually refresh the players, bets, etc.

16 16 Related data and behavior Heuristic 2.9: Keep related data and behavior in one place. avoids having to change two places when one change is needed example: Should a poker game's Player class remember whether that player is in the game, what that player's current bet is, etc? Or should the Game class remember who is in the game, the Bet class remember every player's current bets,...? Heuristic 2.10: Spin off nonrelated behavior into another class (i.e., noncommunicating behavior). example: code to do save/load of dictionary for anagram game

17 17 Roles of objects Heuristic 2.11: Be sure the abstractions that you model are classes and not simply the roles objects play. example: To model a family tree, should we make classes for Father, Mother ? example: Should we make a Club, Diamond, Heart, Spade class to represent each suit of cards? example: Should we make a FirstBetter class that represents the player who is currently betting first in our card game?

18 18 Interfaces interfaces should be used when you want: polymorphism: ability to treat different types of objects the same way (can call same method on two objects and get different results, based on their types) no code sharing (each class implements the methods in the interface in its own way) example: Java's collection framework: List --> LinkedList, ArrayList Map --> HashMap, TreeMap Iterator example: Java's Comparable interface

19 19 Inheritance inheritance should be used when you want: code sharing: subclass's object receives all code from superclass's objects; those methods can now be called on it substitutability: client code can use subclass's object in any situation that a superclass object was expected, and expect the same results to occur example: Java Swing JComponent class a superclass that represents any graphical component stores common features like size, location, color, and font JButton, JPanel, etc. extend JComponent to share these features. any JComponent may be substituted for another in a variety of cases, such as being added to a frame on the screen

20 20 Inheritance vs. delegation If we write a Stack class that is really just a variation on a List, should Stack extend List ? We want a class that models a sorted linked list, so that when any element is added to the list, it will be added in-order and the list's contents will always be sorted. Should SortedLinkedList extend LinkedList ? We're writing shape classes. Should Square extend Rectangle ? +add() +remove List Stack +push +pop() +top() Stack add() remov List +push +pop() +top() In all cases, no. We do not want the user to be able to arbitrarily call add or remove on the Stack. The SortedLinkedList cannot substitute for a normal LinkedList (result of an add differs), so it should not extend it. Both should delegate to an inner list data field.

21 21 Positioning common code We are designing our collection framework, and we want the ability to sort a list of any type. The list could be a linked list or an array list. LinkedList and ArrayList both implement the interface List, but they currently have no common superclass. Where should we put the sorting functionality? A new abstract superclass called AbstractList A static sort method in a new class called Collections or CollectionUtilities (This is what Java's collection framework does!)

22 22 Interface, inheritance example We want it so that some objects can be allowed to be exported on the network, and some objects can be allowed to be stored locally. All types of objects would export or store themselves in the same way. An object can be exportable, storable, or both. Some objects also can be cloned, and each type of object clones itself in a different way. Lastly, some objects are output buffers and should implement common output buffer that is always done the same way. What combination of superclasses, interfaces and delegation should be used in this system? use methodless interfaces named Exportable and Storable ; classes that can be used in these ways implement these "tagging" interfaces (JDK 1.5+ supports attributes instead) delegate task of exporting and storing to an Exporter or Storer class whose methods will accept an Exportable or Storable use interface Cloneable that has a method clone() that the class must implement to specify how to clone it use a superclass (abstract?) named OutputBuffer, and extend it when a class wants to be an output buffer

23 23 Chapter 3: Topologies

24 24 Action vs. object-oriented What is the difference between an "action-oriented" and "object-oriented" application? action-oriented: procedural: functional decomposition easy to find data dependencies by looking at function headers not easy to find functional dependencies by looking at pieces of data (see fig 3.3, p31) object-oriented: data decomposition, decentralized functionality data in front of coder's mind, functionality in back

25 25 When action-oriented works When does it work better to use an action-oriented style for application building? when they put the data in the same file with the functions on it; essentially makes a class so why not just make it a class? forces programmer to use good conventions forces coders to stick with good design

26 26 "God class" problem What are "god classes?" What is wrong with having a "god class" in your system? god class: a class that hoards too much of the data or functionality of a system. problem: not modular! Heuristic 3.1: Distribute system intelligence horizontally as uniformly as possible, that is, the top-level classes in a design should share the work uniformly. Heuristic 3.2: Do not create god classes/objects in your system. Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem.

27 27 Forms of god classes behavioral god class: holds too much logic often has a name ending with "System", "Manager" data god class: holds too much information often has a bunch of access / search methods

28 28 Eliminating god classes Heuristic 3.3: Beware of classes that have many accessor methods defined in their public interface. Having many implies that related data and behavior are not being kept in one place. location of "policy" behavior should be in the place where that policy is enforced / enacted lots of accessors are okay on a class with important data that needs to be shown by a GUI

29 29 "Controller" classes What is a "controller" class? Is it good or bad? controller class: a class that only contains behavior (might contain some fields, but they are superfluous) usually grabs state from other classes and acts on it often has an "-er" or "-or" verb phrase as its name, such as DataLoader, PasswordChecker similar to a behavioral god class on a smaller scale design on right below has a controller class (checking of prereqs could be done by course offering)

30 30 Controllers, cont'd. problems with controller classes data (entity) and behavior (control) should be together, not in separate classes controller classes are basically the action-oriented paradigm it becomes difficult to ask a piece of data, "what functionality depends on you?" in the real world, people dislike controllers... microwave, radio, car have data and behavior together VCR / tape has control separate because controller is expensive What about a TV? It has remote control separate; why? physical convenience, price, dependency; you never want one without the other

31 31 Non-communicating behavior Heuristic 3.4: Beware of classes that have too much non-communicating behavior, that is, methods that operate on a proper subset of the data members of a class. God classes often exhibit much non- communicating behavior.

32 32 Model and view model: classes in your system that are related to the internal representation of the state of the system often part of the model is connected to file(s) or database(s) examples (card game): Card, Deck, Player examples (bank system): Account, User, UserList view: classes in your system that display the state of the model to the user generally, this is your GUI (could also be a text UI) should not contain crucial application data Different views can represent the same data in different ways Example: bar chart vs. pie chart examples: PokerPanel, BankApplet

33 33 Model-view-controller model-view-controller (MVC): common design paradigm for graphical systems controller: classes that connect model and view defines how user interface reacts to user input (events) receives messages from view (where events come from) sends messages to model (tells what data to display) sometimes part of view (see left) Model Controller View data for rendering events updates Model View Component Controller

34 34 Advantages of MVC decreases coupling simplifies complex user interface code multiple controllers may be defined based on desired behavior changes to part can affect others without requiring the changed object to know details of others increases cohesion only the view is concerned with pixels and screen-based data improved flexibility new views can be added without changing model change the feel (Controller) without changing the look (view) increases reuse one model can be represented in several ways

35 35 Model-view separation Heuristic 3.5: In applications that consist of an object-oriented model interacting with a user interface, the model should never be dependent on the interface. The interface should be dependent on the model. (bad) example: Making a system with lots of classes that know how to render themselves; the GUI just calls card.draw(), deck.draw(), player.draw(). GUI should render them, not delegate! doesn't this violate Heuristic 2.9: Keep related data and behavior in one place? Shouldn't things know how to draw themselves? The behavior of drawing things is related to the GUI, because it is part of the GUI's appearance. So it belongs in the GUI classes. Having things draw themselves locks them in to one representation.

36 36 Representing the real world Heuristic 3.6: Model the real world whenever possible. Example of room heat: fig 3.7 - 3.9, p37-38 model the room as a way to decide if heat is needed, and to encapsulate sensors

37 37 Proliferation of classes What is the "proliferation of classes" problem? proliferation of classes: When object-oriented design leads us to design a system that has too many classes that are too small in size and scope, making the system hard to use, debug, and maintain Heuristic 3.7: Eliminate irrelevant classes from your design. irrelevant classes often have only get / set methods Heuristic 3.8: Eliminate classes that are outside the system. don't model behavior of a blender just because you sell blenders; don't model a user just because the system is used Heuristic 3.9: Do not turn an operation into a class. Be suspicious of any class whose name is a verb, especially those that have only one piece of meaningful behavior. Ask if that piece of behavior needs to be migrated to some existing or undiscovered class.

38 38 Agent classes What is an "agent class?" Is it good or bad to have them in your system? agent class: a class that acts as a middle-man to help two or more other classes communicate. example: Farmer class to link Cow and Milk classes example: Librarian class to link Book and Shelf classes Heuristic 3.10: Agent classes are often placed in the analysis model of an application. During design time, many agents are found to be irrelevant and should be removed. What defines whether an agent is relevant? A relevant agent must have some other behavior beyond simply being a middle-man; it must have some useful purpose of its own as well.

39 39 Is the controller relevant? In the model-view-controller paradigm, the controller acts largely as an agent. Should it be there? View model representation Model business logic Controller user interaction UpdateEvent User Actions Change View SetState Get State

40 40 In-class exercise In your project groups, define a set of classes and their major attributes and operations, for a calendar management system. Multiple users should be able to use the system to: create appointments (either individual or group meetings) see an overview of their calendars at various levels of granularity (day, week, month) edit or delete existing appointments set reminders to go off for an existing appointment Appt. data should be persistent (save and load). What classes would you use in this system? What model would you use? What data would it contain? What views of the model(s) would you want? After some time to discuss, we'll do a quick discussion of each group's design and critique it.

41 41 Heuristics 2 quick reference Heuristic 2.1: All data should be hidden within its class. Heuristic 2.2: Users of a class must be dependent on its public interface, but a class should not be dependent on its users. Heuristic 2.3: Minimize the number of messages in the protocol of a class. Heuristic 2.4: Implement a minimal public interface that all classes understand. Heuristic 2.5: Do not put implementation details such as common-code private functions into the public interface of a class. Heuristic 2.6: Do not clutter the public interface of a class with items that users of that class are not able to use or are not interested in using. Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes, that is, a class should only use operations in the public interface of another class or have nothing to do with that class. Heuristic 2.8: A class should capture one and only one key abstraction. Heuristic 2.9: Keep related data and behavior in one place. Heuristic 2.10: Spin off nonrelated behavior into another class (i.e., noncommunicating behavior). Heuristic 2.11: Be sure the abstractions that you model are classes and not simply the roles objects play.

42 42 Heuristics 3 quick reference Heuristic 3.1: Distribute system intelligence horizontally as uniformly as possible, that is, the top-level classes in a design should share the work uniformly. Heuristic 3.2: Do not create god classes/objects in your system. Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem. Heuristic 3.3: Beware of classes that have many accessor methods defined in their public interface. Heuristic 3.4: Beware of classes that have too much noncommunicating behavior. Heuristic 3.5: In applications that consist of an object-oriented model interacting with a user interface, the model should never be dependent on the interface. Heuristic 3.6: Model the real world whenever possible. Heuristic 3.7: Eliminate irrelevant classes from your design. Heuristic 3.8: Eliminate classes that are outside the system. Heuristic 3.9: Do not turn an operation into a class. Be suspicious of any class whose name is a verb or is derived from a verb, especially those that have only one piece of meaningful behavior (don't count set, get, print). Heuristic 3.10: Agent classes are often placed in the analysis model of an application. During design time, many agents are found to be irrelevant and should be removed.


Download ppt "1 CSE 403 Object-Oriented Design Reading: Object Oriented Design Heuristics Ch. 2-3, by Authur Riel These lecture slides are copyright (C) Marty Stepp,"

Similar presentations


Ads by Google