Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Professor of Computer Science Nipissing University.

Similar presentations


Presentation on theme: "1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Professor of Computer Science Nipissing University."— Presentation transcript:

1 1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Professor of Computer Science Nipissing University

2 2 Lecture 2 u Object-Oriented Design, Classes and Methods

3 3 Why Design ? u Object-oriented thinking begins with object-oriented design u It is the easiest way to give the student an appreciation of the problems of programming in the large (realistic modern software development). u Without understanding programming in the large, one cannot understand the importance of OOP

4 4 Activities in Software Development u Problem Analysis u Program Design u Coding u Documenting u Testing u Maintenance

5 5 Remember u Be clear about what you are trying to build. u Successful software development is a long term activity. u The systems that we build tend to be at the limit of the complexity that we and our tools can handle. u There are no cookbook methods that can replace intelligence, experience, and good taste in programming.

6 6 Remember u Experimentation is essential for all non- trivial software development. u Design and programming are iterative activities. u The different phases of a software project cannot be strictly separated. u Programming and design cannot be considered without also considering the management of these activities.

7 7 Strategy u There is only one basic way to deal with complexity: Divide and Conquer. u Systems can be divided into modules(Objects or Classes). u The challenge is to ensure effective communication between different parts of the program without destroying the divisions.

8 8 Objectives u We are concerned with producing software that satisfies the users’ requirements. u The primary means to do so is to produce software with a clean internal structure. u The Tasks of OO Design: u To specify: u The needed classes (or components) u The interface

9 9 The Need for a Clean Internal Structure To simplify: u Testing u Porting u Maintenance u Extension u Re-organization u Understanding

10 10 Characteristics of Successful Software It has an extended life where it might be: u worked on by succession of programmers and designers u ported to new hardware u adapted to unanticipated uses

11 11 Some Issues of Design u Identify Components u Postponing Decisions u Preparing for Changes u Coupling and Cohesion u Two views of a Software System u Formalize the Interface u Naming u Documentation

12 12 Identify Components u A component is simply an abstract entity that can perform tasks or fulfill some responsibilities. u It may eventually be turned into a class, a function, a module, or something else. u A component must have a small, well- defined set of responsibilities. u A component should interact with other components to the minimal extent possible.

13 13 Postponing Decisions u Many decisions can be ignored for the moment u Only need to note that somehow the user can manipulate

14 14 Preparing for Change u Your design team should also keep in mind that change is inevitable. Users requirements change with experience, hardware changes, government regulations change. u Try to predict the most likely sources of change, and isolate the effect. Common changes include interfaces, file formats, communication protocols. u Isolate interfaces to hardware that is likely to change. u Reduce dependency of one software component on another. u Keep accurate record of the reasoning behind every major decision in the design documentation.

15 15 Design for Change u The system must be designed to remain as simple as possible under a sequence of changes. u We must aim for u Flexibility u Extensibility u Portability u OOD can support the above.

16 16 Coupling and Cohesion u The separation of tasks into the domains of different components should be guided by the concepts of coupling and cohesion. u Cohesion is the degree to which the tasks assigned to a component seem to form a meaningful unit. Want to maximize cohesion. u Coupling is the degree to which the ability to fulfill a certain responsibility depends upon the actions of another component. Want to minimize coupling.

17 17 Parnas' Principles u The developer of a software component must provide the intended user with all the information needed to make effective use of the services provided by the component, and should provide no other information. u The implementer of a software component must be provided with all the information necessary to carry out the given responsibilities assigned to the component, and should be provided with no other information.

18 18 Public and Private View u Public view - those features (data or behavior) that other components can see and use u Private view - those features (data or behavior) that are used only within the component

19 19 Formalize the Interface u The general structure of each component is identified. u Components with only one behavior may be made into functions. u Components with many behaviors are probably more easily implemented as classes. u Names are given to each of the responsibilities - these will eventually be mapped on to procedure names. u Information is assigned to each component and accounted for. u Scenarios are replayed in order to ensure all data is available.

20 20 Naming u The selection of names is an important task. u Names should be evocative in the context of the problem. u Names should be short. u Names should be pronounceable (read them out load). u Names should be consistent within the project. u Avoid digits within a name.

21 21 Documentation u The user manual describes the application as seen by the user. u Quality u System Design Documentation

