Classes, interfaces, & documentation. Review of basic building blocks

Size: px
Start display at page:

Download "Classes, interfaces, & documentation. Review of basic building blocks"

Transcription

1 Classes, interfaces, & documentation Review of basic building blocks

2 Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform on data are its actions Object knowledge and actions are specified by its class In a class definition: knowledge: instance variables actions: instance methods

3 Information hiding Separation of program specification from its implementation several programmers can work on different facets of same problem, knowing specs others will meet (and not having to know how specs are met) an ADT (abstract data type) is a class presented to client programmers with information hiding What do you, as the client programmer, need to know?

4 Class Basis for a Java program, but more to the point: specification for a data type An object is an instance of a class Class specification includes these members: data (variables) constructor(s) methods

5 Interfaces What is an interface? Google says: For example user interface

6 Again, from Google: Interfaces Which sounds suspiciously like what we just called a class specification because it is! From the Java Tutorial: objects define their interaction with the outside world through the methods they expose. Methods form the object s interface with the outside world.

7 Information hiding, again Classic OOP theory suggests that we should define an object s interface before we design its implementation; lots of good reasons for this: Makes it easy to break up a large programming task so a team can handle it Everybody has a clear idea of what to expect from others methods even though they haven t been written yet Test code can be written before implementation: should be able to use the same test code regardless of implementation

8 Interfaces & information hiding A class s interface consists of its public portions: typically methods, occasionally data (constants only, except in very rare cases) Separating implementation from specification means that implementation can change (and improve) without interfering with code that depends on the original class to have the same interface

9 In Java, we take it a step further

10 Example public interface Container { public void insert (Object data); public Object retrieve (Object target); public boolean remove (Object target); public boolean contains (Object target); public int getsize(); public int getcapacity(); } The public methods are specified: we know how to call them (and can make guesses about what they do) We know nothing about the data structures and algorithms that define the implementation of the class One important point: an interface is not a class We can t create objects using this interface type directly We need a class that implements the interface

11 Example continued public class SadSack implements Container { public void insert (Object data) {} public Object retrieve (Object target) {return null;} public boolean remove (Object target) {return false;} public boolean contains (Object target) {return false;} public int getsize() {return 0;} public int getcapacity() {return 0;} } This class could be used to write a quick test driver More sophisticated implementations could use the same test code

12 Test code (separate handout) Good testing practice requires that we: think ahead about how our program should behave under a variety of conditions run tests to verify the correctness of the program under each of these conditions Setting up a sample data set to test against is important: a simple list of values to try may be appropriate for some programs a ready-made data file would be more appropriate for others.

13 Documentation: we can do better! Goals: Make your code readable to other programmers Be able to make sense of your own code, much less others, a year from now Self-documenting code: naming things deliberately so that their reason for being becomes obvious Be consistent with: indentation use of white space bracket style anything else you can think of!

14 Clarity Client programmers need to be able to comprehend your class s interface: confused programmers write buggy code Clarity often comes down to documentation: explain what a method does in terms you (and your clients) can easily understand 14

15 Programming by Contract Spell out responsibilities: of caller of implementor Increase reliability Increase efficiency 15

16 Pre and post conditions Represent a contract of sorts between the provider of a service (e.g. a Java class) and the client who uses that service (another programmer) Pre and post condition statements are the documentation you can and should write before you write any code they are, or at any rate should be, part of the interface

17 Preconditions State what must be true about the data being passed to a method For example, if I m writing a method to calculate the square root of a number, I can only operate on positive values so I state this as a precondition The contract: if you meet my precondition, my method will work as advertised; if not, anything could happen (I cannot be held responsible for your bad data choices!)

18 Preconditions When precondition fails, service provider may throw exception return false answer corrupt data So the client is entirely responsible for meeting the precondition; but the careful service provider will: Inform the client of the precondition (documentation!) Check the validity of the precondition before proceeding with the method (option 1, above, is usually the best option!) 18

19 Preconditions: some caveats Excessive error checking is costly so service code should throw exceptions, not try to catch them (leave that up to clients) Returning dummy values can complicate testing worked okay for our very generic toy example, but in most cases it s not the best option we want our programs to produce reliable, and reliably correct, results 19

