Object Oriented Programming. Object Oriented Programming. Object Oriented Programming Keep in mind. Object Oriented Programming Key Ideas

Object Oriented Programming Introduction Object Oriented Programming Introduction to Computer Science II Definition Christopher M. Bourke cbourke@cs...
Author: Wilfrid Dixon
55 downloads 3 Views 677KB Size
Object Oriented Programming Introduction

Object Oriented Programming Introduction to Computer Science II

Definition Christopher M. Bourke [email protected]

Objected-Oriented Programming is a programming paradigm that uses objects (data structures which have data fields and methods) which interact together within a computer program.

Object Oriented Programming

Object Oriented Programming

Key Ideas

Keep in mind

When talking about OOP, keep in mind: I

Modularity of design

I

Encapsulation of data into Objects

I

Abstraction of an object’s behavior and representation

I

Hierarchical organization of objects with subtypes inheriting behavior and state

I

Polymorphism ability of objects to have multiple forms in different contexts at different times

Object Oriented Programming

I

Definitions are often blurred, authors/contexts may differ slightly

I

Languages can have some, all, or none OOP features

I

Programs can ignore or utilize some subset of features

I

Non-OOP languages can support some (or all!) OOP features without being “OOP”

I

Debate still going as to “best” practices, how to do OOP, etc.

I

Understanding some concepts requires understanding other concepts

Motivation I

Advantages

Consider the evolution of computer languages

I

Facilitates modeling of real-world agents & problems

I

Supports modularity & decomposition

I

I

Clear demarcation of responsibilities and functionality

I

I

Separates interface (the what) from implementation (the how)

I

Promotes code reuse

I

Bugs, side-effects, etc. can be localized, less and more predictable testing

Machine Code → Assembly → Imperative Language

Each iteration still forces you to think in terms of a computer’s structure

I

Other Programming language paradigms force models/problems into their paradigm

I

Example: LISP assumes that all problems involve lists

I

Example: C assumes all problems are procedural (algorithmic)

Motivation II

I

In general, problems are forced into a language’s paradigm

I

Involves some “translation” or pigeonholing

I

Good for domain-specific problems or just number-crunching, bad for generality

I

Opposite of what it should be: computers should be serving our needs

I

Languages should model our world and problems

Versus Declarative

Declarative Paradigm I

“Declares” behavior of a program

I

Specifies logic of computation, not control flow

I

Functional, avoids state (Lisp, Scheme, Haskell)

I

Logic programming

I

Domain languages: Regular Expressions, HTML, Excel, SQL

I

Not necessarily Turing-complete

History of OOP I I

Paradigms have “evolved” to OOP

I

MIT 50s - 60s: LISP “atoms”

I

1960: Sketchpad (first CAD, revolutionary GUI) by Ivan Sutherland, introduced initial concepts

I

1967: Simula 67 by Dahl & Nygaard (bank simulation; agents: tellers, customers, accounts, transactions; physical modeling) 1972: Smalltalk by Alan Kay

I

I I I I

I

Based on Plato’s Theory of Forms Allegory of the Cave “A form is an objective ’blueprint’ of perfection” (an archetype) No perfect circle, just shadows, representations of it verything has a quintessence, an archetype, an apotheosis

1983: Bjarne Stoustrup develops C++ I

Inspired to add OOP features to C from Simula

Contrasting with Other Paradigms

I

Most modern programming languages support some OOP features

I

Features back-added due to demand or advantages that OOP provides

I

OOP vs. Declarative paradigm

I

OOP vs. Imperative paradigm

Versus Imperative

Imperative Paradigm I

Specifies a specific process (algorithm) that changes a program’s state

I

Built from one or more procedures (methods, functions)

I

Procedural & Structured paradigms (state changes are local or parameterized), not encapsulated

I

Examples: FORTRAN, C

History of OOP II I

First compilers simply translated C++ syntax to pure C

I

1983: Brad Cox & Tom Love develop Objective-C

I

1990s: OOP came to dominate programming methodologies (especially due to GUI development)

