Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.

Slides:



Advertisements
Similar presentations
Lilian Blot Announcements Teaching Evaluation Form week 9 practical session Formative Assessment week 10 during usual practical sessions group 1 Friday.
Advertisements

Computer Science 112 Fundamentals of Programming II List Iterators.
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Computer Science 112 Fundamentals of Programming II Overview of Collections.
Computer Science 112 Fundamentals of Programming II Array-Based Queues.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Computer Science 112 Fundamentals of Programming II Lists.
A Bag Implementation that Links Data Chapter 3 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Fundamentals of Programming II Inheritance and Abstract Classes
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
COMPSCI 105 S Principles of Computer Science Linked Lists 2.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Sorted Lists and Their Implementations Chapter 12 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
COMPSCI 105 S Principles of Computer Science Linked Lists 1.
Chapter 10 Classes Continued
Bag Implementations that Use Arrays Chapter 2 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
Topic 3 The Stack ADT.
The Software Development Life Cycle: An Overview Presented by Maxwell Drew and Dan Kaiser Southwest State University Computer Science Program.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Computer Science 111 Fundamentals of Programming I More Data Modeling.
OOD Case Study (For parallel treatment, see Chapter 2 of the text)
Computer Science 112 Fundamentals of Programming II Introduction to Stacks.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.
Object Oriented Analysis and Design Class and Object Diagrams.
Computer Science 112 Fundamentals of Programming II Implementation Strategies for Unordered Collections.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Genericity collections of objects. COSC 2006 Bags of Objects2 collections of objects  for real programming applications, pratical collections are collections.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Why Use Classes - Anatomy of a Class.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Tirgul 10. What We Will See Today:  Linked lists  Graphs  Trees  Iterators and Generators.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Introduction to Objects and Encapsulation Computer Science 4 Mr. Gerb Reference: Objective: Understand Encapsulation and abstract data types.
Computer Science 112 Fundamentals of Programming II Iterators.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Click to edit Master text styles Stacks Data Structure.
CSC 243 – Java Programming, Fall, 2008 Tuesday, September 30, end of week 5, Interfaces, Derived Classes, and Abstract Classes.
Fundamentals of Programming II Linked Lists
Abstract Data Type.
Fundamentals of Programming II Overview of Collections
COMPSCI 107 Computer Science Fundamentals
CSSE 120—Rose Hulman Institute of Technology
Software Development Java Classes and Methods
Fundamentals of Programming II Binary Search Trees
Fundamentals of Programming II Equality and Multiple Inheritance
Fundamentals of Programming II Interfaces and Implementations
Computer Science 111 Fundamentals of Programming I
Fundamentals of Programming I More Data Modeling
Fundamentals of Programming I More Data Modeling
Computer Science 112 Fundamentals of Programming II
A Bag Implementation that Links Data
Introduction to Object-Oriented Programming (OOP) II
Computer Science 111 Fundamentals of Programming I
Fundamentals of Programming I Commonly Used Methods More Modeling
Fundamentals of Programming I More Data Modeling
Fundamentals of Programming I More Data Modeling
Terry Scott University of Northern Colorado 2007 Prentice Hall
Fundamentals of Programming II What Is Equality?
Presentation transcript:

Computer Science 112 Fundamentals of Programming II Interfaces and Implementations

What Is an Interface? The public or external view of a resource What you see when you run help on a resource Example: Python’s math module – a set of function names and constant names

What Is an Implementation? The private or internal view of a resource What you see when you examine the full code of a resource def fib(n): """Returns the nth Fibonacci number.""" if n == 1 or n == 2: return 1 else: return fib(n – 1) + fib(n – 2) Interface Implementation

Types of Interfaces Function – The function’s header and docstring Class – The class and method headers and docstrings Module – The class and function headers

Interface and Implementation Users and implementers have different responsibilities A interface provides an abstraction barrier between users and implementers User’s codeInterfaceImplementer’s code

Why the Barrier? The resource is easier to learn Can plug and play resources Can provide several implementations of the same resource (polymorphism) Can maintain a resource without disturbing users’ code

Example Resource: A Bag Collection A bag is a container where you can put things, see if they’re there, visit them all, or remove each one There is one interface or set of methods for all bag implementations Two common implementations use an array or a linked structure

UML Class Diagram for Bags LinkedBagArrayBag BagInterface The Unified Modeling Language is a way of describing relationships among resources visually means implements an interface

b.isEmpty()Returns True if empty, False otherwise len(b)Returns the number of items in the bag str(b)Returns a string representation of the bag item in bReturns True if item is present in the bag, or False otherwise for item in b:Visit each item in the bag b.add(item)Adds item to the bag b.remove(item)Removes item from the bag b.clear()Removes all items from the bag b1 + b2Combines items in a new bag and returns it b == anythingTrue if equal, False otherwise The Interface for All Bags

b.isEmpty()isEmpty(self) len(b)__len__(self) str(b)__str__(self) item in b__contains__(self, item) for item in b:__iter__(self) b.add(item)add(self, item) b.remove(item)remove(self, item) b.clear()clear(self) b1 + b2__add__(self, other) b == anything__eq__(self, other) Actual Methods in Python

Bag Implementations Array-based Linked structure Always a single set of abstract operations bag1 = LinkedBag() bag2 = ArrayBag([1, 2, 3, 4])

bag = LinkedBag() # or ArrayBag() bag.add("A string") bag.add("Another string") for item in bag: print(item) secondBag = LinkedBag(bag) thirdBag = bag + secondBag print(secondBag == thirdBag) for item in bag: secondBag.remove(item) print(len(secondBag)) Example Use of a Bag We have a single set of abstract operations and two implementing classes, ArrayBag and LinkedBag

Docstrings and Preconditions def remove(self, item): """Removes item from self. Precondition: item is in self. Raises: KeyError if item is not in self.""" A docstring states what the method does. A precondition states what must be true for a method to run correctly. The method raises an exception if a precondition is not true.

Implementation: Data The first step is to decide what the attributes are and represent these using the appropriate data Will name these data with class or instance variables The __init__ method sets these up

Composition and Aggregation means “is composed of” LinkedBagNode * ArrayBag BagInterface Array * means “aggregates zero or more within”

from arrays import Array class ArrayBag(object): """An array-based bag implementation.""" # Class variable DEFAULT_CAPACITY = 10 # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) Data for ArrayBag

# Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" return len(self) == 0 def __len__(self): """Returns the number of items in self.""" return self._size def __str__(self): """Returns the string representation of self.""" return "{" + ", ".join(map(str, self)) + "}" Some Accessor Methods Try to run methods within an implementation, rather than accessing variables directly.

# Mutator methods def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArrayBag.DEFAULT_CAPACITY) def add(self, item): """Adds item to self.""" # Resize the array here if necessary self._items[len(self)] = item self._size += 1 Some Mutator Methods

from node import Node class LinkedBag(object): """A link-based bag implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = None self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) Data for LinkedBag

# Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" return len(self) == 0 def __len__(self): """Returns the number of items in self.""" return self._size def __str__(self): """Returns the string representation of self.""" return "{" + ", ".join(map(str, self)) + "}" Some Accessor Methods Hooray! No changes from the same methods in ArrayBag !

# Mutator methods def clear(self): """Makes self become empty.""" self._size = 0 self._items = None def add(self, item): """Adds item to self.""" self._items = Node(item, self._items) self._size += 1 Some Mutator Methods The container is now a linked structure, so it must be manipulated differently.

For Friday Iterators