22 22 User Manual u Does not depend upon the implementation, so can be developed before the implementation. u Can naturally flow from the process of walking through scenarios. u Can be carried back to the clients to make sure the users and the implementers have the same ideas.

23 23 Quality u You should always remember that the primary measure of quality is the degree to which your customers (clients) are satisfied with your product. u Since often customers do not know exactly what it is they want, it is important to work with the client early in the design phase 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.

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

25 25 Implement and Test Subsystems u Classic techniques, such as stepwise refinement, are used to implement each of the subsystems. u Subsystems are validated in isolation. u Informal proofs of correctness for the subsystem are developed. u Identify necessary conditions for correct functioning. Try to minimize conditions, and test input values whenever possible. u Software testing is used as a confidence building measure.

26 26 Integration and Testing u Components are slowly integrated into completed system. u Stubs can be used to perform testing all during integration. u Errors discovered during integration to cause reinvestigation of validation techniques performed at the subsystem level.

27 27 Maintenance and Evolution u Software does not remain fixed after the first working version is released. u Errors or bugs can be discovered. Must be corrected. u Requirements may change. Say as a result of government regulations, or standardization among similar products. u Hardware may change. u Users expectations may change. Greater functionality, more features. Often as a result of competition from similar products. u Better documentation may be required. u A good design recognizes the inevitability of change, and plans an accommodation for these activities from the very beginning.

28 28 Common Design Flaws u Direct modification u Components that make direct modification of data values in other components are a direct violation of encapsulation. u Such coupling makes for inflexible designs. u Too Much Responsibility (or services, methods) u Components with too much responsibility are difficult to understand and to use. u Responsibility should be broken into smaller meaningful packages and distributed. u No Responsibility u Components with no responsibility serve no purpose. u Often arise when designers equate physical existence with logical design existence. u Components with unused responsibility u Usually the result of designing software components without thinking about how they will be used. u Misleading Names u Names should be short and unambiguously indicate what the responsibilities of the component involve.

29 29 Classes and Methods u Same Ideas, Different Terms u Encapsulation and Instantiation u Internal and External Views u Behavior and State u Class Definitions u Methods u Variations on Classes

30 30 Same Ideas, Different Terms u All OOP languages have the following concepts, although the terms they use may differ: u classes, object type, factory object u instances, objects u message passing, method lookup, member function invocation, method binding u methods, member function, method function u inheritance, subclassing

31 31 Encapsulation and Instantiation u Encapsulation - The purposeful hiding of information, thereby reducing the amount of details that need to be remembered/communicated among programmers. u A Service View - The ability to characterise an object by the service it provides, without knowing how it performs its task. u Instantiation - The ability to create multiple instances of an abstraction.

32 32 Common Behavior and State u A class can also be viewed as a combination of behavior and state. u Behavior: The actions that an instance can perform in response to a request. Implemented by methods. u State: The data that an object must maintain in order to successfully complete its behavior. Stored in instance variables (also known as data members, or data fields).

33 33 Design Steps of OOD u Find the Concepts/Classes and their most fundamental relationships. u Refine the Classes by specifying the sets of Operations on them u classify these operations: constructors, destructors, etc. u consider minimalism, completeness, and convenience

34 34 Design Steps (cont’d) u Refine the classes by specifying their dependencies on other classes: u Inheritance dependencies u Composition dependencies u Use dependencies u Specify the interfaces for the classes: u separate functions into public and protected operations u specify the exact type of the operations on the classes.

35 35 Finding Classes u Good design must capture and model some aspects of reality. u Look at the application rather than the computer abstractions. u Usually nouns correspond to classes and verbs represent functions. u Discussions with experts in the application domain.

36 36 Behavior and State u All classes can be characterized by two aspects: u The behavior of an object class is the set of actions a component can perform. The complete set of behavior for an object is sometimes called the protocol. u The state of an object represents all the information (data values) held within an object. u Notice that it is common for behavior to change state. For example, the edit behavior of a recipe may change the preparation instructions, which is part of the state.

37 37 Example u When ordering new videotapes from a supplier, the store manager creates a purchase order, fills in the date, the supplier’s name, address, and enters a list of videotapes to be ordered. The purchase order is added to a permanent list of purchases. When one or more video tapes are received from a supplier, a clerk locates the original purchase order and makes a record of each tape that was received. A record of the videotape is then added to the store’s inventory. When all tapes listed on a particular purchase order have been received, the manager sends a payment to the supplier and the purchase order is given a completion date.

