01 - OO Overview
01 - OO Overview
Questions to ponder
How does software differ from other products? How does software change over time? What do we mean when we talk about high-quality software? How are software projects organized? How can we define software engineering? Why will following a disciplined approach to software engineering help us produce successful software systems? What activities occur in every software project? What should we keep in mind as we perform any software engineering activity?
Types of Software...
Custom For a specific customer Generic Sold on open market Often called COTS (Commercial Off The Shelf) Shrink-wrapped Embedded Built into hardware Hard to change
7
Types of Software
Differences among custom, generic and embedded software
Number of copies in use Total processing power devoted to running this type of software Worldwide annual development effort Custom low low Generic medium high Embedded high medium
high
medium
low
Types of Software
Real time software E.g. control and monitoring systems Must react immediately Safety often a concern Data processing software Used to run businesses Accuracy and security of data are key Some software has both aspects
12
13
14
Exercise 1
How do you think each of the four types of stakeholders would react in each of the following situations? You study a proposal for a new system that will completely automate the work of one individual in the customers company. You discover that the cost of developing the system would be far more than the cost of continuing to do the work manually, so you recommend against proceeding with the project. You implement a system according to the precise specifications of a customer. However, when the software is put to use, the users find it does not solve their problem.
15
Software Quality...
Customer: solves problems at an acceptable cost in terms of money paid and resources used QUALITY SOFTWARE Developer: easy to design; easy to maintain; easy to reuse its parts Development manager: sells more and pleases customers while costing less to develop and maintain User: easy to learn; efficient to use; helps get work done
17
Software Quality
The different qualities can conflict Increasing efficiency can reduce maintainability or reusability Increasing usability can reduce efficiency Setting objectives for quality is a key engineering activity You then design to meet the objectives Avoids over-engineering which wastes money Optimizing is also sometimes necessary E.g. obtain the highest possible reliability using a fixed budget
18
Exercise 2
For each of the following system, which quality attributes do you think would be the most important and the least important? 1. A web-based banking systems, enabling the user to do all aspects of banking on-line. 2. An air traffic control system. 3. A program that will enable users to view digital images or movies stored in all known formats. 4. A system to manage the work schedule of nurses that respects all the constraints and regulations in force at a particular hospital. 5. An application that allows you to purchase any item seen while watching TV
19
20
21
23
Benefit from reusing reliable software. Provide much of the same freedom to innovate found in green field development.
24
Requirements analysis
- Organizing the information
Requirements specification
- Writing detailed instructions about how the software should behave
25
28
29
Object oriented paradigm: Organizing procedural abstractions in the context of data abstractions
31
32
Account
credit debit
credit
debit
compute fees if checking then xxx if savings then xxx etc. CheckingAccount
compute interest compute fees
SavingsAccount
compute interest compute fees
33
34
Objects
Jane:
date of birth: 1955/02/02 address: 99 UML St. position: Manager
Greg:
date of birth: 1970/01/01 address: 75 Object Dr.
Transaction 487:
amount: 200.00 time: 2001/09/01 14:30
35
Classes
A class: Is a unit of abstraction in an object oriented (OO) program Represents similar objects Its instances Is a kind of software module Describes its instances structure (properties) Contains methods to implement their behaviour
36
Naming classes
Use capital letters E.g. BankAccount not bankAccount Use singular nouns Use the right level of generality E.g. Municipality, not City Make sure the name has only one meaning E.g. bus has several meanings
38
Instance Variables
Variables defined inside a class corresponding to data present in each instance Attributes Simple data E.g. name, dateOfBirth Associations Relationships to other important classes E.g. supervisor, coursesTaken
39
40
Class variables
A class variables value is shared by all instances of a class. Also called a static variable If one instance sets the value of a class variable, then all the other instances see the same changed value. What is the example usage of class variables? Class variables are useful for: Default or constant values (e.g. PI) Lookup tables and similar structures Caution: do not over-use class variables
41
42
43
Polymorphism
A property of object oriented software by which an abstract operation may be performed in different ways in different classes. Requires that there be multiple methods of the same name The choice of which one to execute depends on the object that is in a variable Reduces the need for programmers to code many ifelse or switch statements Example: calculateInterests
44
45
SavingsAccount
ChequingAccount
MortgageAccount
Inheritance The implicit possession by all subclasses of features defined in its superclasses
Features include variables and methods
46
OverdrawnAccount
SavingsAccount
ChequingAccount
highestChequeNumber withdrawUsingCheque calculateServiceCharge
MortgageAccount
collateralProperty collateralValue setCollateralValue
47
48
49
Shape
Point
Matrix
Shape2D
Shape3D
Ellipse
Polygon
Line
Plane
Circle
Quadrilateral
Rectangle
50
Shape2D
EllipticalShape
semiMajorAxis
Polygon
getBoundingRect getVertices
Circle
rotate changeScale getArea getPerimeterLength getBoundingRect getRadius
Ellipse
semiMinorAxis orientation rotate changeScale getArea getPerimeterLength getBoundingRect getOrientation getSemiMajorAxis getSemiMinorAxis getFocus1 getFocus2
SimplePolygon
orientation rotate getOrientation
ArbitraryPolygon
points addPoint removePoint rotate changeScale getArea getPerimeterLength getVertices
Rectangle
height width changeScale setHeight setWidth getArea getPerimeterLength getVertices getBoundingRect
RegularPolygon
numPoints radius changeNumPoints changeScale getArea getPerimeterLength getVertices
51
52
Overriding
A method would be inherited, but a subclass contains a new version instead For restriction E.g. scale(x,y) would not work in Circle For extension E.g. SavingsAccount might charge an extra fee following every debit For optimization E.g. The getPerimeterLength method in Circle is much simpler than the one in Ellipse
54
Immutable objects
Why? Useful because they are inherently thread-safe Simpler to understand and reason about Offer higher security than mutable objects However, performance of copying could be an issue Instance variables may only be set when an object is first created. None of the operations allow any changes to the instance variables E.g. a scale method could only create a new object, not modify an existing one
55
By default, fields and local variables are mutable. They can be made immutable using the final keyword.
int i = 42; i = 43; // OK final int j = 42; j = 43; // does not compile
56
4.
57
Dynamic binding
Occurs when decision about which method to run can only be made at run time Needed when: A variable is declared to have a superclass as its type, and There is more than one possible polymorphic method that could be run among the type of the variable and its subclasses
58
59
60
61
Java documentation
Looking up classes and methods is an essential skill Looking up unknown classes and methods will get you a long way towards understanding code Java documentation can be automatically generated by a program called Javadoc Documentation is generated from the code and its comments You should format your comments These may include embedded html
62
Overview of Java
The next few slides will remind you of several key Java features java.sun.com
63
64
Casting
Java is very strict about types If a variable is declared to have the type X, you can only invoke operations on it that are defined in class X or its superclasses Even though an instance of a subclass of X may be actually stored in the variable If you know an instance of a subclass is stored, then you can cast the variable to the subclass E.g. if I know a Vector contains instances of String, I can get the next element of its Iterator using: (String)iterator.next();
66
Exceptions
Anything that can go wrong should result in the raising of an Exception Exception is a class with many subclasses for specific things that can go wrong Use a try - catch block to trap an exception
try { // some code } catch (ArithmeticException e) { // code to handle division by zero }
67
Interfaces
Like abstract classes, but cannot have executable statements Define a set of operations that make sense in several classes Abstract Data Types A class can implement any number of interfaces It must have concrete methods for the operations You can declare the type of a variable to be an interface This is just like declaring the type to be an abstract class Important interfaces in Javas library include Runnable, Collection, Iterator, Comparable, Cloneable
68
69
Access control
Applies to methods and variables public Any class can access protected Only code in the package, or subclasses can access (blank) Only code in the package can access private Only code written in the class can access Inheritance still occurs!
70
71
72
Programming style
Comment extensively Comment whatever is non-obvious Do not comment the obvious Comments should be 25-50% of the code Organize class elements consistently Variables, constructors, public methods then private methods Be consistent regarding layout of code
73
Programming style
Avoid duplication of code Do not clone if possible Create a new method and call it Cloning results in two copies that may both have bugs - When one copy of the bug is fixed, the other may be forgotten
74
75
76
77
80
A vicious cycle
Developers tend not develop high quality reusable components, so there is often little to reuse To solve the problem, recognize that: This vicious cycle costs money Investment in reusable code is important Attention to quality of reusable components is essential So that potential reusers have confidence in them The quality of a software product is only as good as its lowest-quality reusable component Developing reusable components can often simplify design Developing reusable components improves reliability
81
82
83
Object-oriented frameworks
In the object oriented paradigm, a framework is composed of a library of classes. The API is defined by the set of all public methods of these classes. Some of the classes will normally be abstract
84
Examples of frameworks
A framework for payroll management A framework for frequent buyer clubs A framework for university registration A framework for e-commerce web sites A framework for controlling microwave ovens
85
Types of frameworks
A horizontal framework provides general application facilities that a large number of applications can use A vertical framework (application framework) is more complete but still needs some slots to be filled to adapt it to specific application needs
Application Services offered by the framework Application
86
87
90
Questions:
Is it possible for the client and server to be located on the same machine? Is it possible for the same program to be both client and server at the same time?
91
92
93
94
Activities of a server
1. Initializes itself 2. Starts listening for clients 3. Handles the following types of events originating from clients
1. 2. 3. accepts connections responds to messages handles client disconnection
Initializing For the server as a whole: Waiting
start listening stop listening
handle
95
Activities of a client
1. 2. 3. 4. Initializes itself Initiates a connection Sends messages Handles the following types of events originating from the server
responds to messages handles server disconnection
initialize
1. 2.
terminate
96
97
Heavy computation a
Light computation b
98
Communications protocols
The messages the client sends to the server form a language. The server has to be programmed to understand that language. The messages the server sends to the client also form a language. The client has to be programmed to understand that language. When a client and server are communicating, they are in effect having a conversation using these two languages The two languages and the rules of the conversation, taken together, are called the protocol
99
100
101
104
AbstractServer
listen stopListening close sendToAllClients getClientConnections clientConnected clientDisconnected clientException serverStarted serverStopped listeningException serverClosed handleMessageFromClient *
ConnectionToClient
sendToClient close setInfo getInfo
105
Using OCSF
Software engineers using OCSF never modify its three classes They: Create subclasses of the abstract classes in the framework Call public methods that are provided by the framework Override certain slot and hook methods (explicitly designed to be overridden)
106
107
109
Using AbstractClient
Create a subclass of AbstractClient Implement handleMessageFromServer slot method Write code that: Creates an instance of the new subclass Calls openConnection Sends messages to the server using the sendToServer service method Implement the connectionClosed callback Implement the connectionException callback
110
Internals of AbstractClient
Instance variables: A Socket which keeps all the information about the connection to the server Two streams, an ObjectOutputStream and an ObjectInputStream A Thread that runs using AbstractClients run method Two variables storing the host and port of the server
111
112
115
ChatIF
display
AbstractClient
AbstractServer
ChatClient ClientConsole
accept display main handleMessageFromServer handleMessageFromClientUI quit
EchoServer
handleMessageFromClient serverStarted serverStopped main
118
The server
EchoServer is a subclass of AbstractServer The main method creates a new instance and starts it It listens for clients and handles connections until the server is stopped The three callback methods just print out a message to the user handleMessageFromClient, serverStarted and serverStopped The slot method handleMessageFromClient calls sendToAllClients This echoes any messages
119
120
The client
When the client program starts, it creates instances of two classes: ChatClient A subclass of AbstractClient Overrides handleMessageFromServer
- This calls the display method of the user interface
Accepts user input by calling accept in its run method Sends all user input to the ChatClient by calling its handleMessageFromClientUI
- This, in turn, calls sendToServer
121
122
123
Compatibility not maintained Avoid obscure features Only re-use technology that others are also re-using
124
125
126
127