Download presentation
Presentation is loading. Please wait.
1
Object-Oriented Development
2
Course Overview Course Goals
Fundamentals and principles of object-oriented development Object-oriented analysis, design and Programming
3
Assumptions Familiar with preliminary programming background
Data types Program control structures: sequential. selection, repetition Streams and files (program input and output) Simple data structures: array Compilation and execution of simple programs
4
An Example (C++) // File name: HelloWorld.cpp
// Purpose: A simple C++ program which prints "Hello World!" on the screen #include <iostream> // need this header file to support the C++ I/O system using namespace std; // telling the compiler to use namespace "std", // where the entire C++ library is declared. int main() { // Print out a sentence on the screen. // "<<" causes the expression on its right to // be directed to the device on its left. // "cout" is the standard output device -- the screen. cout << "Hello World!" << endl; return 0; // returns 0,which indicate the successful // termination of the "main" function }
5
If not… Decide which programming language you are going to use in this course, and pick up a book, start to read it and practice programming No time and material in this course will be teaching you those preliminary programming experience
6
Course Overview Topics Abstraction, Encapsulation
Interface and Implementation, Abstract Data Type Object-Oriented Design Principles Classes, Methods, Instances Object Communication (Message Passing) Inheritance, Multiple Inheritance
7
Course Overview Topics (Cont.) Static and Dynamic Behavior
Polymorphism Overriding, Overloading, Polymorphic Variable Object Interconnection Coupling and Cohesion Reflection and Retrospection Exception, Error Handling
8
Course Overview Course Website Instructor Course Duties:
Instructor Lirong Dai, Ph.D., University of Texas at Dallas Course Duties: Material Reading In-Class Exercises/Lab Programming Assignments Midterm Final
9
Today… Chapter 1: Thinking Object-Oriented Chapter 2: Abstraction
10
Chapter 1: Thinking Object-Oriented
Why Object-Oriented? Comparison with non-OO approaches What is Object-Oriented?
11
Programming Programming a computer involves writing instructions that enable a computer to carry out a single task or a group of tasks These set of instructions are called as programs or software Programming languages: Java, C++, C#…
12
An Example // File name: HelloWorld.cpp
// Purpose: A simple C++ program which prints "Hello World!" on the screen #include <iostream> // need this header file to support the C++ I/O system using namespace std; // telling the compiler to use namespace "std", // where the entire C++ library is declared. int main() { // Print out a sentence on the screen. // "<<" causes the expression on its right to // be directed to the device on its left. // "cout" is the standard output device -- the screen. cout << "Hello World!" << endl; return 0; // returns 0,which indicate the successful // termination of the "main" function }
13
A Survey of Programming Techniques/Paradigm
Unstructured Programming Procedural Programming Modular Programming Object-Oriented Programming
14
Unstructured Programming
All code is contained in a single continuous block (e.g., “main” program) Has to rely on flow execution statements, such as GOTO (e.g., Spaghetti code) Still used in MS-DOS batch files Old languages, such as BASIC, FORTRAN Assembly language Program Main Program data
15
MS-DOS Batch File Example
rem display and check if there is an argument if "%1"=="" goto noparameter echo the parameter is %1 goto exit :noparameter echo you must supply an argument to this batch file :exit
16
Unstructured Programming (Cont.)
Problems Difficult to read and debug Only works for very simple and small problems Tremendous disadvantages once the program gets sufficiently large For example, if the same statement sequence is needed at different locations within the program, the sequence must be copied Solution: extract these sequences, name them and offer a technique to call and return from these procedures
17
Procedural Programming
Able to combine returning sequences of statements into one single place A procedure call is used to invoke the procedure Data from main program to procedures (i.e., parameters) After the sequence is processed, flow of control proceeds right after the position where the call was made Processed data back to main program Procedures, also known as routines, subroutines, methods, or functions Main Program Procedure Procedure calls
18
C Program Example int add( int, int); /* Function declaration */
main() { int i=1; printf("i starts out life as %d.", i); i = add(1, 1); /* Procure/Function call */ printf(" And becomes %d after function is executed.\n", i); } /********************************************************/ int add( int a, int b) /* Procure/Function definition */ int c; c = a + b; return c;
19
Procedural Programming (Cont.)
Languages COBOL, FORTRAN, BASIC, C, Pascal … Problems Difficulties of reasoning about programs To some degree difficulty of parallelization Relatively low level In large, complicated programs, modularity is generally desirable
20
Modular Programming Module
Generally, a component of a larger system, and operates within that system independently from the operations of the other components Modular Programming A common functionality are grouped together into separate modules A program is now divided into several smaller parts which interact through procedure calls Main Program data Module1 data +data1 Module2 data +data2 Procedure1 Procedure2 Procedure3
21
Modular Programming (Cont.)
Example: a singly linked list Operations on the list Append element in the end Delete element at the front Application: queue Implement the list in two separate modules Interface definition Describe what is available Implementation files Describe how it is made available Fundamental principles in software engineering Change the implementation won’t affect the interface
22
Singly List Interface Definition
/* * Interface definition for a module which implements * a singly linked list for storing data of any type. */ MODULE Singly-Linked-List-1 BOOL list_initialize(); /* Initialize variables local to the module BOOL list_append(ANY data); BOOL list_delete(); list_end(); ANY list_getFirst(); ANY list_getNext(); BOOL list_isEmpty(); END Singly-Linked-List-1
23
Singly List (Cont.) What if we need more than one list in the program?
/* * A list module for more than one list. */ MODULE Singly-Linked-List-2 DECLARE TYPE list_handle_t; /* list_handle_t represents list handle, which is used in every provided procedure to uniquely identify the list in question */ list_handle_t list_create(); list_destroy(list_handle_t this); BOOL list_append(list_handle_t this, ANY data); ANY list_getFirst(list_handle_t this); ANY list_getNext(list_handle_t this); BOOL list_isEmpty(list_handle_t this); END Singly-Linked-List-2;
24
Singly List (Cont.) PROCEDURE foo() BEGIN list_handle_t myList;
myList <- list_create(); /* Do something with myList */ ... list_destroy(myList); END PROCEDURE foo() BEGIN list_handle_t myList; /* List is created and initialized */ /* Do something with the myList */ ... END /* myList is destroyed */
25
Singly List (Cont.) PROCEDURE foo() BEGIN SomeDataType data1;
SomeOtherType data2; list_handle_t myList; myList <- list_create(); list_append(myList, data1); list_append(myList, data2); list_destroy(myList); END /* Oops */ ...
26
Modular Programming Problems Decouple data and behaviors
Module is oriented on operations but not actual data Cannot guarantee type safety Programs can access memory in inappropriate ways Inflexible Hard to extend
27
Object-Oriented Programming (OOP)
What is object-oriented programming? Principles of object-oriented programming
28
Kay's Description of OOP
Object-oriented programming is based on the principle of recursive design Everything is an object Objects perform computation by making requests of each other through the passing of messages Every object has it's own memory, which consists of other objects Every object is an instance of a class. A class groups similar objects The class is the repository for behavior associated with an object Classes are organized into singly-rooted tree structure, called an inheritance hierarchy
29
What is an Object? The most fundamental concept/mechanism of OOP
From an application modeling perspective, an object has the components: characteristics/attributes, services/behaviors), unique identifier, rules and policies, relationships From a design modeling perspective, an object can be an example (instance) of a category (class), can be a category or a type, created (instantiated) by a category, can communicate…
30
What is a Class? From a modeling perspective, a class is a template for a category. It defines characteristics, services, rules and policies, relationships From a design perspective, a class is a special kind of object From an implementation perspective, a class is a “global” object with class data members and class services From a compiler’s perspective, a class is a programmer’s defined data type
31
Principles of Object-Orientation
Principle 1. Encapsulation: The object contains both the data and the methods (code) that manipulate or change that data
32
Case Study In this example, we have a family with a father (John), a mother (Jane), two sons (Peter and Paul), and two daughters (Elizabeth and Mary). John is an actor and Jane is a dentist. All the children are students and the family dog is Lassie. Their family physician is Alice. This family owns a house in the suburbs. Although mowing the family lawn is normally a chore for the father, it can be a paid chore for any one of the children. However, working within the neighborhood is Jack, a professional lawn mower. One morning, Jane notices that the lawn needs mowing, so she mentions to John that it is time to mow the lawn. John agrees and says that he will mow the lawn this evening. Later that evening, John comes home and is exhausted from a long day at the studio and decides to pay one of his children to mow the lawn. He looks for one of his children; he sees Mary first. He asks Mary to mow the lawn for five dollars. Mary agrees; however, Mary knows that Jack, a professional lawn mower, is willing to mow the lawn for four dollars. So Mary calls Jack to mow the lawn for four dollars and Jack agrees to mow the lawn. Jane comes home later that evening and she sees the lawn mowed. Thinking that John mowed the lawn, Jane complements John on the excellent condition of the lawn.
33
Principles of Object-Orientation
Principle 2. Information Hiding: The object that contains the attributes (data) defines what services (functions) are available to the other objects and prevents other objects from access or knowledge of the attributes (data) and how a service (function) is provided Information hiding is important because it allows an object complete control over the integrity of the data contained within it. This gives us high cohesion and low coupling concerning the manipulation of data Note: Encapsulation alone does not prevent the data of an object from being manipulated by functions other than the methods bound to the object. Protecting data from manipulation by entities outside the object can be achieved by requiring that access of data can only be provided by the services of the object that contains the data.
34
Principles of Object-Orientation
Principle 3. Message Passing: An object may communicate with another object only via the message-passing mechanism Each message must be sent to a designated receiver, and the interpretation of the message depends on the receiver
35
Principles of Object-Orientation
Principle 4. Late Binding: Support for the ability to determine the specific receiver and its corresponding method (code) to be executed for a message at runtime This is another way in which message passing in the OOP differs from a function call is that the specific receiver of any given message is not usually known until runtime, so the determination of which method to invoke cannot be made until then Late binding enables to model a real behavior of the world. For example, if you are reading the textbook in a class at school, it is unlikely that you could have known who your classmates would be before the first day of the class. You only know who your classmates are once the class has begun, and even then some individuals might register late
36
Principles of Object-Orientation
Principle 5. Delegation: Work is passed, via message passing, from one object (client) to another object (agent) because from the client’s perspective, the agent has the service that the client needs. Work is continuously passed until it reaches the object that has both the data and the method (code) to perform the work
37
Principles of Object-Orientation
Principle 6. Class/Instance/Object: All objects are instances of a class. Instance can be created (instantiated) or destroyed (deleted) at runtime. How the object provides a service is determined by the class of which the object is an instance
38
Principles of Object-Orientation
Principle 7. Generalization/Specialization: Classes can be organized by using a hierarchical inheritance structure. In the structure, the specialized class (subclass) inherits the attributes, the relationships, the methods from the generalized class (superclass) that is higher in the structure
39
Principles of Object-Orientation
Principle 8. Relationships: Collaboration between objects to provide a service to a client are usually captured by an association relationship
40
Principles of Object-Orientation
Principle 9. Reflection: Each object knows the detailed information about the class(es) and the interface(s) to which it is an instance. This means that an application can, at runtime, acquire information about the object from the object itself
41
CSSE501 Object-Oriented Development
42
Chapter 2: Abstraction Abstraction This chapter
the most important tool used in the control of complexity This chapter Various abstraction mechanisms A short history of the development of abstraction tools
43
Abstraction Abstraction is the purposeful suppression, or hiding, of some details of a process or artifact, in order to bring out more clearly other aspects, details, or structure
44
Information Hiding Information hiding is the purposeful omission of details in the development of an abstract representation Information hiding is what allows abstraction to control complexity
45
Abstraction in an Atlas
The various different levels of maps A map of the world, contains mountain ranges, large political boundaries A map of a continent, contains all political boundaries, large cities A map of a country, contains more cities, major roads A map of a large city, roads, major structures A map of a portion of a city, buildings, occupants Each level contains information appropriate to the level of abstraction
46
Levels of Abstraction in OO Program
At the highest level of abstraction we view a program as a community of interacting objects Important characteristics here are the lines of communication between the various agents
47
Abstraction in OO Programs -- Packages and Name spaces
The next level of abstraction is found in some (but not all) OO languages. A package, Unit or Name Space allows a programmer to surround a collection of objects (a small community in itself) with a layer, and control visibility from outside the module
48
Abstraction in OO Languages -- Clients and Servers
The next level of abstraction considers the relationship between two individual objects. Typically one is providing a service, and the other is using the service
49
Abstraction in OO languages -- Description of Services
We can next examine just the person providing a service, independent of the client. We define the nature of the services that are offered, but not how those services are realized
50
Levels of Abstraction in OO -- Interfaces
Interfaces are one way to describe services at this level of abstraction. interface Stack { public void push (Object val); public Object top () throws EmptyStackException; public void pop () throws EmptyStackException; }
51
Levels of Abstraction -- An Implementation
Next we look at the services provided, but from the implementation side: public class LinkedList implements Stack ... { public void pop () throws EmptyStackException { ... } ... }
52
Levels of Abstraction -- A Method in Isolation
Finally, we consider the implementation of each method in isolation public class LinkedList implements Stack ... { ... public void pop () throws EmptyStackException if (isEmpty()) throw new EmptyStackException(); removeFirst(); // delete first element of list } }
53
Finding the Right Level of Abstraction
Critical problem in early stages of development is to determine what details are appropriate at each level of abstraction, and (often more importantly) what details should be omitted One does not want to ignore or throw away important information But one does not want to manage too much information, or have the amount of information hide critical details
54
Forms of Abstraction Specialization class hierarchies Division
into parts Service view ADT(Abstract Data Type) Patterns OOP Mathematical induction Recursive algorithm Recursive data structures Composition Catalogs Cross-references Dictionaries Multiple views Repetition Abstraction
55
Is-a and Has-A abstraction
Two of the most important types of abstraction are the following: Division into parts -- Has-a abstraction Division into specialization -- Is-a abstraction
56
Has-A Abstraction Division into parts takes a complex system, and divides into component parts, which can then be considered in isolation Characterized by sentences that have the words “has-a'' A car has-a engine, and has-a transmission A bicycle has-a wheel A window has-a menu bar Allows us to drop down a level of complexity when we consider the component in isolation
57
Is-a Abstraction Is-a abstraction takes a complex system, and views it as an instance of a more general abstraction Characterized by sentences that have the words “is-a'' A car is a wheeled vehicle, which is-a means of transportation A bicycle is-a wheeled vehicle A pack horse is-a means of transportation Allows us to categorize artifacts and information and make it applicable to many different situations
58
Encapsulation and Interchangeability
An important aspect of division into parts is to clearly characterize the connection, or interface, between to components Allows for considering multiple different implementations of the same interface For example, a car can have several different types of engine and one transmission
59
The Service View Another way to think of an interface is as a way of describing the service that an object provides The interface is a contract for the service--if the interface is upheld, then the service will be provided as described
60
Other Types of Abstraction -- Composition
Details will be discussed later…
61
Patterns Patterns are another attempt to document and reuse abstractions Patterns are description of proven and useful relationships between objects; which can help guide the solution of new problems Example pattern, Proxy:
62
A Short History of Abstraction Mechanisms
Another way to better understand OOP is to put it in context with the history of abstraction in computer science. Assembly languages Procedures Modules ADT (Abstract Data Types) The Service View Objects The future....
63
Abstract Data Types (ADT)
An Abstract Data Type is a programmer-defined data type that can be manipulated in a manner similar to system-provided data types Must have the ability to instantiate many different copies of the data type Data type can be manipulated using provided operations, without knowledge of internal representation But ADTs were important not because they were data structures, but because they provided an easily characterized service to the rest of an application
64
ADT Examples String List Linked List Stack Queue Binary search tree
Priority queue Complex number Associative array Multimap
65
Stack ADT op(Stack s) : Void Precondition: isEmpty(s) returns false Postconditions: See Explanation that follows Explanation: A push immediately followed by a pop has no effect on the stack. This is the Stack Axiom. Any sequence of pushes and pops (after create has been called) will yield the same result as a certain sequence of only push operations. destroy(Stack s) : Void Precondition: s is not null Postcondition: s is null create() : Stack Precondition: none Postconditions: if s = create() then: s is a newly created object isEmpty(s) returns true isEmpty(Stack s) : Boolean Precondition: s is not null top(Stack s) : Object Precondition: isEmpty(s) returns false push(Stack s, Object o) : Void Precondition: s is not null Postconditions: top(stack) returns o isEmpty(s) returns false
66
Objects - ADT's with Message Passing
Characteristics of Objects Encapsulation -- similar to modules Instantiation -- similar to ADT's Messages -- dynamic binding of procedure names to behavior Classes -- a way of organization that permits sharing and reuse Polymorphism -- A new form of software reuse using dynamic binding
67
CSSE 501 Object-Oriented Development
68
Today… Chapter 3: Object-Oriented Design
69
Programming in the Small and Programming in the Large
70
Chapter 3: Object-Oriented Design
Software development Ultimate goal: deliver software products that are oriented towards Customer satisfaction Customer delight Customer ecstasy
71
Popular software development methodologies
System Development Life Cycle (SDLC) Model Prototyping Model Rapid Application Development Model Component Assembly Model
72
System Development Life Cycle (SDLC) Model
Waterfall model System/Information Engineering and Modeling 2. Software Requirement Analysis 3. System Analysis and Design 4. Code Generation/ Implementation 5. Testing 6. Maintenance
73
Prototyping Model A cyclic version of the linear model
Once the requirement analysis is done and the design for a prototype is made, the development process gets started to create a prototype Once the prototype is created, it is given to the customer for evaluation Many iterations between customers’ feedback and developers’ refinement until the final software package is delivered In this methodology, the software is evolved as a result of periodic shuttling of information between the customer and developer Popular development model in the contemporary IT industry - as it is very difficult to comprehend all the requirements of a customer in one shot New versions of a software product evolve as a result of prototyping
74
Prototyping Model( many versions)
or
75
Rapid Application Development (RAD) Model
A "high speed" adaptation of the linear sequential model Achieved by using a component-based construction approach The RAD approach encompasses the following phases: Business modeling The information flow among business functions is modeled in a way that answers the following questions: What information drives the business process? what information is generated? Who generates it? where does the information go? who processes it? Data modeling The information flow defined as part of the business modeling phase is refined into a set of data objects that are needed to support the business The characteristic (called attributes) of each object is identified and the relationships between these objects are defined
76
Rapid Application Development (RAD) Model (Cont.)
Process modeling The data objects defined in the data-modeling phase are transformed to achieve the information flow necessary to implement a business function Processing the descriptions are created for adding, modifying, deleting, or retrieving a data object Application generation The RAD model assumes the use of the RAD tools like VB, VC++, Delphi etc... rather than creating software using conventional third generation programming languages The RAD model works to reuse existing program components (when possible) or create reusable components (when necessary) In all cases, automated tools are used to facilitate construction of the software Testing and turnover Since the RAD process emphasizes reuse, many of the program components have already been tested. This minimizes the testing and development time
77
Component Assembly Model
Object technologies provide the technical framework for a component-based process model for software engineering The object oriented paradigm emphasizes the creation of classes that encapsulate both data and the algorithm that are used to manipulate the data If properly designed and implemented, object oriented classes are reusable across different applications and computer based system architectures Component Assembly Model leads to software reusability. The integration/assembly of the already existing software components accelerate the development process Nowadays many component libraries are available on the Internet. If the right components are chosen, the integration aspect is made much simpler
78
What/Why is Software Design
Software design sits at the crossroads of all the computer disciplines: hardware and software engineering, programming, human factors research, ergonomics. It is the study of the intersection of human, machine, and the various interfaces—physical, sensory, psychological—that connect them --- by Association for Software Design (ASD) members Design is conscious Design keeps human concerns in the center Design is a dialog with materials Design is creative Design is communication Design is a social activity Design has social consequences
79
Basis for Design Consider for the moment what aspects of a problem (i.e., to develop a system) are known first: Data Structures Functions A Formal Specification Behavior A design technique based on behavior can be applied from the very beginning of a problem, whereas techniques based on more structural properties necessarily require more preliminary analysis
80
Design Notations/Modeling Languages
Many artifacts generated during the process of software development Requirement specifications Design documents Source code User manual Design notations capture design documents Informal (natural languages) Unified Modeling Languages (UML, semi-formal) Formal (formal methods, architecture description languages)
81
Object-Oriented Design Techniques/Methods
Object-Oriented Development (OOD)/Booch Hierarchical Object-Oriented Design (HOOD) The Object Modeling Technique (OMT) Responsibility-Driven Design (RDD)/Class-Responsibility-Collaboration (CRC) Object-Oriented Analysis (OOA) …
82
Object-Oriented Development (OOD)/Booch
Define the problem Develop an informal strategy for the software realization of the real world problem domain Formalize the strategy Identify the classes and objects at a given level of abstraction Identify the semantics of these classes and objects Identify the relationships among these classes and objects Implement these classes and objects
83
Object-Oriented Development (OOD)/Booch (Cont.)
Major advantages Rich notation available: class diagrams (class structure - static view) object diagrams (object structure - static view) state transition diagrams (class structure - dynamic view) timing diagrams (object structure - dynamic view) module diagrams (module architecture) process diagrams (process architecture)
84
Object-Oriented Development (OOD)/Booch (Cont.)
A Booch Class Diagram for a Company
85
The Object Modeling Technique (OMT)
A method which leads to three models of the system corresponding to three different views of the system The object model Describes the static structure of the objects in a system and their relationships Main concepts are: class, attribute, operation, inheritance, association (i.e. relationship), aggregation The dynamic model Describes the aspects of the system that change over time Used to specify and implement the control aspects of a system Main concepts are: state, sub/super state, event, action, activity The functional model Describes the data value transformations within a system Main concepts are: process, data store, data flow, control flow, actor (source/sink)
86
The Object Modeling Technique (OMT)(Cont.)
The method is divided into four phases, which are stages of the development process Analysis The building of a model of the real world situation, based on a statement of the problem or user requirements System design The partitioning of the target system into subsystems, based on a combination of knowledge of the problem domain and the proposed architecture of the target system (solution domain) Object design Construction of a design, based on the analysis model enriched with implementation detail, including the computer domain infrastructure classes Implementation Translation of the design into a particular language or hardware instantiation, with particular emphasis on traceability and retaining flexibility and extensibility
87
The Object Modeling Technique (OMT)(Cont.)
An Object Model of a Company
88
Responsibility Driven Design (RDD)
Developed as Rebecca Wirfs-Brock One of object-oriented design techniques, driven by an emphasis on behavior at all levels of development A design technique that has the following properties: Can deal with ambiguous and incomplete specifications Naturally flows from Analysis to Solution Easily integrates with various aspects of software development
89
Responsibility Driven Design (RDD)
Describing the actions and activities for which our software is responsible Describing the responsibilities in terms that both users and developers can understand Designing software objects that implement those responsibilities
90
Responsibility Driven Design (RDD)
RDD is not a sequential process Steps in RDD Software components Formalize interfaces Designing and representations Implementing components Integration of components Maintenance and evolution
91
Case Study: the IIKH Briefly, the Intelligent Interactive Kitchen Helper (IIKH) will replace the box of index cards of recipes in the average kitchen
92
Your Job Imagine you are the chief software architect
Your job is to develop the software that will implement the IIKH
93
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, say a week Generate a grocery list that includes all the items in all the menus for a period
94
Characterization by Behavior
Just as an Abstract Data Type is characterized more by behavior than by representation, the goal in using Responsibility Driven Design will be to first characterize the application by behavior First capture the behavior of the entire application Refine this into behavioral descriptions of subsystems Refine behavior descriptions into code This emphasis on behavior is a hallmark of Object-Oriented programming
95
Working Through Scenarios
Because of the ambiguity in the specification, the major tool here used to uncover the desired behavior is to walk through application scenarios Pretend there is already a working application Walk through the various uses of the system Establish the “look and feel'' of the system Make sure uncover all the intended uses Develop descriptive documentation Create the high level software design The term “use-cases'' used for this process of developing scenarios by others
96
Example: Browsing Scenario
Alice Smith starts the IIKH IIKH displays welcome message Alice presses the return button to begin Alice is given a choices of a number of options Alice selects to browse recipe Alice enters keywords to search, e.g., salmon, dill weed IIKH return two results Alice selects the first IIKH displays a window, showing everything regarding the recipe Alice does not want the recipe, returns to the search result page Alice selects the second recipe Alice wants the recipe Alice selects “quit” from the IIKH program menu The IIKH program quits
97
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 function, a module, or something else A component must have a small well defined set of responsibilities A component should interact with other components to the minimal extent possible
98
CRC (Component, Responsibility, Collaborator) Cards
Components are most easily described using CRC cards A CRC card records the name, responsibilities, and collaborators of an component Inexpensive, Erasable, Physical
99
The first component, The Greeter
Let us return to the development of the IIKH. The first component your team defines is the Greeter When the application is started, the Greeter puts an informative and friendly welcome window (the greeting) on the screen Offer the user the choice of several different actions Casually 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
100
The Greeter
101
The Recipe Database Component
Ignoring the planning of meals for the moment, your team elects to next explore the recipe database component 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
102
The Who/What Cycle As we walk through scenarios, we go through cycles of identifying a what, followed by a who What action needs to be performed at this moment Who is the component charged with performing the action Every what must have a who, otherwise it simply will not happen Sometimes the who might not be obvious at first, i.e., who should be in charge of editing a recipe?
103
Postponing Decisions Many decisions, such as the method of browsing, can be ignored for the moment, as they are entirely encapsulated within the recipe database component, and do not effect other components Scroll bars and windows? A virtual “book'' with thumb-holes and flipping pages? Keywords and phrases? Only need to note that somehow the user can manipulate the database to select a specific recipe
104
Responsibilities of a Recipe
We make the recipe itself into an active data structure. It maintains information, but also performs tasks Maintains the list of ingredients and transformation algorithm (i.e., ingredients to final product) 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 We will add other actions later (ability to scale itself, produce integrate ingredients into a grocery list, and so on)
105
The Planner Component Returning to the greeter, we start a different scenario. This leads to the description of the Planner Permits the user to select a sequence of dates for planning Permits the user to edit an existing plan Associates with Date object
106
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 (''Bob's Birthday'', “Christmas Dinner'', and so on) Can print out grocery list for entire set of meals
107
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, recipes are automatically scaled Can produce grocery list for entire meal, by combining grocery lists from individual scaled recipes
108
The Six Components Having walked through the various scenarios, you team eventually decides everything can be accomplished using only six software components You can at this point assign the different components to different programmers for development
109
Interaction Diagrams The picture on the previous slide captures static relationships, but not the dynamic flow of messages in a scenario That information can be recorded by an interaction diagram
110
Characteristics of Components
Let us return to the idea of a software component There are many different aspects to this simple idea, we will consider just a few: Behavior and state Instances and classes Coupling and cohesion Interface and implementation
111
Behavior and State All components can be characterized by two aspects
The behavior of a component is the set of actions a component can perform. The complete set of behavior for a component is sometimes called the protocol The state of a component represents all the information (data values) held within a component 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
112
Instances and Classes We can now clarify a point we earlier ignored. There are likely many instances of recipe, but they will all behave in the same way. We say the behavior is common to the class Recipe
113
Coupling and Cohesion The separation of tasks into the domains 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 Want to maximize cohesion Coupling is the degree to which the ability to fulfill a certain responsibility depends upon the actions of another component Want to minimize coupling
114
Interface and Implementation
We have characterized software components by what they can do The user of a software component need only know what it does, not how it does it “Ask not what you can do to a data structure, ask instead what your data structures can do for you''.
115
Two views of a Software System
This naturally leads to two views of a software system The term information hiding is used to describe the purposeful hiding of implementation details
116
Parnas' Principles These ideas were captured by computer scientist David Parnas in a pair of rules, which are known as Parnas' Principles: 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 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
117
Public and Private View
In C++ and Java, Parnas's Principles lead to the ideas of a public and private view Public view - those features (data or behavior) that other components can see and use Private view - those features (data or behavior) that are used only within the component
118
Next Step - Formalize the Interface
The next step is to formalize the channels of communication between the components The general structure of each component is identified Components with only one behavior may be made into functions Components with many behaviors are probably more easily implemented as classes Names are given to each of the responsibilities - these will eventually be mapped on to procedure names Information is assigned to each component and accounted for Scenarios are replayed in order to ensure all data is available
119
Names with Activities The selection of names is an important task
Names should be evocative in the context of the problem Names should be short Names should be pronounceable (read them out load) Names should be consistent within the project Avoid digits within a name
120
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
121
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 carried back to the clients to make sure the users and the implementers have the same ideas
122
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 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
123
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 or diary of the process schedule 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
124
Preparing for Change Your design team should also keep in mind that change is inevitable Users requirements change with experience, hardware changes, government regulations change Try to predict the most likely sources of change, and isolate the effect Common changes include interfaces, file formats, communication protocols Isolate interfaces to hardware that is likely to change Reduce dependency of one software component on another Keep accurate record of the reasoning behind every major decision in the design documentation
125
Next Step - Select Representations for Subsystems
Next the internal representation of the software subsystem corresponding to each component is selected Knowledge of the classic data structures of Computer Science is important here Often once data structures have been selected, the code is almost self-evident
126
Next Step - Implement and Test Subsystems
Classic techniques, such as stepwise refinement, are used to implement each of the subsystems Subsystems are validated in isolation Informal proofs of correctness for the subsystem are developed Identify necessary conditions for correct functioning. Try to minimize conditions, and test input values whenever possible Software testing is used as a confidence building measure
127
Step - Integration and Testing
Components are slowly integrated into completed system Stubs can be used to perform testing all during integration Errors discovered during integration to cause reinvestigation of validation techniques performed at the subsystem level
128
Maintenance and Evolution
Software does not remain fixed after the first working version is released Errors or bugs can be discovered. 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 Better documentation may be required. A good design recognizes the inevitability of change, and plans an accommodation for these activities from the very beginning
129
Common Design Flaws The following categories present some of the more common design flaws: Direct modification Components that make direct modification of data values in other components are a direct violation of encapsulation Such coupling makes for inflexible designs Too Much Responsibility Components with too much responsibility are difficult to understand and to use Responsibility should be broken into smaller meaningful packages and distributed No Responsibility Components with no responsibility serve no purpose Often arise when designers equate physical existence with logical design existence “Money is no object'' Components with unused responsibility Usually the result of designing software components without thinking about how they will be used Misleading Names Names should be short and unambiguously indicate what the responsibilities of the component involve
130
CSSE501 Object-Oriented Development
131
Chapter 4: Classes and Methods
Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile time representation of object-oriented programs. Chapter 5 discusses the dynamic, run time behavior Both are important, and both chapters should be understood before you begin further investigation of object-oriented programming
132
Same Ideas, Different Terms
All OOP languages have the following concepts, although the terms they use may differ: classes, object type, factory object instances, objects message passing, method lookup, member function invocation, method binding methods, member function, method function inheritance, subclassing
133
Encapsulation and Instantiation
What is a class? A class is a category of objects; it is a new data type you create that is more complex than the basic data types Classes provide a number of very important capabilities: Encapsulation - The purposeful hiding of information, thereby reducing the amount of details that need to be remembered/communicated among programmers A Service View - The ability to characterize an object by the service it provides, without knowing how it performs its task Instantiation - The ability to create multiple instances of an abstraction
134
Examples Student Book Vehicle Banking Account ……
135
Behavior and State A class can also be viewed as a combination of behavior and state Behavior: The actions that an instance can perform in response to a request. Implemented by methods 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)
136
Take the Student Class as an Example
Behavior Register/withdraw courses Provide or change his/her name, ID, average grade, Provide or change his/her contact information … State Courses that are taking/taken Name, ID number, Average grade Address & Phone Number ….
137
Class Definitions We will use the Student class as a running example for the class definition, and show how this appears in several languages
138
C++ Class Definition (Partial)
class Student { int idNum; string name; double gradePointAverage; void displayStudentData(); };
139
Java Class Definition (Partial)
class Student { int idNum; string name; double gradePointAverage; void displayStudentData(); }
140
Visibility Modifiers Accessibility to data fields (state) and methods (behavior) Purpose Information hiding Visibility of a class (interface, field, method) should be as restricted as possible Clear abstraction of program components Does visibility of program components affect security? Intuitively, it should A secret may be embedded in an object as its private field Untrusted code can be prevented from executing sensitive code by placing it in a package-local class
141
Visibility Modifiers The terms public and private are used to differentiate the internal and external aspects of a class. Public Public features can be seen and manipulated by anybody (All part of the application) -- they are the external (interface or service) view Private Private features can be manipulated only within a class. They are the internal (implementation) view Protected (Only in some, Not in all OO languages) Protected features can be used only in the same package and from subclasses in other packages
142
Visibility Modifiers Typically in object-oriented technology
All the data fields should be private All the methods that are accessible by other should be public Protected should only be used when a subclass needs access to what would otherwise be a private member
143
C++ Class Definition (Partial)
class Student { private: int idNum; string name; double gradePointAverage; public: void displayStudentData(); };
144
Java Class Definition (Partial)
class Student { private int idNum; private string name; private double gradePointAverage; public void displayStudentData(); }
145
Methods Although syntax will differ depending upon language, all methods have the following: A name that will be matched to a message to determine when the method should be executed A signature, which is the combination of return type and argument types. Methods with the same name can be distinguished by different signatures a body, which is the code that will be executed when the method is invoked in response to a message
146
C++ Class Definition (Partial)
//declaration section: class Student { private: int idNum; string name; double gradePointAverage; public: void displayStudentData(); }; //implementation section: void Student::displayStudentData() { cout<<“Student #”<<idNum<< “’s name is “<<name<<endl; cout<<“The grade point average for this student is “ <<gradePointAverage<<endl; } Body Name: dispalyStudentData Signature: void Student::displayStudentData()
147
Java Class Definition (Partial)
class Student { private int idNum; private string name; private double gradePointAverage; public void displayStudentData() { system.out.println(“Student #” + idNum +” ‘s name is” + name); system.out.println(“The grade point average for this student is “ + gradePointAverage); } Body Name: dispalyStudentData Signature: public void Student::displayStudentData()
148
Constructor A constructor
Is a method that is used to initialize a newly constructed object Is called automatically each time an object is created In C++, Java, C# and many other languages it has the same name as the class A constructor cannot have a return type
149
C++ Class Definition (Partial)
//declaration section: class Student { private: int idNum; string name; double gradePointAverage; public: Student(); void displayStudentData(); }; Student::Student() { idNum = 9999; name = “J. Smith”; gradePointAverage = 0.0; } void Student::displayStudentData() { …… A constructor without arguments
150
Java Class Definition (Partial)
class Student { private int idNum; private string name; private double gradePointAverage; public Student() { idNum = 9999; name = “J. Smith”; gradePointAverage = 0.0; } public void displayStudentData() { system.out.println(“Student #” + idNum +” ‘s name is” + name); system.out.println(“The grade point average for this student is “ + gradePointAverage); A constructor without arguments
151
Accessor (or getter) Methods
Since all data fields should be private, how can we update or present a student’s information? Answer: through accessor or setter methods An accessor (or getter) is a method that simply returns an internal data value Therefore, we can present private data fields
152
Why Use an Accessor? There are many reasons why an accessor is preferable to providing direct access to a data field. You can make the data field read-only (private) It provides better documentation that the data field is accessible It makes it easier to later change the access behavior (count number of accesses, whatever) Some conventions encourage the use of a name that begins with get, (as in getRank()), but this is not universally followed
153
C++ Class Definition (Partial)
//declaration section: class Student { private: int idNum; string name; double gradePointAverage; public: Student(); void displayStudentData(); int getIDNum(); string getName(); double getGradePointAverage(); }; Student::Student() { …… } void Student::displayStudentData() int Student::getIdNum() { return idNum; } string Student::getName() { return name; double Sudent::getGradePointAverage() { return gradePointAverage; Accessors
154
Java Class Definition (Partial)
class Student { private int idNum; private string name; private double gradePointAverage; public Student() { …… } public void displayStudentData() { …. } public int getIdNum() { return idNum; } public string getName() { return name; public double getGradePointAverage() { return gradePointAverage; Accessors
155
Setters (or mutators) A setter (sometimes called a mutator method) is a method that is used to change the state of an object: Mutators are less common than accessors, but reasons for using are similar
156
C++ Class Definition (Partial)
//declaration section: class Student { private: int idNum; string name; double gradePointAverage; public: Student(); void displayStudentData(); int getIDNum(); string getName(); double getGradePointAverage(); void setIDNum(int); void setName(string); void setGradePointAverage(double); }; …… void Student::setIdNum(int num) { const int MAX_NUM = 9999; if (num <= MAX_NUM) idNum = num; else idNum = MAX_NUM; } void Student::setName(string nameIn) { name = nameIn; void Sudent::setGradePointAverage(double grade) { gradePointAverage = grade: setters
157
Java Class Definition (Partial)
class Student { private int idNum; private string name; private double gradePointAverage; public Student() { …… } public void displayStudentData() { …. } public int getIdNum() { return idNum; } public string getName() { return name; public double getGradePointAverage() { return gradePointAverage; public void setIdNum(int num) { const int MAX_NUM = 9999; if (num <= MAX_NUM) idNum = num; else idNum = MAX_NUM; } public void setName(string nameIn) { name = nameIn; public void setGradePointAverage(double grade) { gradePointAverage = grade: setters
158
Constant Data Fields Some languages allow data fields to be declared as constant (const modifier in C++, final in Java, other languages have other conventions). Constant data fields can be declared as public, since they cannot be changed class PlayingCard { // Java example ... public static final int Spade = 1; public static final int Diamond = 2; public static final int Club = 3; public static final int Heart = 4; }
159
Order of Methods For the most part, languages don't care about the order that methods are declared. Here are some guidelines: List important topics first. Constructors are generally very important, list them first. Put public features before private ones. Break long lists into groups List items in alphabetical order to make it easier to search. Remember that class definitions will often be read by people other than the original programmer. Remember the readers, and make it easy for them
160
Internal and External Views
As we noted in the last chapter, encapsulation means there are two views of the same system. The outside, or service view, describes what an object does. The inside, or implementation view, describes how it does it
161
Separation of Definition and Implementation
In some languages (such as C++ or Object Pascal) the definition of a method can be separated from its implementation. They may even be in a different file class PlayingCard { public: ... Colors color () ; ... }; PlayingCard::Colors PlayingCard::color ( ) { // return the face color of a playing card if ((suit == Diamond) || (suit == Heart)) return Red; return Black; }
162
Considerations in Method Definitions
In C++ you have a choice to define a method in the class interface, or separately in an implementation file. How do you decide? Readability. Only put very small methods in the class definition, so that it is easier to read. 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.
163
Interfaces in Java An interface is like a class, but it provides no implementation. Later, another class can declare that it supports the interface, and it must then give an implementation. We will have much more to say about interfaces later after we discuss inheritance. public interface Storing { void writeOut (Stream s); void readFrom (Stream s); }; public class BitImage implements Storing void writeOut (Stream s) { // ... } void readFrom (Stream s) { // ... }
164
CSSE501 Object-Oriented Development
165
Chapter 5: Messages, Instances and Initialization
This chapter examines OOP run-time features: Object Creation and Initialization (constructors) Message Passing Syntax Accessing the Receiver from within a method Memory Management or Garbage Collection
166
Constructors A constructor is a function that is implicitly invoked when a new object is created. The constructor performs whatever actions are necessary in order to initialize the object In C++, Java, C# a constructor is a function with the same name as the class. In Python constructors are all named __init__ In Delphi, Objective-C, constructors have special syntax, but can be named anything. (Naming your constructors create is a common convention) class PlayingCard { // a Java constructor public PlayingCard (int s, int r) { suit = s; rank = r; faceUp = true; } ...
167
Overloaded Constructors
Constructors are often overloaded, meaning there are a number of functions with the same name. They are differentiated by the type signature, and the arguments used in the function call or declaration: Student::Student() { idNum = 9999; name = “J. Smith”; gradePointAverage = 0.0; } Student::Student(int id) { idNum = id; …… Student::Student(int id, string nm, double grade) name = nm; gradePointAverage = grade; //C++ example class Student { private: int idNum; string name; double gradePointAverage; public: Student(); Student(int); Student(int, string); Student(int, string, double); …… };
168
//Java Example class DigitalCounter { private int counter; private int minimum; private int maximum; public DigitalCounter() {counter = 0; minimum = 0; maximum = 9;} public DigitalCounter(int counter, int minimum, int maximum) { this.counter = counter; this.minimum = minimum; this.maximum = maximum; } //return the current counter value public int getCounter() { return counter; } public int getMinimum() { return minimum; } public int getMaximum() { return maximum; } public void setCounter(int counter) { this.counter = counter;} public void setMinimum(int minimum) {this.minimum = minimum;} public void setMaximum(int maximum) {this.maximum = maximum;} public void increaseCounter() { if (counter == maximum) counter = minimum; else counter = counter +1;
169
Instances Now, we could use constructors to create instances of classes C++ Student oneStudent; Student twoStudent(7766, “Anna Moore”, 3.74);
170
Instances Java //a digital counter DC1 with minimum 0, maximum 9, and
//current counter value 0 DigitalCounter DC1 = new DigitalCounter(); //a digital counter DC2 with minimum 0, maximum 59, and //current counter value 5 DigitalCounter DC2 = new DigitalCounter(5, 0, 59);
171
Object Creation In most programming languages objects must be created dynamically, usually using the new operator: PlayingCard aCard; // simply names a new variable aCard = new PlayingCard(Diamond, 3); // creates the new object The declaration simply names a variable, the new operator is needed to create the new object value
172
Messages are not Function Calls
Recall from chapter 1 that we noted the following differences between a message and a function (or procedure) call A message is always given to some object, called the receiver The action performed in response is determined by the receiver, different receivers can do different actions in response to the same message
173
Message Passing Syntax
Although the syntax may differ in different languages, all messages have three identifiable parts: aGame.displayCard (aCard, 42, 27); The message receiver: aGame The message selector: displayCard An optional list of arguments: aCard, 42, 27
174
Statically Types and Dynamically Typed Languages
A distinction we will see throughout the term is between the following: A statically typed language requires the programmer to declare a type for each variable. The validity of a message passing expression will be checked at compile time, based on the declared type of the receiver (e.g., Java, C++, C#, Pascal). A dynamically typed language associates types with values, not with variables. A variable is just a name. The legality of a message cannot be determined until run-time (E.g., Smalltalk, CLOS, Python).
175
The Receiver Variable Inside a method, the receiver can be accessed by means of a pseudo-variable Called this in Java, C++, C# Called self in Smalltalk, Objective-C, Object Pascal Called current in Eiffel function PlayingCard.color : colors; begin if (self.suit = Heart) or (self.suit = Diamond) then color := Red else color := Black; end
176
Implicit Use of This Within a method a message expression or a data access with no explicit receiver is implicitly assumed to refer to this: class PlayingCard { ... public void flip () { setFaceUp( ! faceUp ); } ... } Is assumed to be equivalent to: class PlayingCard { ... public void flip () { this.setFaceUp( ! this.faceUp); } ... }
177
Memory Recovery Because in most languages objects are dynamically allocated, they must be recovered at run-time. There are two broad approaches to this: Force the programmer to explicitly say when a value is no longer being used (e.g., C++, Delphi Pascal): delete aCard; // C++ example Use a garbage collection system that will automatically determine when values are no longer being used, and recover the memory (e.g., Java, C#, Smalltalk, CLOS).
178
Memory Errors Garbage collection systems impose a run-time overhead, but prevent a number of potential memory errors: Running out of memory because the programmer forgot to free values Using a memory value after it has been recovered PlayingCard * aCard = new PlayingCard(Spade, delete aCard; cout << aCard.rank(); Free the same value twice PlayingCard * aCard = new PlayingCard(Spade, 1); delete aCard; delete aCard; // delete already deleted value
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.