20 Exceptions in the contract Exception throw also part of the contract Caller can rely on behavior Exception throw not always result of precondition violation Method on next slide has no precondition (because it takes no arguments) but can throw exception anyway, and client should know under what conditions 20

21 Example We want to remove first element from a container Since it s always the first element, we don t need an argument so what happens if the container is empty? IllegalArgumentException if queue is empty */ public Message removefirst() { if (count == 0) throw new IllegalArgumentException(); Message r = elements[head]; } 21

22 Postcondition Condition that the service provider guarantees Describes what the method does (not the algorithm, just the results) If the method returns a value, describes that value Otherwise, just describes what happens when method is called 22

23 Example Is this sufficient documentation? How can it be improved?

24 Example What is the precondition? Where/how should it be stated? What is the postcondition?

25 Javadoc The previous examples contained a commenting style that may not be familiar to some of you: javadoc A javadoc comment is a multiline comment that begins with /** and ends with */ The first line of a javadoc comment should be a concise description of the class or method it refers to Various embedded tags can be used to create standardized comments (like what you see in the Java API)

26 Javadoc Take credit for your could be a number or a date; one way to keep track of describe one method parameter per tag can be used to describe pertinent describe return value can be used to describe use for exceptions code might spawn; can be another place to describe precondition

27 Back to classes We have seen that we can specify what a class does independent of how its methods actually work But sooner or later, we need to think in terms of the data representation and the algorithms that operate on that data The next several slides will take us through that process

28 Example: a throttle Models physical object that controls flow of fuel to an engine Attributes include: shutoff point: 0% fuel flow progressively higher flow rates represented by lever position; maximum is fully open, 100% fuel flow each position between 0 and max is proportionately higher than the previous source:

29 Member variables We need to represent the attributes described on the previous slide: number of throttle positions (max) current position (position) Fill in the blanks of the class definition (next slide)

30 public Throttle { // member variables: private max; position;

31 Constructor Method for initializing instance variables of a new object For the Throttle class, we ll define two constructors: a default constructor that presets a chosen maximum value a constructor that allows the client programmer to choose the maximum value

32 // class definition continued // default constructor: public Throttle () { max = 100; position = 0; } // second constructor: public (int cap) { }

33 Questions What happens if you don t define a constructor for your class? Is there an advantage to defining your own constructor?

34 Instance methods - Accessors Accessors provide information about an object s state Accessors do not change the state of the object An accessor method always returns a value

35 Why not use public instance variables instead? Accessors support the principle of information hiding; client programmers don t need to know anything about implementation (e.g., names of the variables), just how to get the information they need (return value from accessor) Use of accessors (instead of public variables) allows change to the implementation of a class without any required change to client code Private data can t be modified in ways the author of the class didn t intend

36 Accessors for the Throttle class getflow: returns value indicating proportion of max is currently flowing ison: returns value indicating whether or not throttle is turned on

37 // accessor methods public getflow () { } public ison () { }

38 Instance methods - modifiers Also known as mutators: methods that make specific changes to object s state Usually void why?

39 Modifiers for Throttle class shutoff: turns off Throttle shift: moves Throttle s position up or down by a specific amount how will this amount be specified? how do we handle a value that goes out of bounds (<0 or >max)?

40 // modifier methods: public void shutoff () { } public void shift ( setting) { }

41 Documentation for Data Pre and post conditions are statements about class methods Invariants are statements about instance variables

42 Class Invariants Condition that is true after every constructor (no invalid objects can be created) preserved by every method (if it's true before the call, it's again true afterwards) Useful for checking validity of operations 42

43 Class invariants As long as instance fields are private, you have complete control over object modification Can guarantee certain values are within legal range, certain references are not null Invariant is appropriate tool for documenting such a guarantee 43

44 Using a class Once a class has been established, you can use instances of the class (objects) in other programs Remember, the class is a data type; in order to perform the actions specified by its instance methods, we need to instantiate an object

45 Instantiating objects Object creation is a two step process: declaration: Throttle choke; initialization: choke = new Throttle(50); This is often done in a single step: Throttle choke = new Throttle(50);

46 Calling methods Once we have an object, we can call instance methods defined in the class The calling object and method are specified, along with any necessary arguments; syntax: objectname.methodname(arg(s)) Write a line of code that adjusts choke (the Throttle object created on the previous slide) up 3 steps:

47 Key points to remember Objects are instances of classes Object names are references to objects Objects are created using the new operator and one of the class s constructors What happens in the following situation? How do we avoid the problem? Throttle uhoh; uhoh.shutoff();

48 Null references Instead of creating an object immediately, you can declare a variable and set it to null: Throttle t = null; You can also set an object reference to null after it s been in use: Throttle t = new Throttle(); t.shift(30);. // after a while, finished with this object t = null;

49 Why use null references? Helps conserve system resources; even though Java has automatic garbage collection, not a bad idea to help out Means every object reference can be counted on to be in one of two conditions: refers to an object (not null) refers to NO object (null) We can test an object reference to see if it is null; this means we can always avoid a NullPointerException; see code on next slide

50 // One way: if (t!= null) System.out.println( Current setting is + t.getflow()); else System.out.println( Can t get setting no active throttle ); // Another way: try { System.out.println( Current setting is + t.getflow()); } catch (NullPointerException e) { System.out.println( Can t get setting no active throttle ); }

51 Reference variables & assignment Consider the code snippet below: Throttle t1=null, t2=null; t1 = new Throttle(100); t2 = t1; t2.shift(50); System.out.println( Current value of t1 is + t1.getflow()); What is output? Why?

52 Sketch of situation Since both variables refer to the same object, a change invoked by one shows up in both

53 A better way Using the assignment operator with objects does not copy the object, it only copies its address, leading to the situation we ve just seen If we need two identical objects, we could simply instantiate two objects with the same parameters: Throttle t1 = new Throttle(100); Throttle t2 = new Throttle(100); What would this look like? Is (t1 == t2) a true statement?

54 A better way To ensure that two object references aren t pointing to the same object, the best option is to define a clone method for the data type you re creating All classes have an inherited clone method (from Object), but it doesn t really help matters, as we will see If you are defining a new clone method, you should tag your class as implementing the Cloneable interface this signals to other programmers that you have a valid clone method

Class design guidelines. Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3)