I

Languages updated to include OOP features 1995: Java!

I

I

I I I I I I

Inspired to add OOP features to C from Smalltalk

1995 by James Gosling, Sun Microsystems “simple, object-oriented and familiar” “robust & secure” “architecture-neutral and portable” “high performance” “interpreted, threaded, dynamic”

Continued Refinements I

I

Design Patterns - a general reusable solution to a common and reoccurring problem in software design (also called idioms)

I

Anti-patterns and “smells”

I

Modeling tools (UML – Unified Modeling Language)

I

Design-by-contract frameworks

I

Integrated Development Environments (IDEs)

I

Development of libraries, frameworks

I

Development of methodologies, best practices, etc.

Objects

Continued Refinements II

Figure : UML Diagram Example

Objects

Abstract Data Types

I

Basis for Objects: Abstract Data Types (ADTs)

Definition

I

Mathematical model for classes of data structures with similar behavior or semantics

An object is a general entity characterized by the following.

I

Purely theoretical entities

I

Identity – An aspect that distinguishes it from other objects

I

Generalization applicable to areas other than OOP

I

State – properties (attributes, elements, data, fields)

I

Algebraic structures, AI, algorithms, etc.

I

I

Examples: stacks, queues, maps, strings, and their operations

Behavior – describes an object’s interface (methods, routines, functions)

Objects I

Objects II

Key Concepts

Key Concepts

Message sending I

Objects provide services

I

Client code (user) can access these services by sending messages

I

Example: a signal to execute one of its methods

I

A signal to turn a Light object on() or off()

I

Facilitated by an externally available interface

Complex Data Types I

Collection of multiple pieces of information

I

Mixed types

I

Varying visibility

Objects III

Objects IV

Key Concepts

Key Concepts

Construction I

Objects are constructed rather than assigned

I

Construction may be specified through constructors

I

Assignment through references

I

Contrast with primitive types

Objects V

Object Design I

General approach: decompose an entity to the point where it is simple enough to implement or a suitable object already exists

I

Keep it simple

I

Semantics may dictate design

I

Avoid the God-Object anti-pattern

4 Main Principles

Key Concepts

Examples I

An animal is a general type

I

Dogs, Cats, Snakes, Lizards are all animals

I

How can we further develop a taxonomy? Should the following be incorporated?

I

I I

Pets? Gender?

I

Strict is-a relationship

I

Examples: vehicle, automobile, truck, car, boat plane

Abstraction I

Definition Abstraction is the mechanism by which objects are given their representation and implementation details are hidden. Abstraction is apparent in many areas: I

Application layers (database, middle-tier, front-end)

I

System Layers

I

Protocol layers (OSI networking model)

Object Oriented Programming involves 4 main principles 1. Abstraction 2. Encapsulation 3. Inheritance 4. Polymorphism

Abstraction II

Already familiar with Procedural Abstraction: the implementation of a process is codified into a reusable piece of code inside a function. Example: a square root function may be implemented using various algorithms. I

Taylor series

I

Babylonian method

I

Some other interpolation method

Abstraction III

Abstraction IV

I

Abstraction in OOP takes this further: methods implementations are abstracted, but so are the internal representations of the objects

I

Objects are defined with a representation similar to is meaning (semantics) while hiding implementation details

I

Defines the conceptual boundaries of an object, distinguishing between objects

In the end: who cares?

I

Procedural abstraction relieves us of the need to worry about implementation details

Allows the client (programmer, user) to deal with objects based on their public interface without worrying about details

I

It just works!

Example: A sorting function I

Selection sort? Quick sort? Other?

I

Temporary space?

I

How does it swap?

Abstraction in languages

Abstraction Example 1 Date/Time

A date/time stamp object may be defined to represent a particular point in time (with functionality for formatting, comparing and operating with durations, intervals, other date/time instances). I

Abstraction of objects is achieved through its publicly available interface

I

Interface specifies how you can use the object

I