38 38 Specifying operations u Consider how an object of the class is constructed, copied, and destroyed. u Define the minimal set of operations required by the concept the class is representing. u Consider which operations could be added for notational convenience and include only a few really important ones. u Consider which operations are to be virtual. u Consider what commonality of naming and functionality can be achieved across all the classes of the component.

39 39 Operations on a Class u Foundation: u Constructors and destructors u Selectors( or Accessors): u Operations that do not modify the state of an object. u Modifiers(or Setters): u Operations that modify the state of an object. u Conversion Operators: u Operations that produce an object of another type based on the value (state) of the object to which they are applied. u Iterators: u Operations that processes data members containing collections of objects.

40 40 Specifying Dependencies u The key dependencies to consider in the context of design are inheritance and use relationships. u Overuse can lead to inefficient and incomprehensible designs.

41 41 Specifying Interfaces u Private functions are not considered at this stage. u The interface should be implementation independent (more than one implementation should be possible). u All operators in a class should support the same level of abstraction.

42 42 Reorganizing the Class Hierarchy u Typically, the initial organization of classes may not be adequate and therefore, we may have to reorganize to improve the design and/or implementation. u The two most common reorganizations of a class hierarchy are u factoring of two classes into a new class u splitting a class into two new ones.

43 43 Experimentation and Analysis u Prototyping is frequently used for experimenting. u Different aspects of a system may be prototyped independently, such as the graphical user interface. u Analysis of a design and/or implementation can be an important source of insight.

44 44 The Definition of Class u Class ::=, where u n is an Identification or a name of the class; u d is the space description (template) for memory; u m is the set of methods (or services, operations) the objects of this class can make; and u x is a unified interface of all the objects of the class.

45 45 Class Definition in C++ class PlayingCard { public: enum Suits {Spade, Diamond, Club, Heart}; Suits suit () { return suitValue; } int rank () { return rankValue; } private: Suits suitValue; int rankValue; };

46 46 Visibility Modifiers u The terms public and private are used to differentiate the internal and external aspects of a class. u public features can be seen and manipulated by anybody -- they are the external (interface or service) view. u private features can be manipulated only within a class. They are the internal (implementation) view. u Typically methods are public and data fields are private, but either can be placed in either category.

47 47 Methods u A name that will be matched to a message to determine when the method should be executed. u A signature, which is the combination of return type and argument types. Methods with the same name can be distinguished by different signatures. u A body, which is the code that will be executed when the method is invoked in response to a message.