Class design guidelines. Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3) Class design guidelines Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3) 1 Encapsulation Classes can be implemented many different ways each has advantages

More information

Outline. From last Time. Announcements. CS1007: Object Oriented Design and Programming in Java. Design considerations Testing Putting all together

Outline. From last Time. Announcements. CS1007: Object Oriented Design and Programming in Java. Design considerations Testing Putting all together Outline CS1007: Object Oriented Design and Programming in Java Lecture #7 Sept 27 Shlomo Hershkop shlomo@cs.columbia.edu Design considerations Testing Putting all together Midterm date set Will post review

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Assertions, pre/postconditions

Assertions, pre/postconditions Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

Java Review. Fundamentals of Computer Science

Java Review. Fundamentals of Computer Science Java Review Fundamentals of Computer Science Link to Head First pdf File https://zimslifeintcs.files.wordpress.com/2011/12/h ead-first-java-2nd-edition.pdf Outline Data Types Arrays Boolean Expressions

More information

CSE331 Winter 2014, Midterm Examination February 12, 2014

CSE331 Winter 2014, Midterm Examination February 12, 2014 CSE331 Winter 2014, Midterm Examination February 12, 2014 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 11:20. There are 100 points

More information

CSE 331. Programming by contract: pre/post conditions; Javadoc

CSE 331. Programming by contract: pre/post conditions; Javadoc CSE 331 Programming by contract: pre/post conditions; Javadoc slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1

More information

Write for your audience

Write for your audience Comments Write for your audience Program documentation is for programmers, not end users There are two groups of programmers, and they need different kinds of documentation Some programmers need to use

More information

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

CSE wi Midterm Exam 2/8/18. Name UW ID #

CSE wi Midterm Exam 2/8/18. Name UW ID # Name UW ID # There are 11 questions worth a total of 120 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

Assertions and Exceptions Lecture 11 Fall 2005

Assertions and Exceptions Lecture 11 Fall 2005 Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,

More information

Representation Invariants and Abstraction Functions

Representation Invariants and Abstraction Functions Representation Invariants and Abstraction Functions Outline Reasoning about ADTs Representation invariants (rep invariants) Representation exposure Checking rep invariants Abstraction functions CSCI 2600

More information

Advanced Object Oriented Programming EECS2030Z

