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

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

CS 201 Advanced Object-Oriented Programming Lab 4 - Asteroids, Part 2 Due: February 24/25, 11:30 PM

Chapter 4 Defining Classes I

Write for your audience

CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM

Assertions, pre/postconditions

Introduction to Programming Using Java (98-388)

Tips from the experts: How to waste a lot of time on this assignment

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Chapter Two Bonus Lesson: JavaDoc

Documentation Requirements Computer Science 2334 Spring 2016

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

CS 211 Programming Practicum Fall 2018

CompuScholar, Inc. 9th - 12th grades

Jtest Tutorial. Tutorial

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Pace University. Fundamental Concepts of CS121 1

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

Lab Exercise 6: Abstract Classes and Interfaces CS 2334

02/03/15. Compile, execute, debugging THE ECLIPSE PLATFORM. Blanks'distribu.on' Ques+ons'with'no'answer' 10" 9" 8" No."of"students"vs."no.

CS664 Compiler Theory and Design LIU 1 of 16 ANTLR. Christopher League* 17 February Figure 1: ANTLR plugin installer

CS 211 Programming Practicum Spring 2017

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

TeenCoder : Java Programming (ISBN )

10 Java Collections; Equality, JUnit

Introduction to Programming in Turing. Input, Output, and Variables

Defining Classes and Methods

CS11 Advanced Java. Winter Lecture 2

Absolute C++ Walter Savitch

Introduction to Programming System Design CSCI 455x (4 Units)

Program Correctness and Efficiency. Chapter 2

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Tips from the experts: How to waste a lot of time on this assignment

Exceptions and Libraries

CSE 143: Computer Programming II Winter 2019 HW6: AnagramSolver (due Thursday, Feb 28, :30pm)

CSE 331 Final Exam 3/16/15 Sample Solution

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

CS3901 Intermediate Programming and Data Structures Winter 2008 (Q2 AY 08) Assignment #5. Due: noon Tuesday, 3 March 2008

Object Oriented Programming

CSE 142 Su 04 Computer Programming 1 - Java. Objects

, has the form T i1i 2 i m. = κ i1i 2 i m. x i1. 1 xi2 2 xim m (2)

CS 211 Programming Practicum Spring 2018

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

CSCI 2101 Java Style Guide

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

Programming II (CS300)

CS 201 Advanced Object-Oriented Programming Lab 5 - Sudoku, Part 1 Due: March 3/4, 11:30 PM

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

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

EXCEPTION HANDLING. Summer 2018