A collection of individual numbers (year, month, day, etc.) A single numerical value (time from a particular epoch) ISO 8601-formatted string (ex: 2012-05-04T12:20:34.000343+01:00)

How could such an object be represented?

Specifies which methods may be signaled by client code

I

I

May specify a contract

I

I

In conjunction with inheritance: behavior of subtypes may change, be enhanced, etc.

I

Abstraction Example 2

Abstraction relieves us of the need to worry about such details I

Representation is internal to the object

I

Consistency and changes are handled by the object

I

We only interact with its interface

Example 3

Strings

Most languages support strings, but may use different representations I

A null-terminated character array

I

A length-prefixed character array

I

Dynamic character array

I

ASCII or Unicode?

Representing a string as an object relieves us of the need to worry about these details I

Contrast with procedural language (C): memory management, consistency, expectations must be handled manually

I

Instead of worrying about details: just use it!

A Graph has vertices (nodes) and edges; may be represented as: I

matrix

I

adjacency list

I

maps

Encapsulation I

Encapsulation II

Definition Encapsulation is a mechanism for restricting access to (some of) an object’s components and for bundling data and methods operating on that data. Includes:

I

A form of information hiding

I

In contrast to abstraction which is implementation hiding

I

Includes the aspect of grouping data – modularity

I

Protection of data

I

Allows restriction to access and control of data

I

Allows internal behavior to change, evolve, be fixed without affecting client code

I

Usually breakable (through reflection, exposing in subclasses)

1. Grouping of data 2. Protection of data 3. Grouping of methods that act on an object’s data

Encapsulation III

Encapsulation Best Practice

I

Enables mutator and accessor methods I I I

Changes are made to be intentional Side-effects can be controlled and localized Allows validation

I

Best practice: make everything private, control access through getters/setters

I

Objects should not just be data containers

I

Enables objects to be immutable (predictable, thread-safe)

I

I

Key idea: abstraction allows a user to access essential information, encapsulation hides the data, they compliment each other

Any method that acts on an object’s data should be a member method

I

Do not break encapsulation by placing related functionality elsewhere