Advanced Object Oriented Programming EECS2030Z Advanced Object Oriented Programming EECS2030Z 1 Academic Support Programs: Bethune having trouble with your FSC and LSE courses? consider using the Academic Support Programs at Bethune College PASS free,

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

CSE 331 Midterm Exam 2/13/12

CSE 331 Midterm Exam 2/13/12 Name There are 10 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes, closed

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute. Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute. Abelson & Sussman Use a good set of coding conventions, such as the ones given in the

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos. Aggregation Thursday, July 6 2006 CSE 1020, Summer 2006, Overview (1): Before We Begin Some administrative details Some questions to consider Aggregation Overview / Introduction The aggregate s constructor

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley In Brief: What You Need to Know to Comment Methods in CSE 143 Audience o A random person you don t know who wants

More information

Lecture 4: Procedure Specifications

Lecture 4: Procedure Specifications Lecture 4: Procedure Specifications 4.1. Introduction In this lecture, we ll look at the role played by specifications of methods. Specifications are the linchpin of team work. It s impossible to delegate

More information

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

What is software testing? Software testing is designing, executing and evaluating test cases in order to detect faults.

What is software testing? Software testing is designing, executing and evaluating test cases in order to detect faults. ϖοιδ τεσταδδανδχουντ() { ασσερ τεθυαλσ(1, ο.αδδανδχουντ(νεω ΑρραψΛιστ()); ϖοιδ τεσταδδανδχουντ() { ασσερ τεθυαλσ(1, ο.αδδανδχουντ(νεω ΑρραψΛιστ()); ιντ αδδανδχουντ(λιστ λιστ) { ρετυρν λιστ.σιζε(); ιντ

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm) CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, 2015 11:30pm) This program focuses on binary trees and recursion. Turn in the following files using the link on the

More information

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) CSE 11 Winter 2017 Program Assignment #2 (100 points) START EARLY! Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) PROGRAM #2: DoubleArray11 READ THE ENTIRE ASSIGNMENT BEFORE STARTING In lecture,

More information

Classes Classes 2 / 36

Classes Classes 2 / 36 Classes 1 / 36 Classes Classes 2 / 36 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Linked Lists. It s all connected

Linked Lists. It s all connected Linked Lists It s all connected Linked list: a data structure used to represent an ordered list Consists of a sequence of nodes A node consists of a data item and a reference to the next node -- the connecting

More information

CSE 331 Midterm Exam Sample Solution 2/13/12

CSE 331 Midterm Exam Sample Solution 2/13/12 Question 1. (14 points) (assertions) Using backwards reasoning, find the weakest precondition for each sequence of statements and postcondition below. Insert appropriate assertions in each blank line.

More information

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions CSE1720 Click to edit Master Week text 01, styles Lecture 02 Second level Third level Fourth level Fifth level Winter 2015! Thursday, Jan 8, 2015 1 Objectives for this class meeting 1. Conduct review of

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

The compiler is spewing error messages.

The compiler is spewing error messages. Appendix B Debugging There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly. Compile-time errors are

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup. Chapter 5 Errors Hyunyoung Lee Based on slides by Bjarne Stroustrup www.stroustrup.com/programming 1 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must

More information

Week 7 - More Java! this stands for the calling object:

Week 7 - More Java! this stands for the calling object: Week 7 - More Java! Variable Scoping, Revisited this Parameter Encapsulation & Principles of Information Hiding: Use of public and private within class API, ADT javadoc Variables of class Type Wrapper

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

CSE wi Midterm Exam 2/8/18 Sample Solution

CSE wi Midterm Exam 2/8/18 Sample Solution Remember: For all of the questions involving proofs, assertions, invariants, and so forth, you should assume that all numeric quantities are unbounded integers (i.e., overflow can not happen) and that

More information

Designing and Implementing Classes Topic 6

Designing and Implementing Classes Topic 6 Designing and Implementing Classes Topic 6 Don't know much geography Don't know much trigonometry Don't know much about algebra Don't know what a slide rule is for -Sam Cooke AP Computer Science Designing

More information

CS 3 Introduction to Software Engineering. 5: Iterators

CS 3 Introduction to Software Engineering. 5: Iterators CS 3 Introduction to Software Engineering 5: Iterators Questions? 2 PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One

More information

CSE331 Autumn 2011 Midterm Examination October 28, 2011

CSE331 Autumn 2011 Midterm Examination October 28, 2011 CSE331 Autumn 2011 Midterm Examination October 28, 2011 50 minutes; 75 points total. Open note, open book, closed neighbor, closed anything electronic (computers, webenabled phones, etc.) An easier-to-read

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Algebraic Specifications

Algebraic Specifications Object-Oriented Design Lecture 2 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 11, 2007 Algebraic Specifications Last time I said a word about the abstraction barrier, separating the clients from the implementors.

More information

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Errors. Lecture 6. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with

More information

Page 1. Human-computer interaction. Lecture 1b: Design & Implementation. Building user interfaces. Mental & implementation models

Page 1. Human-computer interaction. Lecture 1b: Design & Implementation. Building user interfaces. Mental & implementation models Human-computer interaction Lecture 1b: Design & Implementation Human-computer interaction is a discipline concerned with the design, implementation, and evaluation of interactive systems for human use

More information

Software Engineering Testing and Debugging Testing

Software Engineering Testing and Debugging Testing Software Engineering Testing and Debugging Testing Prof. Dr. Peter Thiemann Universitt Freiburg 08.06.2011 Recap Testing detect the presence of bugs by observing failures Debugging find the bug causing

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

What This Course Is About Design-by-Contract (DbC)

What This Course Is About Design-by-Contract (DbC) What This Course Is About Design-by-Contract (DbC) Readings: OOSC2 Chapter 11 EECS3311 A: Software Design Fall 2018 CHEN-WEI WANG Focus is design Architecture: (many) inter-related modules Specification:

More information

Javadoc. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 7

Javadoc. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 7 Javadoc Computer Science and Engineering College of Engineering The Ohio State University Lecture 7 Motivation Over the lifetime of a project, it is easy for documentation and implementation to diverge

More information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Introduction to Programming for ECE Lecture 1 Course Overview Welcome! What is this class about? Java programming somewhat software somewhat Solving engineering

More information

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM Objectives Defining a wellformed method to check class invariants Using assert statements to check preconditions,

More information

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II Adam Blank Lecture 3 Autumn 2016 CSE 143 Computer Programming II CSE 143: Computer Programming II More ArrayIntList; pre/post; exceptions; debugging Drawings 1 Drawings 2 Drawings 3 Drawings 4 Drawings

More information

CS 215 Software Design Homework 3 Due: February 28, 11:30 PM

CS 215 Software Design Homework 3 Due: February 28, 11:30 PM CS 215 Software Design Homework 3 Due: February 28, 11:30 PM Objectives Specifying and checking class invariants Writing an abstract class Writing an immutable class Background Polynomials are a common

More information

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points. Java for Non Majors Final Study Guide April 26, 2017 The test consists of 1. Multiple choice questions 2. Given code, find the output 3. Code writing questions 4. Code debugging question 5. Short answer

More information

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II Adam Blank Lecture 3 Autumn 201 CSE 143 CSE 143: Computer Programming II More ArrayIntList; pre/post; exceptions; debugging Computer Programming II Drawings 1 Drawings 2 Drawings 3 Drawings 4 Drawings

More information

1 Inheritance (8 minutes, 9 points)

1 Inheritance (8 minutes, 9 points) Name: Career Account ID: Recitation#: 1 CS180 Spring 2011 Exam 2, 6 April, 2011 Prof. Chris Clifton Turn Off Your Cell Phone. Use of any electronic device during the test is prohibited. Time will be tight.

More information

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters. CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.

More information

Utilities (Part 3) Implementing static features

Utilities (Part 3) Implementing static features Utilities (Part 3) Implementing static features 1 Goals for Today learn about preconditions versus validation introduction to documentation introduction to testing 2 Yahtzee class so far recall our implementation

More information

Chapter 5 Errors. Bjarne Stroustrup

Chapter 5 Errors. Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup www.stroustrup.com/programming Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications,

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

Topic 3 Encapsulation - Implementing Classes

Topic 3 Encapsulation - Implementing Classes Topic 3 Encapsulation - Implementing Classes And so, from Europe, we get things such as... object-oriented analysis and design (a clever way of breaking up software programming instructions and data into

More information

Documentation Requirements Computer Science 2334 Spring 2016

Documentation Requirements Computer Science 2334 Spring 2016 Overview: Documentation Requirements Computer Science 2334 Spring 2016 These requirements are based on official Java coding conventions but have been adapted to be more appropriate to an academic environment.

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

Announcements. CS18000: Problem Solving And Object-Oriented Programming

Announcements. CS18000: Problem Solving And Object-Oriented Programming Announcements Exam 1 Monday, February 28 Wetherill 200, 4:30pm-5:20pm Coverage: Through Week 6 Project 2 is a good study mechanism Final Exam Tuesday, May 3, 3:20pm-5:20pm, PHYS 112 If you have three or

More information

a correct statement? You need to know what the statement is supposed to do.

a correct statement? You need to know what the statement is supposed to do. Using assertions for correctness How can we know that software is correct? It is only correct if it does what it is supposed to do. But how do we know what it is supposed to do? We need a specification.

More information

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm)

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm) CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, 2015 11:30pm) This assignment focuses on binary trees and recursion. Turn in the following files using the link