48 48 Constructor u class PlayingCard { u // constructor, initialize new playing card u public PlayingCard (Suits is, int ir) u { suit = is; rank = ir; faceUp = true; } u... u } u A constructor is a method that is used to initialize a newly constructed object. In C++, Java, C# and many other languages it has the same name as the class. u More about constructors in the next lecture.

49 49 Accessor (or getter) Methods u An accessor (or getter) is a method that simply returns an internal data value: u class PlayingCard { u... u // operations on a playing card u public int rank () { return rankValue; } u public Suits suit () { return suitValue; } u... u private int rankValue; u }

50 50 Why Use an Accessor? u You can make the data field read-only. u It provides better documentation that the data field is accessible u It makes it easier to later change the access behavior (count number of accesses, whatever).

51 51 Setters (or mutators) u A setter (sometimes called a mutator method) is a method that is used to change the state of an object: u class PlayingCard { u // operations on a playing card u public void setFaceUp (boolean up) { faceUp = up; } u... u // private data values u private boolean faceUp; u }

52 52 Order of Methods u List important topics first. u Constructors are generally very important, list them first. u Put public features before private ones. u Break long lists into groups u List items in alphabetical order to make it easier to search.

53 53 Separation of Definition and Implementation u In C++: u class PlayingCard { u public: u... u Colors color () ; u... u }; u PlayingCard::Colors PlayingCard::color ( ) u { u // return the face color of a playing card u if ((suit == Diamond) || (suit == Heart)) u return Red; u return Black; u } u Notice need for fully-qualified names.

54 54 Considerations in Method Definitions u In C++ you have a choice to define a method in the class interface, or separately in an implementation file. How do you decide? u Readability. Only put very small methods in the class definition, so that it is easier to read. u Semantics. Methods defined in class interface may (at the discretion of the compiler) be expanded in-line. Another reason for only defining very small methods this way.

55 55 Variations on Classes u Interfaces in Java (Methods without Implementations) u Nested classes in Java and C++ u Class Data fields

56 56 Properties u Properties are a way to define getters and setters, but allow them to be used as if they were simple assignments and expressions: u writeln ('rank is ', aCard.rank); (* rank is property of card *) u aCard.rank = 5; (* changing the rank property *)

57 57 Inner or Nested Classes u C++ or Java u Whether the inner class can access features of the outer class is different in different languages. u class LinkedList { u... u private class Link { // inner class u public int value; u public Link next; u }

58 58 Class Data Fields u Idea is that all instances of a class can share a common data field. Simple idea, but how to resolve the following paradox. All instances have the same behavior: u Either they all initialize the common area, which seems bad, or u Nobody initializes the common area, which is also bad. u Different languages use a variety of mechanisms to get around this.

59 59 Java Class class PlayingCard { public int suit () { return suitValue; } public int rank () { return rankValue; } private int suitValue; private int rankValue; public static final int Spade = 1; public static final int Diamond = 2; public static final int Club = 3; public static final int Heart = 4; } Note: Java also applies visibility modifiers to each item individually. Does not have enumerated data types, uses symbolic constants instead.

60 60 Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor)

61 61 Data Member Declaration ; private String ownerName ; Modifiers Data Type Name Note: There’s only one modifier in this example.

62 62 Method Declaration ( ){ } public void setOwnerName ( String name ) { ownerName = name; } Statements Modifier Return Type Method Name Parameter

63 63 Constructor u A constructor is a special method that is executed when a new instance of the class is created. public ( ){ } public Bicycle ( ) { ownerName = “ Unassigned ” ; } Statements Modifier Class Name Parameter

64 64 The Definition of the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; }

65 65 The Account Class class Account { private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public double getCurrentBalance( ) { return balance; } public String getOwnerName( ) { return ownerName; } public void setInitialBalance(double bal) { balance = bal; } public void setOwnerName(String name) { ownerName = name; }

66 66 Using Bicycle and Account public class Application2 { //This sample program uses both the Bicycle and Account classes public static void main(String[] args) { Bicycle bike; Account acct; String myName = "Jon Java"; bike = new Bicycle( ); bike.setOwnerName(myName); acct = new Account( ); acct.setOwnerName(myName); acct.setInitialBalance(250.00); acct.add(25.00); acct.deduct(50); //Output some information System.out.println(bike.getOwnerName() + " owns a bicycle and"); System.out.println("has $ " + acct.getCurrentBalance() +" left in the bank"); } }//Application2.java

67 67 Java Visibility Modifiers u The modifiers public and private designate the accessibility of data members and methods. u If a class component (data member or method) is declared private, client classes cannot access it. u If a class component is declared public, client classes can access it. u Internal details of a class are declared private and hidden from the clients. This is information hiding.

68 68 Accessibility Example class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientServer

69 69 Data Members Should Be private u Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private. u Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods.

70 70 Guideline for Visibility Modifiers u Guidelines in determining the visibility of data members and methods: u Declare the class and instance variables private. u Declare the class and instance methods private if they are used only by the other methods in the same class. u Declare the class constants public if you want to make their values directly readable by the client programs. If the class constants are used for internal purposes only, then declare them private.

71 71 Static and Final u Notice how symbolic constants are defined in Java: u static means that all instances share the same value. One per class. Similar meaning in many languages. u final is Java specific, and means it will not be reassigned. (C++ has const keyword that is similar). u public static final int Spade = 1; u public static final int Diamond = 2; u public static final int Club = 3; u public static final int Heart = 4;

72 72 Java Constants class Dice { private static final int MAX_NUMBER = 6; private static final int MIN_NUMBER = 1; private static final int NO_NUMBER = 0; private int number; public Dice( ) { number = NO_NUMBER; } //Rolls the dice public void roll( ) { number = (int) (Math.floor(Math.random() * (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER); } /Returns the number on this dice public int getNumber( ) { return number; }

73 73 Summary u Object-oriented Design u Programming in the large u Design Steps u Design Issues u Class and Methods u Definition u Visibilities u Accessor and setters u Java Classes and Methods

74 74 The End Interesting materials at http://stwww.weizmann.ac.il/g-cs/benari/home/software.html#java


Download ppt "1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Professor of Computer Science Nipissing University."

Similar presentations


Ads by Google