Computer Components. Software{ User Programs. Operating System. Hardware

LAT-TD-xxxxx-xx May 21, 2002

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

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

Programming Project 5: NYPD Motor Vehicle Collisions Analysis

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

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

CSE 143: Computer Programming II Summer 2017 HW5: Anagrams (due Thursday, August 3, :30pm)

CSE 331 Software Design & Implementation

EECS168 Exam 3 Review

Com S 227 Spring 2018 Assignment points Due Date: Thursday, September 27, 11:59 pm (midnight) "Late" deadline: Friday, September 28, 11:59 pm

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Programming II (CS300)

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

After completing this appendix, you will be able to:

Homework #10 due Monday, April 16, 10:00 PM

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Lab 5 : WordAnalyzer class

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

1 Lexical Considerations

III. Classes (Chap. 3)

Tips from the experts: How to waste a lot of time on this assignment

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

CMPSCI 187 / Spring 2015 Hanoi

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

A Fraction Class. Using a Fraction class, we can compute the above as: Assignment Objectives

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Lecture Notes on Contracts

Initial Coding Guidelines

Java Programming Tutorial 1

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

MULTI-ATTRIBUTE VALUE FUNCTION FOR ORDERING WEB PAGES 1. INTRODUCTION. 1.1 The Problem Considered

CMPSCI 187 / Spring 2015 Sorting Kata

Java: advanced object-oriented features

CSCI 200 Lab 3 Using and implementing sets

Lab #1: A Quick Introduction to the Eclipse IDE

SFU CMPT 379 Compilers Spring 2018 Milestone 1. Milestone due Friday, January 26, by 11:59 pm.

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

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

Using Eclipse Europa - A Tutorial

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

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

public static void negate2(list<integer> t)

Assertions. Assertions - Example

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

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Transcription:

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, postconditions and invariants Defining a meaningful tostring method. Java Background Arrays In this lab you will use arrays which work slightly differently in Java than in C++. Array declarations look like: int[] coeffs; This declares an array whose initial value is null. You then need to create the array by saying how many elements it should have: coeffs = new int[10]; This gives you an array with 10 integers, indexed from 0 to 9. If the variable is an instance variable, all elements of the array are initialized to 0. If it is a local variable, the elements are not initialized. You can combine the declaration and creation of the array as follows: int[] coeffs = new int[10]; An array is an object in Java. You can find out how big an array is by saying: coeffs.length Notice that there are no parentheses here. length is not a method. An interesting feature is that you can create arrays whose length is 0: coeffs = new int[0]; 1

This can be very useful. It is much easier to deal with 0-length arrays than null arrays in your code. For example, you can walk any array, even 0-length arrays, using something like: for (int i = 0; i < coeffs.length; i++) { // Do something } If coeffs is null rather than 0-length, this would not work. Instead, you would get a Null- PointerException. If you try to work with an array with an invalid index value, you will see the exception ArrayIndexOutOfBoundsException. This will happen if you use an index that is less than 0, an index >= the length of the array, or a negative size when you try to construct an array. Javadoc Comments The descriptions of classes and methods that you see when you link to API documentation for standard Java libraries is generated by a tool called javadoc. Javadoc generates this html documentation based on the contents of specially-formatted comments within your Java programs. For each method, javadoc allows you to provide general information about what the method does, a description of each parameter to the method, a description of the return result, and a description of each exception thrown. A javadoc comment is distinguished from other comments by enclosing the comments inside You place the javadoc comment for a method immediately before the declaration of the method. Within the comment, javadoc looks for specific tags to identify parameter comments, return value comments, and exception comments: @param <parameter-name> Parameter description, one for each parameter @return Return value description, omit if void Description of when thrown, one for each possible @exception <exception-name> exception Unfortunately, javadoc does not have explicit tags for preconditions or postconditions. Preconditions that pertain to a particular parameter should be included in the parameter description. Preconditions that depend on other things should be described in the general comments for the method. Postconditions that pertain to the return value should be described in the return value description. Postconditions that pertain to when exceptions are thrown should be provided with the exception descriptions. Other postconditions should be described in the general comments. An example should help clarify this. Here is what the javadoc comment for the Polynomial add method is: 2

Returns a polynomial by adding the parameter to this. Neither this nor the parameter are modified. @param q the polynomial to add to this. q should not be null. @return this + q @exception NullPointerException if q is null public Polynomial add (Polynomial q); Given comments like these for the entire class, javadoc creates a nicely-formatted Web page for us. This is the basics, but it is all you need to know for 95% of what you will do with javadoc. For more help with javadoc, please see Sun's documentation on Javadoc. Below are instructions on how to run javadoc from within Eclipse. Please refer to Sun's documentation if you wish to run javadoc from the command line instead. Java Assert Statements Java has support for assertion checking. Java does not distinguish between preconditions, postconditions, and invariants. Instead it provides one statement, an assert statement, and a compiler flag that either inserts assertion checking or turns it off. Thus, for each precondition that you want to check, you would add an assert statement at the beginning of the method and similarly for each postcondition, you would add an assert statement at the end of each method. For each invariant, you would need to add an assertion for that invariant at the beginning and end of each non-private method. Assertion checking can be a powerful assistant while developing code, but generally should be disabled when you are convinced the code works correctly and you want to let others use it. Let's assume that we have an implementation of wellformed for dense polynomials. Using the assert statement, we could write the DensePolynomial add method as: public Polynomial add (Polynomial q) { // Precondition assert q!= null : parameter is null ; // Invariant assert wellformed(); // Do the work // Invariant assert result.wellformed(); } return result; The first assert statement above contains an expression following a colon. This expression is printed out if the assertion fails. This can be helpful for debugging. If you leave it out and your code fails, you will get a stack trace that you can use to find the line of code where 3

the error occurred. It can be very helpful to use this feature to display the value of a variable or expression that is in error when an assertion fails. If assertion checking is enabled and an assertion is violated, Java will produce a stack trace identifying the location of the assertion failure. Liberal use of assertion checking is an excellent way to find errors close to where the problematic code actually is. To use assertion checking, you need to tell the compiler that it should treat your source code as being Java 1.4 or later. This may seem a bit odd, but the reason is that prior to 1.4, the word "assert" was not a keyword and since 1.4 it has been. As a result, source code written prior to 1.4 could have used the word "assert" as a variable name, method name, etc. while after 1.4 it cannot. So that programmers are not forced to rename all uses of "assert" in old code, you need to tell the compiler that you intend "assert" to be treated as a keyword by compiling with the flag "-source 1.4". By default, assertions are disabled at runtime to improve performance of the executing code. To enable assertion checking, you must pass the "-ea" argument to the Java virtual machine. See below for instructions on turning assertion checking on and off from within Eclipse. For more details on assertion checking in Java, please see Sun's documentation on assertion checking. Assignment Polynomials are a common type of mathematical function. A polynomial involving a single variable can be represented as an array of terms, where the index of the array identifies the degree for that term. For example, we could represent 3x 2 + 2x with an array, coeffs, containing three elements: coeffs[0] = 0 coeffs[1] = 2 coeffs[2] = 3 This representation works well in many, but not all, situations. This representation would not work if the polynomial contained negative exponents. It would also be inefficient for polynomials that have a high degree but only a few terms, such as x 1000 + 5x 50. For this assignment, I provide an interface called Polynomial. Your job is to define an implementation called DensePolynomial using the representation described above (and having the limitations listed above). You may find it helpful to define new private methods beyond those defined in the Polynomial interface, but you should not create any additional public methods and you should not modify the Polynomial interface in any way. When approaching this problem, you will need to address some specific questions in your design, among them: How should you represent the constant 0? Should you use arrays that are the minimum length needed for a polynomial or not? 4

As part of your implementation, you should be sure to practice what we have been discussing in class: preconditions, postconditions, representation invariants, and abstraction functions. Specifically, For each method, you should create a Javadoc-style comment that describes preconditions and postconditions. For each method, you should use a Java assert statement to check your preconditions, postconditions, and class invariants. You should implement a wellformed method to check the class invariant. For example, if you decide to keep your polynomial at its minimum size at all times, your wellformed method should check that you are really doing so. You should implement a tostring method to serve as the abstraction function. This method should display a polynomial in a standard mathematical way. Terms should be sorted by exponent, terms with a zero coefficient should not be printed, there should be at most one term printed per exponent. For example, the following is in canonical form: 2x^3 + 3x + 1 while these are not: 2x^3 + 1 + 3x 2x^3 + 0x^2 + 3x + 1 x^3 + x^3 + 3x + 1 You should write your implementation assuming any polynomial parameters that are passed in can be any subtype of Polynomial. What this means is that you should never downcast the Polynomial parameter that is passed to one of your methods to a Dense- Polynomial. You should write a main method that tests your implementation. To do this, I recommend that you use assert statements to verify that the output of an operation produces what you expect by comparing the value produced by tostring with a String literal that you expect it to be. For example, Polynomial p1 = new DensePolynomial (3, 2); assert p1.tostring().equals("3x^2") : p1; Eclipse Polynomial p2 = new DensePolynomial (0, 5); assert p2.tostring().equals("0") : p2; Polynomial p3 = p1.add(p2); assert p3.tostring().equals("3x^2") : p3; To do this assignment in Eclipse, create a project called Polynomial. Now, download Polynomial.java from the Web site. To import that file into your project, open the File menu and select Import... Then select File system and click the Next button. Select the directory where your file downloaded to using the Browse button. Then select the directory again (but don't click on the box) in the left panel Then click on the box next to Polynomial.java in the right panel. Set the folder to import into to be the src folder in your Polynomial project. Then click Finish. Now, we will set a preference so you get reasonable javadoc stub comments when you implement your new class. Open the Window menu and select Preferences. Select Java, then 5

Code Style, and finally Code Templates from the list of preferences. Now select Comments and then Overriding methods in the right panel. Click the Edit button. Change the comment to be a javadoc comment, that is, it should begin with rather than /. Erase the part that says (non-javadoc). Add a line to the comment. Click the Insert variable button and select tags. Now create your new class, DensePolyomial. Open the File menu, select New and then Class. Be sure the Source Folder is the src folder in your polynomial project, enter Dense- Polynomial in the name field. Click the Add button next to the interfaces box, and enter Polynomial. Under stubs, select main and inherited abstract methods. Then click the Finish button. The top right panel should now show an outline for your new class. There should be stub implementations of all the methods you need to define to implement the Polynomial interface. Running javadoc from within Eclipse Eclipse assists with creating javadoc comments. In particular, after entering the signature of a method, you can move the cursor to the line immediately preceding the method. Then type followed by the enter key. Eclipse will create a stub for your javadoc comment that includes the appropriate @param, @return, and @exception tags. To generate the javadoc html pages within Eclipse, select your project in the Package Explorer. Open the File menu and select Export. Select javadoc and click the Next button twice. Check the box for 1.4 source compatibility and click the Finish button. All the defaults are fine. This will create a doc directory within your project. If you double-click on doc, it will open to reveal lots of files. Find index.html and doubleclick on that. That should start a browser within Eclipse showing you the generated Web pages. Cool! Turning assertion checking on and off with Eclipse To have Eclipse compile your code with the "-source 1.4" argument, do the following. Open the Window menu and select Preferences. Open Java in the left column and select Compiler. Make sure "Compiler Compliance Level" is set to 1.4 or later. Make sure generated.class files compatibility is set to 1.4 or later and source compatibility is set to 1.4 or later. To have Eclipse run your code with the "-ea" argument, do the following. Run your program once using Run As Application. Quit your program. Open the Run menu and select Run Configurations... Select your run configuration, which should have a familiar looking name, from the list on the left. Click on the Arguments tab. In the VM Arguments area, enter -ea. Grading In addition to correctness and style, this assignment focuses on use of Javadoc as a way of documenting preconditions, postconditions, and invariants, the use of assertion checking to check these, and the use of wellformed and tostring methods. 6

Simplicity of design Javadoc comments Assertions wellformed tostring Style Correctness 10 points 15 points 15 points 10 points 10 points 15 points 25 points Turning in your work To turn in your work, create a jar file that contains your source code and the generated html documentation. Submit this on Ella. In Ella, use the text area to include any instructions I need to know to run your program. For example, tell me if it requires command-line arguments or the format for any input you expect from the user. The Polynomial Interface / The Polynomial interface adapted from Liskov, Program Development in Java, page 85. public interface Polynomial { Returns the degree of the polynomial. @return the largest exponent with a non-zero coefficient. If all terms have zero exponents, it returns 0. public int getdegree(); Returns the coefficient corresponding to the given exponent. Returns 0 if there is no term with that exponent in the polynomial. @param d the exponent whose coefficent is returned. @return the coefficient of the term of whose exponent is d. public int getcoeff (int d); @return true if the polynomial represents the zero constant public boolean iszero(); 7

Returns a polynomial by adding the parameter to this. Neither this nor the parameter are modified. @param q the polynomial to add to this. q should not be null. @return this + q @exception NullPointerException if q is null public Polynomial add (Polynomial q); Returns a polynomial by multiplying the parameter with this. Neither this nor the parameter are modified. q should not be null. @param q the polynomial to multiply with this @return this q @exception NullPointerException if q is null public Polynomial multiply (Polynomial q); Returns a polynomial by subtracting the parameter from this. Neither this nor the parameter are modified. @param q the polynomial to subtract from this. q should not be null. @return this - q @exception NullPointerException if q is null public Polynomial subtract (Polynomial q); Returns a polynomial by negating this. this is not modified. @return -this public Polynomial minus (); } Returns true if the object's class invariant holds @return true iff the class invariant holds public boolean wellformed (); 8