More information

Specifications. CSE 331 Spring 2010

Specifications. CSE 331 Spring 2010 Specifications CSE 331 Spring 2010 The challenge of scaling software Small programs are simple and malleable easy to write easy to change Big programs are (often) complex and inflexible hard to write hard

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

Lecture 4 Specifications

Lecture 4 Specifications CSE 331 Software Design and Implementation Administrivia Next assignments posted tonight HW2: Written problems on loops Lecture 4 Specifications Readings posted as well! Quizzes coming soon J Zach Tatlock

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

public static boolean isoutside(int min, int max, int value)

public static boolean isoutside(int min, int max, int value) See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static

More information

CSE 331 Midterm Exam Sample Solution 2/18/15

CSE 331 Midterm Exam Sample Solution 2/18/15 Question 1. (10 points) (Forward reasoning) Using forward reasoning, write an assertion in each blank space indicating what is known about the program state at that point, given the precondition and the

More information

CSE 331 Final Exam 6/5/17. Name UW ID#

CSE 331 Final Exam 6/5/17. Name UW ID# Name UW ID# There are 10 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions. CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines

More information

Classes. 1 Data Abstraction. 2 A Complex Number ADT

Classes. 1 Data Abstraction. 2 A Complex Number ADT Classes 1 Data Abstraction An abstraction of a concept attempts to capture the essence of the concept its essential properties and behaviors by ignoring irrelevant details. Process abstraction - group