Encapsulation I

 1 public class BankAccount { 2 private double balance ; 3 private double apr ; 4 ... 5 // constructors , getters / setters 6 ... 7 public double g et Mo nt hl yE ar ni ng s () { 8 return this . balance * ( this . apr / 12.0) ; 9 } 10 } 

Java Example

1. Grouping of data 2. Protection of data 3. Grouping of functionality that acts on that data



Encapsulation II Java Example

 public class BankUtils {

Breaking encapsulation:

1 2 3

4



5 6

} 

public static double g et Mo nt hl yE ar ni ng s ( BankAccount acct ) { return acct . getBalance () * ( acct . getAPR () / 12.0) ; }





Side-effects

Why Encapsulation

Definition Beginners question: why can’t everything just be public? A function or expression has a side-effect if it modifies some state or has an observable interaction with calling functions or other parts of the program (either globally, to other threads, the outside world, etc.).

Without Encapsulation:

Examples:

I

Internal state could be modified with impunity

I

Everything essentially becomes global

I

Difficult to test/control

I

A sort method that reorders the original list

I

Anti-modular

I

A setter method that modifies an object’s state that can be observed through its public interface

I

No way to enforce rules

I

A subroutine used in a logical expression that makes changes to its parameters

I

Any changes to global, static variables, parameters, data I/O, etc.

Inheritance

Save on typing: utilize IDE macros (Eclipse: Source → generate getters/setters)

Aspects of Inheritance

Definition Inheritance is the ability to extend the definition of objects; creating objects from previously created or defined objects Most common form: classical inheritance (subclassing)

I

Allows us to define a hierarchy of related objects

I

Subclasses inherit behavior and/or fields from superclasses

I

Subclasses can augment, modify, or change the behavior of methods

I

Facilitates code reuse

I

Generalized common behavior and/or interface can be defined in superclasses

I

subclass/superclass

I

Subclasses provide specialization (more specificity)

I

derived/base classes

I

I

child/parent classes

General properties or behavior is specialized into more concrete implementations

I

Super/subclass defines an is-a relationship

Inheritance

Java Example

Java Example

I

Bird is a superclass

I

All birds move(), but how?

I

Ostrich and Robin may be subclasses

I

Ostrich may specify a walk() method

I

Robin may specify a fly() method

I

move() may be overridden in the subclasses to call their respective

methods I

Subclasses may be referred to as their super class

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27



public class Bird { public void move () { System . out . println ( " Moving somehow ... " ) ; } }



public class Robin extends Bird { public void fly () { System . out . println ( " Flying ... " ) ; } ... @Override public void move () { this . fly () ; } } public class Ostrich extends Bird { public void walk () { System . out . println ( " Walking ... " ) ; } ... @Override public void move () { this . walk () ; } }





Collections Hierarchy I

Collections Hierarchy II

Collection

Set

HashSet

List

TreeSet

ArrayList

LinkedList

I

A general collection is a data structure that holds stuff

I

A set is a collection that holds stuff in an unordered manner; a list is a collection that holds stuff in an ordered manner

I

A HashSet is a set that holds stuff in an unordered manner using a hash table

I

An ArrayList is a list that holds stuff in an ordered manner using an array, etc.

Figure : Java Collections Library Inheritance structure

Virtual Functions

How this works: Dynamic Dispatch

A virtual function is a function that can be overridden in a subclass. I I

C++: all functions are non-virtual by default; can be made virtual by use of the keyword virtual Java: all non-private functions are virtual by default; can be made non-virtual by use of the keyword final I I I

static methods can be overridden1 visibility of methods can be more open, but not decreased within a class, access to the superclass’s method is accessible via the super keyword

I

Upon instantiation, a particular constructor is called

I

This creates the object in memory as a virtual table (vtable)

I

Object has data in memory, but also references to the code for its methods

I

When a method is called, the method which the vtable refers to is invoked

I

This process is a run-time mechanism (since methods can be invoked via a reference to the super class)

1 but when static methods are invoked, they should be done so via the class name anyway

How this works: Dynamic Dispatch

Multiple Inheritance

Java Example

1 2



3 4 5 6 7 8 9 10



Bird b = new Bird () ; b . move () ; // prints " Moving somehow ..." Robin r = new Robin () ; r . move () ; // prints " Flying ..." r . fly () ; // prints " Flying ..." b = r ; // subclass referred to as its superclass b . move () ; // prints " Flying ..." // b . fly () ; m = new HashMap < String , Student >() ; 2 ... 3 String nuid = " 12345678 " ; 4 Student s = new Student (...) ; 5 m . put ( nuid , s ) ; 6 ... 7 String someNuid = " 87654321 " ; 8 Student joe = m . get ( someNuid ) ;  I

Maps are key-value data structures

I

Abstraction: get and put methods define how to use this data structure without worrying about its implementation details

Summary Example III





Maps I

Encapsulation: maps could be implemented using a tree or hashtable; could use open or closed addressing; representation details are irrelevant and hiddent to us

I

Inheritance: HashMap is-a Map that uses a hash table (while a TreeMap is a map that uses a tree)

I

Polymorphism: through parametric polymorphism, we can map specific types to other specific types

I

Java note: a Map is not Collection (see why: http://docs.oracle.com/javase/1.4.2/docs/guide/ collections/designfaq.html#14

Software Engineering & Design Books I

Maps

Map

AbstractMap

HashMap

TreeMap

LinkedHashMap Figure : Map data structures in Java Collections library

Software Engineering & Design Books II

Figure : Code Complete (1993) by Steve McConnell

Figure : Design Patterns: Elements of Reusable Object-Oriented Software (1994) by Gamma et al.

Software Engineering & Design Books III

Figure : The Mythical Man-Month (1975) by Frederick Brooks Jr.

Software Engineering & Design Books IV

Figure : Refactoring: Improving the Design of Existing Code (1999) by Martin Fowler