1 / 57

Comp5421 Object Oriented Programming

Comp5421 Object Oriented Programming. A Simple Example of Object-Oriented Design Lecture 2 Tianxiang(Tim) Shen Summer 2002 Department of Computer Science Concordia university. Object-Oriented Design.

Download Presentation

Comp5421 Object Oriented Programming

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. Comp5421 Object Oriented Programming A Simple Example of Object-Oriented Design Lecture 2 Tianxiang(Tim) Shen Summer 2002 Department of Computer Science Concordia university Concordia TAV 2002 Comp5421_2

  2. Object-Oriented Design • Understanding the problem and the potential solution is a necessary starting point for a successful design. • Object-oriented design is fundamentally a three-step process: • Identifying the Classes • Characterizing the Classes • Defining the Implementation • Evaluating a Design Concordia TAV 2002 Comp5421_2

  3. Knight Tour Problem Knight tour (KT) is a classic search problem: Consider a k by k board of squares and a chess piece called a knight. A knight in chess makes a move consisting either of two squares in a horizontal direction followed by one in a vertical direction or two squares in a vertical direction followed by one in a horizontal, as seen in Figure 2-1. A move in this sense conveys the knight from one square on the board to another. A "knight's tour" is a sequence of moves such that each square on the board is visited by the knight exactly once and the knight ends up in the square where it started, as in Figure 2-2. That is, the knight must visit each square of the board as part of its tour and must not visit any square (other than its starting one ) more than once. Your task is to write a program inputting k, the size of the board, and outputting a valid tour if there is one or a message if there is not. The tour should be output by showing a view of the board with each square. labeled with the index of that move on a valid tour. An example of possible output is shown in Figure 2-2. Concordia TAV 2002 Comp5421_2

  4. Understanding Problem Figure 2-1 The legal moves of the knight in chess: Concordia TAV 2002 Comp5421_2

  5. Understanding Problem Inputting and outputting: Figure 2-2 Concordia TAV 2002 Comp5421_2

  6. Understanding Problem • Task is to write a program: Input: size of the board, Output: a valid tour with each square labeled with the index of its move, or a message if there is no KT. • Move consisting: 1. two squares in a horizontal direction, one square in vertical direction, or 2. two squares in a vertical direction, one square in horizontal direction. • Valid tour: Knight starts at a square, follows a path without visiting any square twice, and ends up where it started. Concordia TAV 2002 Comp5421_2

  7. Exploring Potential Solution • Knight tour is a classic search problem. Considering all possibilities will not yield a practical solution. Why? Concordia TAV 2002 Comp5421_2

  8. Exploring Potential Solution • Model KT search problem as a general tree: 1.Root corresponds to the start cell. 2. Number of 1st level nodes of tree corresponds to the number of the moves from start cell. 3. Second move from each of these cells leads to further nodes, and so on. 4. Degree of each node corresponds to the number of moves from its corresponding cell, it varies from 2 to 8. • Consider k=8 and 4 alternatives per move (average), the number of possible solutions will be 464. It will take forever! Concordia TAV 2002 Comp5421_2

  9. Exploring Potential Solution (cont.) • Searching Result: 1. Suppose there are N nodes in the path from root to the node that corresponds to one cell. 2. From last node, one starting node may be reached: if N = k2 then KT is found else the path failed for KT. Concordia TAV 2002 Comp5421_2

  10. Exploring Potential Solution (cont.) • Two principal Ways to explore a search tree: 1. Depth first search (DFS): Follow a path until either find a solution, or get stuck. 2. Breadth firstsearch (BFS): Visit all the vertexes at distance 1 from root, then all the vertexes at distance 2 from root, and so on. Concordia TAV 2002 Comp5421_2

  11. Exploring Potential Solution (cont.) • Depth first search: 1. Put visited vertexes into a stack (last-in-first-out) 2. More efficient in space because only vertexes on the path are stored in the stack; • Breath first search: 1. Put visited vertexes into a queue (first-in-first-out); 2. More space than DFS because the queue must contain all vertexes on the current path but usually contain other vertexes as well; • DFS may fail to terminate (if tree contain infinite path), but BFS always succeeds to complete the search. Concordia TAV 2002 Comp5421_2

  12. Exploring Potential Solution (cont.) • Methods of making choices: • systematic: explore the paths in some organized way. For KTs, we could try knight's moves in the following order: up-left, left-up, left-down, and so on, going clockwise. If a move is impossible, because it leads to a previously-visited cell or off the board, we try the next one. • Random: use a random-number generator to explore the path Concordia TAV 2002 Comp5421_2

  13. Exploring Potential Solution (cont.) • Methods of making choices: • Heuristics: are experimental approaches to solving a given problem. They provide a set of guidelines that, while not guaranteed to be the best, is likely to yield a good solution. • Search heuristics such as we use here are guidelines on how best to perform the search. They provide a set of rules specifying what to look at next. The order specified by the rules is not necessarily the fastest or the best, but we hope it is good enough and fast enough for our purposes. • Heuristics are needed for KT because it is difficult or impossible to determine an algorithm to find a tour without doing any searching. This is characteristic of many complex problems. Concordia TAV 2002 Comp5421_2

  14. Exploring Potential Solution (cont.) • Backtracking is a good technique for exploring a search tree without repeating all over again, upon each failure. 1. Start from root and build a path which contains choice points (several extensions). 2. Continue making choices and building the path until success or getting stuck. 3. If get stuck, move back to the most recent choice point and make a different choice. 4. When have tried all choices at a particular choice point, move back further, and so on. 5. If have backed up to the root and no further choice, there is no solution to the problem. Concordia TAV 2002 Comp5421_2

  15. Exploring Potential Solution (cont.) • Which cases have no solution? (observation) k  5, or k is odd number: k = 2, no knight’s move; k = 3, it cannot move to or from the center square; k = 4, 1,2,3,4 four cells form closed paths Concordia TAV 2002 Comp5421_2

  16. Exploring Potential Solution (cont.) • Which cases have no solution? K is odd number, it will not end up at the starting square after odd number of moves. because move must be form green to white, or white to green, and starts and ends on the same cell. It follows that a tour must visit an even number of cells, but the last move must be at the odd number of moves. Concordia TAV 2002 Comp5421_2

  17. Identifying Candidate Classes • Identifying potential class: 1. Using problem statement; (1) Nouns represent objects and potential classes; (2) Verbs represent potential actions (methods of classes); (3) Adjectives represent properties of classes (private, public); 2. Re-state the problem in your own terms; 3. Analyze how a potential solution works and identify the items used in this solution that could quality as classes. Designer looks at scenarios, concrete cases of what the system would do for particular problems, rather than attempting to describe the genera solution. The set of classes involved in the scenario can be determined either by attempting to explain the scenario textually and extracting nouns and verbs from the text, or by listing the basic components of solution. Concordia TAV 2002 Comp5421_2

  18. Candidate Classes Concordia TAV 2002 Comp5421_2

  19. Candidate Classes (cont.) • Categories of Classes: (p23) Physical entities: Board, Knight, and Squares; Virtua1 entities: move sequence, set of legal moves from a square; Placeholder class is abstract interface to system components of the solution, either internal or external; Algorithm class represent internal aspect of the solution that are complex or not well understand, it is used to represent a potential solution; Heuristic class is used to encapsulate whatever heuristics are to be used (For KT, it is used to choose the next move), 2nd algorithm class is used to represent the overall search process, it manages the search by finding next move, detecting success or failure of the search, and backtracking appropriately.. Concordia TAV 2002 Comp5421_2

  20. Candidate Classes (cont.) Concordia TAV 2002 Comp5421_2

  21. Scenario of the potential solution • The program reads in the size of the board, builds the board, finds a valid tour and then prints the resultant tour. We assume each square maintains the set of valid moves from that square as we build the tour. All legal knight moves from that square as are added to this set when the square is initialized. Assume we start and end in the upper left corner There are only two valid moves from this square, and the tours based on these moves are symmetric; we need consider only one of them. We identify the second square on the tour and remove its legal move to the starting corner. (This lets us find a valid tour by simply finding a sequence of moves covering all squares, since there is now only one way of getting to the starting square and hence it must be the last node of such a sequence.) Then we ask that second square to find a sequence of moves containing all unused squares starting at that square. Each square, when asked to find such a sequence, first updates the valid move lists of other squares, then uses some heuristic algorithm to order the list of valid moves so that the most likely to succeed is considered first. Then, for each move in the resultant order, it asks the next square to find the remaining sequence. If a square determines it can not continue a sequence, it restores the valid move lists and returns failure to its caller. If a square determines it has completed the tour, it returns the solution to its caller, which passes it back up to the top level. Concordia TAV 2002 Comp5421_2

  22. Choosing Top-Level Classes • Top-Level classes perform a major role in the solution and interacts with other top-level classes in the significant ways. • Eliminate any candidate class if it is covered by other class. • Number of the top-level classes: 1. Some system has only one top-level class, 2. Large system may have as many as ten top-level classes, 3. Proposed solution with 5-10 component, should fit pretty well into short-term memory and be easier to understand. Concordia TAV 2002 Comp5421_2

  23. Choose Top-Level Classes (cont.) • Top-level classes should be: 1. Independent: their functions should not overlap; 2. Balanced: work done by each class should be about the same; 3. Interrelated: they must interact to solve the problem. • How to choose: 1. Logical subset of potential classes should be grouped and a new class inserted in its place; 2.Too large or too small classes should be either decomposed into subclasses or subsumed by another class. Concordia TAV 2002 Comp5421_2

  24. Choose Top-Level Classes (cont.) • Here are the candidate classes that are not included in the final design: [Direction.] A direction is a (trivial) component of a Move. [Knight.] A Square represents the current position of the imaginary traveling knight. [Move.] A Square contains the set of valid moves. (This does not itself rule out the idea of a class Move. However, the amount of information contained in a move is small and does not warrant an extra class.) [Search.] Searching is performed by the Board class. [Tour.] This is essentially the same as the Solution class that we have included. [User Interface.] The class Main provides user interface services. However, we might decide later that the user interface is sufficiently important to be a separate class. Concordia TAV 2002 Comp5421_2

  25. Top-Level Classes (cont.) Concordia TAV 2002 Comp5421_2

  26. Top-Level Classes (cont.) Concordia TAV 2002 Comp5421_2

  27. Characterizing the Classes • Characterizing Classes: 1. Description of what each class is, 2. Description of what they can do (operation and relationship between them). • Textual design: Describing classes in terms of data, operations, and relationships, in order to help the designer understand them well. Data makes the class concrete Operation helps define what the designer thinks the class can do Relationship helps to show how this class fits in and clarifies the overall solution Concordia TAV 2002 Comp5421_2

  28. Characterizing the Classes • Skeleton declaration that shows important methods and attribute. • Main class represents the overall control process and implements the user interface. process operation reads the board size, sets up the board, does search, and prints the result class Main { public: void process(); private: the_board int board_size; }; Concordia TAV 2002 Comp5421_2

  29. Characterizing Classes (cont.) • Board class contains data member squares, it provides operations to set up the squares and to find the actual tour. • class Board { public: void setup (); void findTour (); private: squares }; Concordia TAV 2002 Comp5421_2

  30. Characterizing Classes (cont.) • Square class contains a square’s position (row and column) and the set of legal moves from that square • It sets up the square by defining the initial set of legal moves, and finds the remainder of a tour starting at this square. • class Square • { public: • void setup (); • void findRestOfTour (); • private: • int row_number; • int column_number; • legal_moves }; Concordia TAV 2002 Comp5421_2

  31. Characterizing Classes (cont.) • Heuristic class contains data, number of moves to consider • It provides method to order a set of moves to improve search time. • class Heuristic • { • public: void orderMoves (); • private: • }; • Solution class contains a sequence of square indexes to hold the resultant tour • It accesses the solution so it can be output • class Solution • { • public: • void showSolution (); • private: • int* tour_index[MAX_MOVES] • }; Concordia TAV 2002 Comp5421_2

  32. Characterizing Classes (cont.) • The textual design lacks some of the information of the diagrammatic design. In particular, the text does not show interactions between classes. • The diagrams do show interaction between classes but they do not show which methods implement these interactions. If we annotated the class declarations to show how methods made use of other classes, the declarations would be more informative than the diagrams. Concordia TAV 2002 Comp5421_2

  33. Characterizing Classes (cont.) • Static Structure Diagram (United Modeling Language): • Result: a high-level view of solution represented in terms of objects and interaction. Concordia TAV 2002 Comp5421_2

  34. Defining Implementation • This is the final stage of OOD. • Designer's task is to ensure that each object is correct and the whole system can be made to work • The result of this phase should be a design that is a detailed enough that a programmer can implement each of the classes independently, put the implementations together, and achieve a working system. • The class definitions done in the previous stage should be taken as provisional. • It is important to find a stable starting point. In KT example, the starting point is the process operation of the class Main. Concordia TAV 2002 Comp5421_2

  35. Defining Implementation • Using Pseudocode to define implementation: 1. Pseudocode is typically written as natural language structured as programming language, it is not a source code, However, it can reflect the target programming language, 2. All information about class interaction must be represented precisely and completely, however it does not need to be told precisely how to implement a class, because the programmers know. Concordia TAV 2002 Comp5421_2

  36. Defining Implementation (cont.) • Main Class: represent main flow of control. 1. It is responsible for handling user interface (input and output). 2. Set up all the other classes as needed to find the tour 4. Print the tour Concordia TAV 2002 Comp5421_2

  37. Main Class • The method Main::process controls the whole program. (Starting point) • void Main::process(int argc, const char ** argv) • {  Determine the board_size • Create a board • Set up the board by calling Board::setup(board_size) • If (tour exists for board size) • result_tour = Board::findTour() • Else result_tour = no_tour • Output the contents of result_tour • } • It is precise about its interaction with other classes. When an operation from another class is used, the code provides the full name and the arguments for that operation.This gives the designer the proper starting point for defining the implementation of that method. • It is vague when it refers to the internal implementation of the class Main.This vagueness provides the flexibility necessary to refine the class further. This type of information hiding is • essential in the design of larger systems. Concordia TAV 2002 Comp5421_2

  38. Main Class • Refined pseudocode for process method: void Main::process (int argc, const char **argv) { board_size = Main::getBoardSize(argc, argv); the_board = new Board; set up board by calling the_board->Board::setup(board_size); if (tour exists for board size) result_tour = Board::findTour(); else result_tour = no_tour; Main::output(result_tour); } Concordia TAV 2002 Comp5421_2

  39. Main Class • Next step is to choose another method and provide the pseudocode for it. • Where possible, it is generally best to proceed with other methods of the same class first. • To simplify the program, use command line arguments and output the solution in the form of a board • int Main::getBoardSize(int argc, const char ** argv) • { Get board size from argv[1]. • If not present, use 8. • Return board size. } • void Main::outputTour(Solution tour) • { If ! Tour->Solution::isValid() then Output message • Else • For row=0 to board_size -1 • For col = 0 to board_size-1 • I=tour->Solution::findIndex(row,col) • Output I using exactly 4 spaces • Next col • Output end of line • Next row • } Concordia TAV 2002 Comp5421_2

  40. Command-line Argument • main function has two version: int main() int main(int argc, char *argv[]) int main(int argc, char **argv) is equivalent to 2nd • Parameter argc holds the number of the command-line arguments, it is an integer. Parameter argv holds a pointer to these arguments, respectively. Ex. #include <iostream> using namespace std; int main(int argc, char *argv[]) { cout <<"Received " << argc << " argumnets."<< endl; for (int i = 0; i <argc ; i++) // argv[1] or *(argv+1) cout << "atgument " << i << ": " << argv[i] << endl; return 0; } Concordia TAV 2002 Comp5421_2

  41. Command-line Argument (cont.) Concordia TAV 2002 Comp5421_2

  42. Board Class • Next define operations for either Board or Solution, since we have specified methods in both of these classes. • In this case, we should do Board first because all its incoming dependencies have been resolved, while Solution has a dependency from Board. One should try to define the classes in an order in which as much as possible is known about the class before any of its methods must be defined. • Data member: 1. Integer board_size; //size of the board 2. Square * the_squares; //sq[bd_size][bd_size] Concordia TAV 2002 Comp5421_2

  43. Board Class • The operation Board::setup must define the board (using constructor). Its responsibilities include setting up the array of squares and initializing the squares: • void Board::setup(int size) • { • board_size = size • the_squares = new Square[size][size] • For row = 0 to size –1 • For col =0 to size –1 • the_squares->Square::setup(row, col) • Next col • Next row • } Concordia TAV 2002 Comp5421_2

  44. Board Class • Method Board::findTour must: specify the first move construct the resultant tour find the rest of the tour • Solution Board::findTour () { Square start = squares[1][2]; Square sq0 = squares[0][0]; start->Square::markUsed(sq0); sq0->Square::markUsed(start); sol = new Solution; sol->Solution::setup(board_size); start->Square::findRestOfTour(sol); return sol; } • markUsed is used to remove the square (argument) from the set of valid moves of the base square • findRestOfTour is used to fill in the solution and return true if solution exists, false otherwise Concordia TAV 2002 Comp5421_2

  45. Board Class • findSquare method is used to return the valid square for valid row and col, otherwise return nothing(NULL) • Square Board::findSquare(int row,int col) • { •   If (row < 0 || row >= board_size) Return no square • If (col < 0 || col >= board_size) Return no square • Return squares[row][col] • } Concordia TAV 2002 Comp5421_2

  46. Square Class • Each square must keep track of the remaining legal moves from the square. • Data member: • 1. Integer row_number; //row index • 2. Integer col_number; //col index • 3. Integer num_moves; //number of legal moves • 4. Square legal_moves[MAX_MOVES]; //available moves • The initial set is defined by the setup operation • void Square::setup(Board board, int row, int col) • { row__number = row • col_number = col • num_moves = 0 • For (x,y) in (-2,1-),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1) • sq = board->Board::findSquare(row+x, col+y) • if (sq is valid) • legal_moves[num_moves] = sq • num_moves = num_moves +1 • endif • Next (x,y) • } Concordia TAV 2002 Comp5421_2

  47. Square Class • findRestOfTour is used to fill in the solution and return true if solution exists, false otherwise • Boolean Square::findRestOfTour(Solution sol) { sol->Solution::addSquare(row_number, column_number)//add this square to solution if(sol->isValid()) return True //check if done For each Move m from this square //remove moves to this square m->Square::markedUsed(this) Next m h = new Heuristic h->Heuristic::setup(num_moves, legal_moves) //try each move in turn while((sq = h->Heuristic::nextMove() ) != no square) do if (sq->Square::findRestOfTour(sol)) return true For each Move m from this square //restore moves to this square m->Square::unmarkUsed(this) Next m sol->Solution::removeSquare(row_number, column_number) //restore the board and fail return false } Concordia TAV 2002 Comp5421_2

  48. Square Class • markUsed is used to remove the square (argument) from the set of valid moves of the base square void Square::markUsed(Square sq) { remove sq from legal_moves and decrement num_moves } • void Square::unmarkUsed(Square sq) { legal_moves[num_moves] = sq num_moves = num_moves + 1 } Concordia TAV 2002 Comp5421_2

  49. Heuristic Class • Class Heuristic is used to order the set of moves A simple heuristic is to look at the moves from the most to the least restrictive, i.e. select the next move with the minimum count • Data member: 1. Integer num_moves 2. Square valid_squares[8] 3. Integer move_count[8] • Define an interface in which the heuristic object is set up for the given square by passing the num_moves and legal_moves Void Heuristic::setup(int num, Square moves[]) //Using constructor to set up • Improve the simple heuristic by considering squares with no valid moves and unreachable sequences. (See next page) Concordia TAV 2002 Comp5421_2

  50. Heuristic Class • Improving version: • Void Heuristic::setup(int num, Square moves[]) • { num_moves = num • numzero = 0 • numone = 0 • For i = 0 to num – 1 • valid_square[ i ] = moves[ i ] • move_count[ i ] =valid_square[i] ->Square::numMoves() • if (move_count[i] ==1) numone =numone +1 • if (move_count[i] == 0) numzero= numzero+1 • Next i • if (numzero>1||(numzero==1 && num>1)) num_moves = 0 • else if (numone>2) num_moves = 0 • else if (numone>0) //i.e. numone = 1 • Eliminate all the move but the move with move_count = 1 • //move_count[i]=MAX_MOVES+1 • //if single sequence, use only it • } Concordia TAV 2002 Comp5421_2

More Related