More information

Procedural Java. Procedures and Static Class Methods. Functions. COMP 210: Object-Oriented Programming Lecture Notes 2.

Procedural Java. Procedures and Static Class Methods. Functions. COMP 210: Object-Oriented Programming Lecture Notes 2. COMP 210: Object-Oriented Programming Lecture Notes 2 Procedural Java Logan Mayfield In these notes we look at designing, implementing, and testing basic procedures in Java. We will rarely, perhaps never,

More information

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 ); Sample Final Exam 1. Evaluate each of the following expressions and show the result and data type of each: Expression Value Data Type 14 % 5 1 / 2 + 1 / 3 + 1 / 4 4.0 / 2.0 Math.pow(2.0, 3.0) (double)(2

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

Creating an object Instance variables

Creating an object Instance variables Introduction to Objects: Semantics and Syntax Defining i an object Creating an object Instance variables Instance methods What is OOP? Object-oriented programming (constructing software using objects)

More information

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

Express Yourself. Writing Your Own Classes

Express Yourself. Writing Your Own Classes Java Programming 1 Lecture 5 Defining Classes Creating your Own Classes Express Yourself Use OpenOffice Writer to create a new document Save the file as LastFirst_ic05 Replace LastFirst with your actual

More information

Shared Variables and Interference

Shared Variables and Interference Illinois Institute of Technology Lecture 24 Shared Variables and Interference CS 536: Science of Programming, Spring 2018 A. Why Parallel programs can coordinate their work using shared variables, but

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Summary. Recursion. Overall Assignment Description. Part 1: Recursively Searching Files and Directories

Summary. Recursion. Overall Assignment Description. Part 1: Recursively Searching Files and Directories Recursion Overall Assignment Description This assignment consists of two parts, both dealing with recursion. In the first, you will write a program that recursively searches a directory tree. In the second,

More information