01_OO Overview.ppt

download 01_OO Overview.ppt

of 127

Transcript of 01_OO Overview.ppt

  • 7/27/2019 01_OO Overview.ppt

    1/127

    Module 1

    Object-Oriented Software Engineering

  • 7/27/2019 01_OO Overview.ppt

    2/127

    Section 1:

    Software and Software Engineering

  • 7/27/2019 01_OO Overview.ppt

    3/127

    3

    Questions to ponder

    How does software differ from other products? How doessoftware 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 willfollowing 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 softwareengineering activity?

  • 7/27/2019 01_OO Overview.ppt

    4/127

    4

    1.1 The Nature of Software...

    Software is intangible Hard to understand development effort

    Software is easy to reproduce

    Cost is in its development

    in other engineering products, manufacturing is the

    costly stage

    The industry is labor-intensive

    Hard to automate

  • 7/27/2019 01_OO Overview.ppt

    5/127

    5

    The Nature of Software ...

    Untrained people can hack something together Quality problems are hard to notice

    Software is easy to modify

    People make changes without fully understanding it

    Software does not wear out

    It deteriorates by having its design changed:

    erroneously, or

    in ways that were not anticipated, thus making itcomplex

  • 7/27/2019 01_OO Overview.ppt

    6/127

    6

    The Nature of Software

    Conclusions Much software has poor design and is getting worse

    Demand for software is high and rising

    We are in a perpetual software crisis

    We have to learn to engineer software

  • 7/27/2019 01_OO Overview.ppt

    7/127

    7

    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/27/2019 01_OO Overview.ppt

    8/127

    8

    Types of Software

    Differences among custom, generic and embeddedsoftware

    Custom Generic Embedded

    Number ofcopies in use low medium high

    Total processing power

    devoted to running this type

    of software

    low high medium

    Worldwide annual

    development effort

    high medium low

  • 7/27/2019 01_OO Overview.ppt

    9/127

    9

    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

  • 7/27/2019 01_OO Overview.ppt

    10/127

    10

    1.2 What is Software Engineering?...

    The process of solving customers problems by thesystematic development and evolution of large, high-quality software systems within cost, time and otherconstraints

    Solving customers problems

    This is the goal of software engineering

    Sometimes the solution is to buy, not build

    Adding unnecessary features does not help solve theproblem

    Software engineers must communicate effectively toidentify and understand the problem

  • 7/27/2019 01_OO Overview.ppt

    11/127

    11

    What is Software Engineering?

    Systematic development and evolution An engineering process involves applying well understood

    techniques in a organized and disciplined way

    Many well-accepted practices have been formally standardized

    e.g. by the IEEE or ISO

    Most development work is evolution

    Large, high quality software systems

    Software engineering techniques are needed because large systemscannot be completely understood by one person

    Teamwork and co-ordination are required Key challenge: Dividing up the work and ensuring that the parts of

    the system work properly together

    The end-product that is produced must be of sufficient quality

  • 7/27/2019 01_OO Overview.ppt

    12/127

    12

    What is Software Engineering?

    Cost, time and other constraints Finite resources

    The benefit must outweigh the cost

    Others are competing to do the job cheaper and faster

    Inaccurate estimates of cost and time have caused many

    project failures

  • 7/27/2019 01_OO Overview.ppt

    13/127

    13

    1.3 Software Engineering and the

    Engineering Profession

    The term Software Engineering was coined in 1968 People began to realize that the principles of engineering

    should be applied to software development

    Engineering is a licensed profession

    In order to protect the public

    Engineers design artifacts following well accepted

    practices which involve the application of science,

    mathematics and economics

    Ethical practice is also a key tenet of the profession

  • 7/27/2019 01_OO Overview.ppt

    14/127

    14

    1.4 Stakeholders in Software Engineering

    1. Users Those who use the software

    2. Customers

    Those who pay for the software

    3. Software developers

    4. Development Managers

    All four roles can be fulfilled by the same person

  • 7/27/2019 01_OO Overview.ppt

    15/127

    15

    Exercise 1

    How do you think each of the four types of stakeholderswould react in each of the following situations?

    You study a proposal for a new system that willcompletely automate the work of one individual in thecustomers company. You discover that the cost of

    developing the system would be far more than the costof continuing to do the work manually, so yourecommend against proceeding with the project.

    You implement a system according to the precisespecifications of a customer. However, when thesoftware is put to use, the users find it does not solvetheir problem.

  • 7/27/2019 01_OO Overview.ppt

    16/127

    16

    1.5 Software Quality...

    Usability

    Users can learn it and fast and get their job done easily

    Efficiency

    It doesnt waste resources such as CPU time and

    memoryReliability

    It does what it is required to do without failing

    Maintainability

    It can be easily changed

    Reusability

    Its parts can be used in other projects, so reprogramming

    is not needed

  • 7/27/2019 01_OO Overview.ppt

    17/127

    17

    Software Quality...

    QUALITY

    SOFTWARE

    Developer:

    easy to design;easy to maintain;

    easy to reuse its parts

    User:easy to learn;

    efficient to use;

    helps get work done

    Customer:

    solves problems atan acceptable cost in

    terms of money paid and

    resources used

    Development manager:

    sells more and

    pleases customers

    while costing less

    to develop and maintain

  • 7/27/2019 01_OO Overview.ppt

    18/127

    18

    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 engineeringactivity

    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 fixedbudget

  • 7/27/2019 01_OO Overview.ppt

    19/127

    19

    Exercise 2

    For each of the following system, which quality

    attributes do you think would be the most importantand the least important?

    1. A web-based banking systems, enabling the user to doall aspects of banking on-line.

    2. An air traffic control system.

    3. A program that will enable users to view digitalimages or movies stored in all known formats.

    4. A system to manage the work schedule of nurses thatrespects 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

  • 7/27/2019 01_OO Overview.ppt

    20/127

    20

    Internal Quality Criteria

    These: Characterize aspects of the design of the software

    Have an effect on the external quality attributes

    E.g.

    The amount of commenting of the code

    The complexity of the code

  • 7/27/2019 01_OO Overview.ppt

    21/127

    21

    Short Term Vs. Long Term Quality

    Short term: Does the software meet the customers immediate

    needs?

    Is it sufficiently efficient for the volume of data we have

    today?Long term:

    Maintainability

    Customers future needs

  • 7/27/2019 01_OO Overview.ppt

    22/127

    22

    1.6 Software Engineering Projects

    Most projects are evolutionary or maintenance projects,involving work on legacy systems

    Corrective projects: fixing defects

    Adaptive projects: changing the system in response to

    changes inOperating system

    Database

    Rules and regulations

    Enhancement projects: adding new features for users

    Reengineering or perfective projects: changing the

    system internally so it is more maintainable

  • 7/27/2019 01_OO Overview.ppt

    23/127

    23

    Software Engineering Projects

    Green field projects New development

    The minority of projects

  • 7/27/2019 01_OO Overview.ppt

    24/127

    24

    Software Engineering Projects

    Projects that involve building on aframework or a set ofexisting components.

    The framework is an application that is missing someimportant details.

    E.g. Specific rules of this organization.

    Such projects:

    Involve plugging together components that are:- Already developed.

    - Provide significant functionality.

    Benefit from reusing reliable software.

    Provide much of the same freedom to innovatefound in green field development.

  • 7/27/2019 01_OO Overview.ppt

    25/127

    25

    1.7 Activities Common to Software

    Projects...

    Requirements and specification Includes

    Domain analysis

    Defining the problem

    Requirements gathering

    - Obtaining input from as many sources as possible

    Requirements analysis

    - Organizing the information

    Requirements specification

    - Writing detailed instructions about how the software should

    behave

  • 7/27/2019 01_OO Overview.ppt

    26/127

    26

    Activities Common to Software Projects...

    Design Deciding how the requirements should be implemented,

    using the available technology

    Includes:

    Systems engineering: Deciding what should be inhardware and what in software

    Software architecture: Dividing the system intosubsystems and deciding how the subsystems willinteract

    Detailed design of the internals of a subsystemUser interface design

    Design of databases

  • 7/27/2019 01_OO Overview.ppt

    27/127

    27

    Activities Common to Software Projects

    Modeling Creating representations of the domain or the software

    Use case modeling

    Structural modeling

    Dynamic and behavioural modelingProgramming

    Quality assurance

    Reviews and inspections

    Testing Can be classified into Validation & Verification

    Deployment

    Managing the process

  • 7/27/2019 01_OO Overview.ppt

    28/127

    28

    1.8 The Four Themes

    1. Understanding the customer and the user2. Basing development on solid principles and reusable

    technology

    3. Object orientation

    4. Visual modeling using UML

  • 7/27/2019 01_OO Overview.ppt

    29/127

    29

    1.9 Difficulties and Risks in Software

    Engineering

    Complexity and large numbers of details Uncertainty about technology

    Uncertainty about requirements

    Uncertainty about software engineering skills

    Constant change

    Deterioration of software design

    Political risks

    Please find solutions to each of the above risks.

  • 7/27/2019 01_OO Overview.ppt

    30/127

    Section 2:

    Introduction of Object Orientation

  • 7/27/2019 01_OO Overview.ppt

    31/127

    31

    What is Object Orientation?

    Procedural paradigm:

    Software is organized around the notion ofprocedures

    Procedural abstraction

    Works as long as the data is simple

    Adding data abstractions

    Groups together the pieces of data that describesome entity

    Helps reduce the systems complexity.- Such asRecords and structures

    Object oriented paradigm:

    Organizing procedural abstractions in the context of dataabstractions

  • 7/27/2019 01_OO Overview.ppt

    32/127

    32

    Object Oriented paradigm

    An approach to the solution of problems in which allcomputations are performed in the context of objects.

    The objects are instances of classes, which:

    are data abstractions

    contain procedural abstractions that operation on the

    objects

    A running program can be seen as a collection of objects

    collaborating to perform a given task

  • 7/27/2019 01_OO Overview.ppt

    33/127

    33

    A View of the Two paradigms

    main

    perform transaction

    compute fees

    if checkingthen xxx

    if savingsthen xxx

    etc.

    compute interest

    if checkingthen xxx

    if savingsthen xxx

    etc.

    debitcredit

    Account

    credit

    debit

    SavingsAccount

    compute interest

    compute fees

    CheckingAccount

    compute interest

    compute fees

  • 7/27/2019 01_OO Overview.ppt

    34/127

    34

    Classes and Objects

    Object A chunk of structured data in a running software system

    Hasproperties

    Represent its state

    Has behaviour

    How it acts and reacts

    May simulate the behaviour of an object in the real

    world

  • 7/27/2019 01_OO Overview.ppt

    35/127

    35

    Objects

    Margaret:

    date of birth: 1980/03/03

    position: Teller

    Transaction 487:

    amount: 200.00

    time: 2001/09/01 14:30

    Greg:

    date of birth: 1970/01/01

    address: 75 Object Dr.

    Mortgage Account 29865:

    balance: 198760.00

    opened: 2000/08/12

    property: 75 Object Dr.

    Instant Teller 876:

    location: Java Valley Cafe

    Savings Account 12876:

    balance: 1976.32

    opened: 1997/03/03

    Jane:date of birth: 1955/02/02

    position: Manager

    address: 99 UML St.

    address: 150 C++ Rd.

  • 7/27/2019 01_OO Overview.ppt

    36/127

    36

    Classes

    A class: Is a unit of abstraction in an object oriented (OO)

    program

    Represents similar objectsIts instances

    Is a kind of software module

    Describes its instances structure (properties)

    Contains methods to implement their behaviour

  • 7/27/2019 01_OO Overview.ppt

    37/127

    37

    Is Something a Class or an Instance? Something should be a class if it could have instances

    Something should be an instance if it is clearly a single member ofthe set defined by a class

    Film

    Class; instances are individual films.

    Reel of Film:

    Class; instances are physical reelsFilm reel with serial number SW19876

    Instance ofReelOfFilm

    Science Fiction

    Subclass/Instance of the class Genre.

    Science Fiction Film

    Class; instances include Star Wars

    Showing of Star Wars in the Phoenix Cinema at 7 p.m.:

    Instance ofShowingOfFilm

  • 7/27/2019 01_OO Overview.ppt

    38/127

    38

    Naming classes

    Use capital lettersE.g. BankAccount not bankAccount

    Use singularnouns

    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

  • 7/27/2019 01_OO Overview.ppt

    39/127

    39

    Instance Variables

    Variables defined inside a class corresponding to datapresent in each instance

    Attributes

    Simple dataE.g. name, dateOfBirth

    Associations

    Relationships to other important classes

    E.g. supervisor, coursesTaken

  • 7/27/2019 01_OO Overview.ppt

    40/127

    40

    Variables vs. Objects

    A variableRefers to an object

    May refer to different objects at different points in time

    An object can be referred to by several different

    variables at the same time

    Type of a variable

    Determines what classes of objects it may contain

  • 7/27/2019 01_OO Overview.ppt

    41/127

    41

    Class variables

    Aclass variables value issharedby 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

  • 7/27/2019 01_OO Overview.ppt

    42/127

    42

    Methods, Operations and Polymorphism

    Operation A higher-level procedural abstraction that specifies a

    type of behaviour

    Independent of any code which implements that

    behaviourE.g., calculating area (in general)

  • 7/27/2019 01_OO Overview.ppt

    43/127

    43

    Methods, Operations and Polymorphism

    Method A procedural abstraction used to implement the

    behaviour of a class.

    Several different classes can have methods with the

    same nameThey implement the same abstract operation in ways

    suitable to each class

    E.g, calculating area in a rectangle is done

    differently from in a circle

  • 7/27/2019 01_OO Overview.ppt

    44/127

    44

    Polymorphism

    A property of object oriented software by which anabstract 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 if-

    else or switch statements Example: calculateInterests

    Organizing Classes into Inheritance

  • 7/27/2019 01_OO Overview.ppt

    45/127

    45

    Organizing Classes into Inheritance

    Hierarchies

    Superclasses Contain features common to a set of subclasses

    Inheritance hierarchies

    Show the relationships among superclasses andsubclasses

    A triangle shows a generalization

    Inheritance The implicitpossession by all subclasses of features

    defined in its superclasses

  • 7/27/2019 01_OO Overview.ppt

    46/127

    46

    An Example Inheritance Hierarchy

    Account

    MortgageAccountSavingsAccount ChequingAccount

    Inheritance

    The implicitpossession by all subclasses of featuresdefined in its superclasses

    Features include variables and methods

    M k S ll I h it d F t M k

  • 7/27/2019 01_OO Overview.ppt

    47/127

    47

    Make Sure all Inherited Features Make

    Sense in Subclasses

    Account

    balance

    opened

    creditOrOverdraftLimit

    credit

    debitcalculateInterest

    MortgageAccount

    collateralProperty

    collateralValue

    setCollateralValue

    ChequingAccount

    highestChequeNumber

    withdrawUsingCheque

    calculateServiceCharge

    SavingsAccount

    OverdrawnAccount

  • 7/27/2019 01_OO Overview.ppt

    48/127

    48

    The Isa Rule

    Always check generalizations to ensure they obey the isarule

    A checking account is an account

    A village is a municipality

    Should Province be a subclass of Country?

    No, it violates the isa rule

    A province is a country is invalid!

  • 7/27/2019 01_OO Overview.ppt

    49/127

    49

    Generalization: Points to Check

    Ambiguous names for superclasses or subclasses Example:Bus

    A subclass must retain its distinctiveness throughout its

    life Example: OverdrawnAccount

    All the inherited features must make sense in each

    subclass Example: credit(), debit()

    A possible inheritance hierarchy of

  • 7/27/2019 01_OO Overview.ppt

    50/127

    50

    A possible inheritance hierarchy of

    mathematical objectsCircle, Point, Rectangle, Matrix, Ellipse, Line, Plane

    Rectangle

    QuadrilateralCircle

    Ellipse Polygon PlaneLine

    Shape3DShape2D

    MatrixShape Point

    MathematicalObject

    Shape2D

  • 7/27/2019 01_OO Overview.ppt

    51/127

    51

    Inheritance,

    Polymorphism and

    Variables

    RegularPolygon

    numPoints

    radius

    changeNumPoints

    changeScale

    getArea

    getPerimeterLength

    getVertices

    Rectangle

    height

    width

    setHeight

    setWidth

    changeScale

    getArea

    getPerimeterLength

    getVertices

    getBoundingRect

    ArbitraryPolygon

    points

    addPoint

    removePoint

    rotate

    changeScale

    getArea

    getPerimeterLength

    getVertices

    SimplePolygon

    orientation

    rotate

    rotate

    translate

    changeScale

    getArea

    getPerimeterLength

    getCenter

    getBoundingRect

    Ellipse

    getSemiMajorAxis

    getSemiMinorAxis

    rotate

    getArea

    getPerimeterLength

    getOrientation

    getBoundingRect

    Circle

    rotate

    getArea

    getPerimeterLength

    getBoundingRect

    Polygon

    getVertices

    getBoundingRect

    EllipticalShape

    semiMajorAxis

    semiMinorAxis

    changeScale

    changeScale

    getRadius

    getFocus1

    getFocus2

    orientation

    getOrientation

    center

  • 7/27/2019 01_OO Overview.ppt

    52/127

    52

    Some Operations in the Shape Example

    Original objects(showing bounding rectangle)

    Rotated objects

    (showing bounding rectangle)

    Translated objects

    (showing original)

    Scaled objects

    (50%)

    Scaled objects

    (150%)

  • 7/27/2019 01_OO Overview.ppt

    53/127

    53

    Abstract Classes and Methods

    An operation should be declared to exist at the highest

    class in the hierarchy where it makes sense The operation may be abstract(lacking implementation)

    at that level

    If so, the class also must be abstract

    No instances can be createdThe opposite of an abstract class is a concrete class

    If a superclass has an abstract operation then itssubclasses at some level must have a concrete methodfor the operation. Can Leaf classes be abstract?

    Leaf classes must have or inherit concrete methodsfor all operations

    Leaf classes must be concrete

    Can non-leaf classes be concrete?

  • 7/27/2019 01_OO Overview.ppt

    54/127

    54

    Overriding

    A method would be inherited, but a subclass contains anew version instead

    For restriction

    E.g. scale(x,y) would not work in Circle

    For extensionE.g. SavingsAccount might charge an extra fee

    following every debit

    For optimization

    E.g. The getPerimeterLength method inCircle is much simpler than the one in Ellipse

  • 7/27/2019 01_OO Overview.ppt

    55/127

    55

    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

  • 7/27/2019 01_OO Overview.ppt

    56/127

    56

    Immutable objects: Example

    Java String classString s = "ABC";

    s.toLowerCase(); // doesnt change String s

    To make the String s contain the data "abc,

    s = s.toLowerCase();

    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

    How a decision is made about which

  • 7/27/2019 01_OO Overview.ppt

    57/127

    57

    How a decision is made about which

    method to run

    1. If there is a concrete method for the operation in

    the current class, run that method.

    2. Otherwise, check in the immediate superclass to

    see if there is a method there; if so, run it.

    3. Repeat step 2, looking in successively higher

    superclasses until a concrete method is found and

    run.

    4. If no method is found, then there is an error

    In Java and C++ the program would not have

    compiled

  • 7/27/2019 01_OO Overview.ppt

    58/127

    58

    Dynamic binding

    Occurs when decision about which method to run canonly be made atrun time

    Needed when:

    A variable is declared to have a superclass as its

    type, andThere is more than one possible polymorphic

    method that could be run among the type of the

    variable and its subclasses

  • 7/27/2019 01_OO Overview.ppt

    59/127

    59

    Concepts that Define Object Orientation

    Necessary for a system or language to be OO

    Identity

    Each object is distinct from each other object, and can bereferred to

    Two objects are distinct even if they have the same data

    Classes

    The code is organized using classes, each of which describes aset of objects

    Inheritance

    The mechanism where features in a hierarchy inherit fromsuperclasses to subclasses

    Polymorphism

    The mechanism by which several methods can have the samename and implement the same abstract operation.

  • 7/27/2019 01_OO Overview.ppt

    60/127

    60

    Other Key Concepts

    Abstraction Object -> something in the world

    Class -> objects

    Superclass -> subclasses

    Operation -> methods

    Attributes and associations -> instance variables

    Modularity

    Code can be constructed entirely of classes

    Encapsulation

    Details can be hidden in classes This gives rise to information hiding:

    Programmers do not need to know all the details of a class

  • 7/27/2019 01_OO Overview.ppt

    61/127

    61

    The Basics of Java

    History

    The first object oriented programming language was Simula-67designed to allow programmers to write simulation programs

    In the early 1980s, Smalltalk was developed at Xerox PARC

    New syntax, large open-source library of reusable code,bytecode, platform independence, garbage collection.

    late 1980s, C++ was developed by B. Stroustrup,Recognized the advantages of OO but also recognized thatthere were tremendous numbers of C programmers

    In 1991, engineers at Sun Microsystems started a project to design alanguage that could be used in consumer smart devices: Oak

    When the Internet gained popularity, Sun saw an opportunity toexploit the technology.

    The new language, renamed Java, was formally presented in1995 at the SunWorld 95 conference.

  • 7/27/2019 01_OO Overview.ppt

    62/127

    62

    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

  • 7/27/2019 01_OO Overview.ppt

    63/127

    63

    Overview of Java

    The next few slides will remind you of several key Javafeatures

    java.sun.com

  • 7/27/2019 01_OO Overview.ppt

    64/127

    64

    Characters and Strings

    Character is a class representing Unicode characters More than a byte each

    Represent any world language

    char is a primitive data type containing a Unicodecharacter

    String is a class containing collections of characters

    + is the operator used to concatenate strings

  • 7/27/2019 01_OO Overview.ppt

    65/127

    65

    Arrays and Collections

    Arrays are of fixed size and lack methods to manipulate them

    Vector is the most widely used class to hold a collection of other

    objects

    More powerful than arrays, but less efficient

    Iterators are used to access members ofVectors

    Enumerations were formally used, but were more complex

    v = new Vector();

    Iterator i = v.iterator();

    while(i.hasNext())

    {

    aMethod(v.next());

    }

  • 7/27/2019 01_OO Overview.ppt

    66/127

    66

    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 beactually stored in the variable

    If you know an instance of a subclass is stored, then you

    can castthe variable to the subclass

    E.g. if I know a Vector contains instances ofString, I can get the next element of its

    Iterator using:

    (String)iterator.next();

  • 7/27/2019 01_OO Overview.ppt

    67/127

    67

    Exceptions

    Anything that can go wrong should result in the raisingof an Exception

    Exception is a class with many subclasses for

    specific things that can go wrong

    Use a try - catch block to trap an exceptiontry

    {

    // some code

    }

    catch (ArithmeticException e){

    // code to handle division by zero

    }

    I t f

  • 7/27/2019 01_OO Overview.ppt

    68/127

    68

    Interfaces

    Like abstract classes, but cannot have executablestatements

    Define a set of operations that make sense in severalclasses

    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

    P k d i ti

  • 7/27/2019 01_OO Overview.ppt

    69/127

    69

    Packages and importing

    A package combines related classes into subsystems All the classes in a particular directory

    Classes in different packages can have the same name

    Although not recommended

    Importing a package is done as follows:

    import finance.banking.accounts.*;

    A t l

  • 7/27/2019 01_OO Overview.ppt

    70/127

    70

    Access control

    Applies to methods and variablespublic

    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!

    Th d d

  • 7/27/2019 01_OO Overview.ppt

    71/127

    71

    Threads and concurrency

    Thread: Sequence of executing statements that can be running

    concurrently with other threads

    To create a thread in Java:

    1. Create a class implementing Runnable or extendingThread

    2. Implement the run method as a loop that does

    something for a period of time

    3. Create an instance of this class 4. Invoke the start operation, which calls run

    P i St l G id li

  • 7/27/2019 01_OO Overview.ppt

    72/127

    72

    Programming Style Guidelines

    Remember that programs are for people to read Always choose the simpler alternative

    Reject clever code that is hard to understand

    Shorter code is not necessarily better

    Choose good names

    Make them highly descriptive

    Do not worry about using long names

    P i t l

  • 7/27/2019 01_OO Overview.ppt

    73/127

    73

    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

    P i t l

  • 7/27/2019 01_OO Overview.ppt

    74/127

    74

    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

    Programming st le

  • 7/27/2019 01_OO Overview.ppt

    75/127

    75

    Programming style ...

    Adhere to good object oriented principles E.g. the isa rule

    Preferprivate as opposed topublic

    Do not mix user interface code with non-user interface

    code

    Interact with the user in separate classes

    This makes non-UI classes more reusable

    M th lit d l it f

  • 7/27/2019 01_OO Overview.ppt

    76/127

    76

    Measure the quality and complexity of a program

    Lines of code

    Uncommented lines of code

    Percentage of lines with comments

    Number of classes

    Number of methods per class

    Number of public methods per class

    Number of public instance variables per class

    Number of parameters per method

    Number of lines of code per method

    Depth of inheritance hierarchyNumber of overridden methods per class

    Difficulties and Risks in Object-Oriented

  • 7/27/2019 01_OO Overview.ppt

    77/127

    77

    j

    Programming

    Language evolution and deprecated features: Java can be less efficient than other languages

    VM-based

    Dynamic binding

    Efficiency can be a concern in some object oriented

    systems

    Java is evolving, so some features are deprecated at

    every release But the same thing is true of most other languages

  • 7/27/2019 01_OO Overview.ppt

    78/127

    Basing Software Development on

    Reusable Technology

    Building on the Experience of Others

  • 7/27/2019 01_OO Overview.ppt

    79/127

    79

    Building on the Experience of Others

    Software engineers should avoid re-developing softwarealready developed

    Types of reuse:

    Reuse of expertise Reuse of standard designs and algorithms

    Reuse of libraries of classes or procedures

    Reuse of powerful commands built into languages and

    operating systems Reuse of frameworks

    Reuse of complete applications

    Reusability and Reuse in SE

  • 7/27/2019 01_OO Overview.ppt

    80/127

    80

    Reusability and Reuse in SE

    Reuse and design for reusability should be part of theculture of software development organizations

    But there are problems to overcome:

    Why take the extra time needed to develop somethingthat will benefit otherprojects/customers?

    Management may only reward the efforts of people who

    create the visible final products.

    Reusable software are often created in a hurry andwithout enough attention to quality.

    A vicious cycle

  • 7/27/2019 01_OO Overview.ppt

    81/127

    81

    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

    Investmentin 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

    Frameworks: Reusable Subsystems

  • 7/27/2019 01_OO Overview.ppt

    82/127

    82

    Frameworks: Reusable Subsystems

    A framework is reusable software that implements ageneric solution to a generalized problem.

    It provides common facilities applicable to different

    application programs.

    Principle: Applications that do different, but related,

    things tend to have quite similar designs

    Frameworks to promote reuse

  • 7/27/2019 01_OO Overview.ppt

    83/127

    83

    Frameworks to promote reuse

    A framework is intrinsically incomplete

    Certain classes or methods are used by the framework,but are missing (slots)

    Some functionality is optional

    Allowance is made for developer to provide it(hooks)

    Developers use the services that the framework provides

    Taken together the services are called theApplication Program Interface (API)

    Object-oriented frameworks

  • 7/27/2019 01_OO Overview.ppt

    84/127

    84

    Object-oriented frameworks

    In the object oriented paradigm, a framework iscomposed of a library of classes.

    The API is defined by the set of all public methods ofthese classes.

    Some of the classes will normally be abstract

    Examples of frameworks

  • 7/27/2019 01_OO Overview.ppt

    85/127

    85

    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

    Types of frameworks

  • 7/27/2019 01_OO Overview.ppt

    86/127

    86

    Types of frameworks

    A horizontal framework provides general application facilities

    that a large number of applications can useA vertical framework (application framework) is more

    complete but still needs some slots to be filled to adapt it to

    specific application needs

    Application Application

    Horizontal framework

    Vertical

    framework

    Code to be provided to adapt the framework to the

    needs of the application

    Services offered

    by the framework

    Exercise: Library Management System

  • 7/27/2019 01_OO Overview.ppt

    87/127

    87

    y g y

    Imagine you are designing a framework that different

    libraries (of books, not code) would be able to adapt to meettheir needs. What kind of facilities would you want to provide

    if you were designing such a framework? In what ways do

    libraries differ such that they would need to use a framework

    rather than a complete application?

    The Client-Server Architecture

  • 7/27/2019 01_OO Overview.ppt

    88/127

    88

    The Client-Server Architecture

    Adistributed system is a system in which:

    computations are performed by separate programs normally running on separate pieces of hardware

    that co-operate to perform the task of the system.

    Server:

    A program that provides a service for other programsthat connect to it using a communication channel

    Client

    A program that accesses a server (or several servers) to

    obtain services A server may be accessed by many clientssimultaneously

    Sequence of activities in a client-server

  • 7/27/2019 01_OO Overview.ppt

    89/127

    89

    system1. The server starts running

    2. The server waits for clients to connect. (listening)

    3. Clients start running and perform operations

    Some operations involve requests to the server

    1. When a client attempts to connect, the server accepts

    the connection (if it is willing)2. The server waits for messages to arrive from

    connected clients

    3. When a message from a client arrives, the server

    takes some action in response, then resumes waiting4. Clients and servers continue functioning in this

    manner until they decide to shut down or disconnect

    A server program communicating with two

  • 7/27/2019 01_OO Overview.ppt

    90/127

    90

    client programs

    Application Application

    Horizontal framework

    Verticalframework

    Code to be provided to adapt the framework to the

    needs of the application

    Services offeredby the framework

    Questions:

  • 7/27/2019 01_OO Overview.ppt

    91/127

    91

    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 andserver at the same time?

    Alternatives to the client server architecture

  • 7/27/2019 01_OO Overview.ppt

    92/127

    92

    Alternatives to the client server architecture

    Have a

    single programon one computer that doeseverything

    Have no communication

    Each computer performs the work separately

    Have some mechanism other than client-server

    communication for exchanging information

    E.g. one program writes to a database; the otherreads from the database

    Advantages of client-server systems

  • 7/27/2019 01_OO Overview.ppt

    93/127

    93

    Advantages of client server systems

    The work can be distributedamong different machines

    The clients can access the servers functionality from adistance

    The client and server can be designed separately

    They can both be simpler

    All the data can be kept centrally at the server Conversely, data can be distributedamong many

    different geographically-distributed clients or servers

    The server can be accessed simultaneously by many

    clients Competing clients can be written to communicate withthe same server, and vice-versa

    Example of client-server systems

  • 7/27/2019 01_OO Overview.ppt

    94/127

    94

    Example of client server systems

    The World Wide Web

    Email

    Network File System

    Transaction Processing System

    Remote Display System Communication System

    Database System

    Please identify the clients and servers in each application.

    Activities of a server

  • 7/27/2019 01_OO Overview.ppt

    95/127

    95

    Activities of a server

    1. Initializes itself2. Starts listening for clients

    3. Handles the following types of

    events originating from clients

    1. accepts connections2. responds to messages

    3. handles client disconnection

    4. May stop listening

    5. Must cleanly terminate

    Waiting for Connections

    Handling a Connection

    do: react to messages

    handledisconnection

    Waiting

    start listening stop listening

    For each connection:

    For the server as a whole:

    accept connection

    Initializing

    terminate

    Activities of a client

  • 7/27/2019 01_OO Overview.ppt

    96/127

    96

    Activities of a client

    1. Initializes itself

    2. Initiates a connection

    3. Sends messages

    4. Handles the following

    types of eventsoriginating from the

    server

    1. responds to messages

    2. handles server

    disconnection

    5. Must cleanly terminate

    initiate a connectionto a server

    respond to eventstriggered by the server

    do: respond to messagesand

    handle server

    disconnection

    interact with theuser,sending messagesto the serveras necessary

    terminate

    initialize

    Threads in a client-server system

  • 7/27/2019 01_OO Overview.ppt

    97/127

    97

    Threads in a client server system

    kill client

    disconnect

    reply to message

    create

    reply to message

    connect

    displaydisconnect

    display reply

    display reply

    create

    wait forconnections

    interactwith user

    wait for serverevents

    wait formessages:

    client A

    interact withserver user

    wait formessages:

    client B

    send message

    send message

    Client Side (Client A) Server Side

    Thin- versus fat-client systems

  • 7/27/2019 01_OO Overview.ppt

    98/127

    98

    Thin versus fat client systems

    Thin-client system (a)

    Client is made as small as possible Most of the work is done in the server.

    Client easy to download over the network

    Fat-client system (b)

    As much work as possible is delegated to the clients.

    Server can handle more clients

    Light computation

    Light computation

    Heavy computation

    Heavy computation

    results

    for display

    simple

    commandsrequests

    for services

    results

    of requests

    a b

    Communications protocols

  • 7/27/2019 01_OO Overview.ppt

    99/127

    99

    Communications protocols

    The messages the client sends to the server form alanguage.

    The server has to be programmed to understand thatlanguage.

    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 theprotocol

    Tasks to perform to develop

    li t li ti

  • 7/27/2019 01_OO Overview.ppt

    100/127

    100

    client-server applications

    1. Design the primary work to be performed by both client

    and server

    2. Design how the work will be distributed

    3. Design the details of the set of messages that will be sent

    4. Design the mechanism for1. Initializing

    2. Handling connections

    3. Sending and receiving messages

    4. Terminating

    Technology Needed to Build Client-Server

    S t

  • 7/27/2019 01_OO Overview.ppt

    101/127

    101

    Systems

    Internet Protocol (IP)

    Route messages from one computer to another

    Long messages are normally split up into small pieces

    Transmission Control Protocol (TCP)

    Handles connections between two computers

    Computers can then exchange many IP messages over a connection Assures that the messages have been satisfactorily received

    A host has anIP address and ahost name

    Several servers can run on the same host.

    Each server is identified by a port number (0 to 65535). To initiate communication with a server, a client must know both

    the host name and the port number

    Establishing a connection in Java

  • 7/27/2019 01_OO Overview.ppt

    102/127

    102

    g

    The java.net package

    Permits the creation of a TCP/IP connection between

    two applications

    Before a connection can be established, the server muststart listening to one of the ports:

    ServerSocket serverSocket = new

    ServerSocket(port);

    Socket clientSocket = serverSocket.accept();

    For a client to connect to a server:

    Socket clientSocket= new Socket(host, port);

    Exchanging information in Java

  • 7/27/2019 01_OO Overview.ppt

    103/127

    103

    g g

    Each program uses an instance of

    InputStream to receive messages from the other

    program

    OutputStream to send messages to the other

    program

    These are found in package java.io

    output = new

    OutputStream(clientSocket.getOutputStream());

    input = new

    InputStream(clientSocket.getInputStream());

    Sending and receiving messages

  • 7/27/2019 01_OO Overview.ppt

    104/127

    104

    g g g

    without any filters

    output.write(msg);

    msg = input.read();

    or using DataInputStream/DataOutputStreamfilters

    output.writeDouble(msg);

    msg = input.readDouble();

    or using ObjectInputStream/ObjectOutputStreamfilters

    output.writeObject(msg);msg = input.readObject();

    The Object Client-Server Framework (OCSF)

  • 7/27/2019 01_OO Overview.ppt

    105/127

    105

    j ( )

    AbstractClient

    openConnection

    closeConnection

    sendToServer

    connectionEstablished

    connectionClosed

    handleMessageFromServer

    connectionException

    ******

    ConnectionToClient

    sendToClient

    close

    setInfo

    getInfo

    AbstractServer

    listen

    stopListening

    close

    clientConnected

    clientDisconnected

    serverStarted

    handleMessageFromClient

    serverStopped

    sendToAllClients

    getClientConnections

    serverClosed

    clientException

    listeningException

    Using OCSF

  • 7/27/2019 01_OO Overview.ppt

    106/127

    106

    g

    Software engineers using OCSFnever modify its three

    classes

    They:

    Create subclasses of the abstract classes in theframework

    Call public methods that are provided by the framework

    Override certain slot and hook methods (explicitly

    designed to be overridden)

    The Client Side

  • 7/27/2019 01_OO Overview.ppt

    107/127

    107

    Consists of a single class: AbstractClient

    Mustbe subclassed

    Any subclass must provide an implementation for

    handleMessageFromServer

    - Takes appropriate action when a message is received from a

    server

    Implements the Runnable interface

    Has a runmethod which

    - Contains a loop that executes for the lifetime of the thread

    The public interface ofAbstractClient

  • 7/27/2019 01_OO Overview.ppt

    108/127

    108

    p

    Controlling methods:

    openConnection

    closeConnection

    sendToServer

    Accessing methods:

    isConnected

    getHost

    setHost

    getPort

    setPort

    getInetAddress

    The callback methods ofAbstractClient

  • 7/27/2019 01_OO Overview.ppt

    109/127

    109

    Methods thatmay be overridden:

    connectionEstablished

    connectionClosed

    Method thatmust be overridden:handleMessageFromServer

    Using AbstractClient

  • 7/27/2019 01_OO Overview.ppt

    110/127

    110

    g

    Create a subclass ofAbstractClient

    Implement handleMessageFromServer slot

    method

    Write code that:

    Creates an instance of the new subclassCalls openConnection

    Sends messages to the server using the

    sendToServer service method

    Implement the connectionClosedcallback Implement the connectionException callback

    Internals ofAbstractClient

  • 7/27/2019 01_OO Overview.ppt

    111/127

    111

    Instance variables:

    A Socket which keeps all the information about the

    connection to the server

    Two streams, an ObjectOutputStreamand an

    ObjectInputStream

    A Threadthat runs usingAbstractClients run

    method

    Two variables storing the hostandportof the server

    The Server Side

  • 7/27/2019 01_OO Overview.ppt

    112/127

    112

    Two classes:

    One for the thread which listens for new connections

    (AbstractServer)

    One for the threads that handle the connections to clients(ConnectionToClient)

    The public interface ofAbstractServer

  • 7/27/2019 01_OO Overview.ppt

    113/127

    113

    Controlling methods:

    listen

    stopListening

    close

    sendToAllClients

    Accessing methods:

    isListening

    getClientConnections

    getPort

    setPort

    setBacklog

    The callback methods ofAbstractServer

  • 7/27/2019 01_OO Overview.ppt

    114/127

    114

    Methods thatmay be overridden:

    serverStarted

    clientConnected

    clientDisconnected

    clientExceptionserverStopped

    listeningException

    serverClosed

    Method thatmust be overridden:

    handleMessageFromClient

    The public interface of

    ConnectionToClient

  • 7/27/2019 01_OO Overview.ppt

    115/127

    115

    ConnectionToClient

    Controlling methods:

    sendToClient

    close

    Accessing methods:

    getInetAddresssetInfo

    getInfo

    Using AbstractServer and

    ConnectionToClient

  • 7/27/2019 01_OO Overview.ppt

    116/127

    116

    ConnectionToClient

    Create a subclass ofAbstractServer

    Implement the slot methodhandleMessageFromClient

    Write code that:

    Creates an instance of the subclass of

    AbstractClientCalls the listen method

    Sends messages to clients, using:- the getClientConnections and sendToClient

    service methods

    - orsendToAllClients

    Implement one or more of the other callback methods

    Internals ofAbstractServer and

    ConnectionToClient

  • 7/27/2019 01_OO Overview.ppt

    117/127

    117

    ConnectionToClient

    The setInfo and getInfo methods make use of a

    Java class called HashMap

    Many methods in the server side are synchronized

    The collection of instances of

    ConnectionToClient is stored using a special

    class called ThreadGroup

    The server must pause from listening every 500ms to see

    if the stopListening method has been called

    if not, then it resumes listening immediately

    An Instant Messaging Application:

    SimpleChat

  • 7/27/2019 01_OO Overview.ppt

    118/127

    118

    SimpleChat

    EchoServer

    handleMessageFromClientserverStarted

    serverStopped

    main

    ChatIF

    display

    ChatClient

    handleMessageFromServerhandleMessageFromClientUI

    quit

    AbstractServer

    ClientConsole

    accept

    display

    main

    AbstractClient

    ClientConsolecan eventually be replaced by ClientGUI

    The server

  • 7/27/2019 01_OO Overview.ppt

    119/127

    119

    EchoServer is a subclass ofAbstractServer

    Themain method creates a new instance and starts it

    It listens for clients and handles connections until

    the server is stopped

    The three callbackmethods just print out a message tothe user

    handleMessageFromClient,

    serverStartedand serverStopped

    Theslotmethod handleMessageFromClientcalls sendToAllClients

    This echoes any messages

    Key code in EchoServer

  • 7/27/2019 01_OO Overview.ppt

    120/127

    120

    public void handleMessageFromClient

    (Object msg, ConnectionToClient client)

    {

    System.out.println(

    "Message received: "+ msg + " from " + client);

    this.sendToAllClients(msg);

    }

    The client

  • 7/27/2019 01_OO Overview.ppt

    121/127

    121

    When the client program starts, it creates instances of two classes:

    ChatClient

    A subclass ofAbstractClient

    Overrides handleMessageFromServer

    - This calls the display method of the user interface

    ClientConsole

    User interface class that implements the interface ChatIF- Hence implements display which outputs to the console

    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

    Key code in ChatClient

  • 7/27/2019 01_OO Overview.ppt

    122/127

    122

    public void handleMessageFromClientUI(

    String message)

    {

    try

    {

    sendToServer(message);

    }

    catch(IOException e){

    clientUI.display (

    "Could not send message. " +

    "Terminating client.");

    quit();}

    }

    Key code in ChatClient - continued

  • 7/27/2019 01_OO Overview.ppt

    123/127

    123

    public void handleMessageFromServer(Object msg)

    {

    clientUI.display(msg.toString());

    }

    Risks when reusing technology

  • 7/27/2019 01_OO Overview.ppt

    124/127

    124

    Poor quality reusable components

    Ensure that the developers of the reusable

    technology:

    - follow good software engineering practices

    - are willing to provide active support

    Compatibility not maintained

    Avoid obscure features

    Only re-use technology that others are also re-using

    Risks when developing reusable technology

  • 7/27/2019 01_OO Overview.ppt

    125/127

    125

    Investment uncertaintyPlan the development of the reusable technology, just

    as if it was a product for a client

    The not invented here syndromeBuild confidence in the reusable technology by:

    - Guaranteeing support

    - Ensuring it is of high quality

    - Responding to the needs of its users

    Risk when developing reusable technology

    continued

  • 7/27/2019 01_OO Overview.ppt

    126/127

    126

    continued

    Competition

    The reusable technology must be as useful and as

    high quality as possible

    Divergence (tendency of various groups to changetechnology in different ways)

    Design it to be general enough, test it and review it

    in advance

    Risks when adopting a client-server

    approach

  • 7/27/2019 01_OO Overview.ppt

    127/127

    approach

    Security

    Security is a big problem with no perfect solutions:

    consider the use of encryption, firewalls, ...

    Need for adaptive maintenance

    Ensure that all software is forward and backward

    compatible with other versions of clients and servers