Utilities (Part 3) Implementing static features

Similar documents
Utilities (Part 2) Implementing static features

Advanced Object Oriented Programming EECS2030Z

Advanced Object Oriented Programming EECS2030E

Advanced Object Oriented Programming EECS2030Z

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

Documenting, Using, and Testing Utility Classes

public static void negate2(list<integer> t)

Exception Handling. 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:

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

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

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

Text User Interfaces. Keyboard IO plus

Documenting Java Code. Javadoc: The Tool and the Legend

Documenting Advanced Programming Techniques

Assertions, pre/postconditions

16-Dec-10. Consider the following method:

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

COMP 110 Programming Exercise: Simulation of the Game of Craps

Example Program. public class ComputeArea {

CS111: PROGRAMMING LANGUAGE II

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Laboratory. of Java and. specifically. On the line the method. does, e.g.: /** Obtains. of the die.

Write for your audience

Assignment 1 due Monday at 11:59pm

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

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

Documentation Requirements Computer Science 2334 Spring 2016

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

EECS2030 Week 7 worksheet Tue Feb 28, 2017

Inheritance (Part 5) Odds and ends

Chapter 4 Defining Classes I

Data Abstraction and Specification of ADTs

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSCI 201L Written Exam #1 Fall % of course grade

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

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Programming Syntax and Style. David Greenstein Monta Vista High School

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Chapter 6 Lab Classes and Objects

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Chapter Two Bonus Lesson: JavaDoc

Midterms Save the Dates!

QueueBlock, ReversalADT, LinkedList,CustomerAccount, not MaintainCustomerData

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

1 Shyam sir JAVA Notes

Composite Pattern - Shapes Example - Java Sourcecode

Introduction to the Java Basics: Control Flow Statements

CS112 Lecture: Defining Instantiable Classes

CSE wi Midterm Exam 2/8/18 Sample Solution

Coding Guidelines. Introduction. General Points. Avoid redundant initialization/assignment

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

COMP 1210 Documentation Guidelines Page 1 of 7. Class documentation (Chapter 1):

2.8. Decision Making: Equality and Relational Operators

Review: Array Initializer Lists

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Computer Science II (20082) Week 1: Review and Inheritance

Midterm Exam CS 251, Intermediate Programming March 6, 2015

CSE 143 SAMPLE MIDTERM

CSC 1351: Quiz 6: Sort and Search

YEAHtzee. Tuesday Nov Aamnah Khalid and Peter Maldonado

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

TeenCoder : Java Programming (ISBN )

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

CSE331 Winter 2014, Midterm Examination February 12, 2014

JAVA Programming Language Homework I - OO concept

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Building a Java First-Person Shooter

Chapter 6 Lab Classes and Objects

Full file at Chapter 2 - Inheritance and Exception Handling

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

H212 Introduction to Software Systems Honors

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Project #1 Computer Science 2334 Fall 2008

CSCD 326 Data Structures I Queues

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Session 04 - Object-Oriented Programming 1 Self-Assessment

Background: This programming assignment focuses on implementation and usage of a graph data structure.

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

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

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS1083 Week 2: Arrays, ArrayList

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Computer Programming, I. Laboratory Manual. Final Exam Solution

CSCI 201L Written Exam #1 Fall % of course grade

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

( &% class MyClass { }

Documentation (and midterm review)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Title. Java Just in Time. John Latham. October 25, October 25, 2017 Java Just in Time - John Latham Page 1(0/0)

Verifying and Documenting ADTs: Javadoc, Java Assertions and JUnits

Arrays. Chapter Arrays What is an Array?

CSE 331 Midterm Exam Sample Solution 2/18/15

CS251L REVIEW Derek Trumbo UNM

Transcription:

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 of the Yahtzee class so far private constructor to prevent instantiation public constant field that represents the number of dice public method that determines if a list of dice represents a roll of three-of-a-kind 3

import java.util.collections; import java.util.arraylist; import java.util.list; public class Yahtzee { private Yahtzee() { // private and empty by design public static final int NUMBER_OF_DICE = 5; public static boolean isthreeofakind(list<die> dice) { List<Die> copy = new ArrayList<Die>(dice); Collections.sort(copy); boolean result = copy.get(0).getvalue() == copy.get(2).getvalue() copy.get(1).getvalue() == copy.get(3).getvalue() copy.get(2).getvalue() == copy.get(4).getvalue(); return result; 4

Yahtzee client: Not enough dice consider the following client program that tries to use our utility class using fewer than 5 dice 5

import java.util.arraylist; import java.util.list; public class YahtzeeClient { public static void main(string[] args) { final int N_DICE = 3; List<Die> dice = new ArrayList<Die>(); for (int i = 0; i < N_DICE; i++) { dice.add(new Die()); // NOT ENOUGH DICE System.out.print("Dice: " + dice.get(0).getvalue()); for (int i = 1; i < N_DICE; i++) { System.out.print(", " + dice.get(i).getvalue()); System.out.println(); boolean isthree = Yahtzee.isThreeOfAKind(dice); System.out.println("three of a kind?: " + isthree); 6

Yahtzee client: Not enough dice the output of the program is: Dice: 5, 4, 4 Exception in thread "main" java.lang.indexoutofboundsexception: Index: 3, Size: 3 at java.util.arraylist.rangecheck(unknown Source) at java.util.arraylist.get(unknown Source) at Yahtzee.isThreeOfAKind(Yahtzee.java:38) at YahtzeeClient.main(YahtzeeClient.java:19) 7

Yahtzee client: Too many dice consider the following client program that tries to use our utility class using more than 5 dice 8

import java.util.arraylist; import java.util.list; public class YahtzeeClient { public static void main(string[] args) { final int N_DICE = 7; List<Die> dice = new ArrayList<Die>(); for (int i = 0; i < N_DICE; i++) { dice.add(new Die()); // TOO MANY DICE System.out.print("Dice: " + dice.get(0).getvalue()); for (int i = 1; i < N_DICE; i++) { System.out.print(", " + dice.get(i).getvalue()); System.out.println(); boolean isthree = Yahtzee.isThreeOfAKind(dice); System.out.println("three of a kind?: " + isthree); 9

Yahtzee client: Too many dice the program seems to work sometimes: Dice: 3, 2, 2, 5, 2, 4, 1 three of a kind?: true but fails sometimes: Dice: 6, 3, 3, 6, 6, 5, 5 three of a kind?: false 10

Preconditions and postconditions recall the meaning of method pre- and postconditions precondition a condition that the client must ensure is true immediately before a method is invoked postcondtion a condition that the method must ensure is true immediately after the method is invoked 11

Who is responsible? our method isthreeofakind clearly fails if the client uses the wrong number of dice we say that the method cannot satisfy its postcondition if the client uses the wrong number of dice as the implementer, we should advertise this fact as part of the method API as the implementer, we also need to decide who is responsible if a client uses the wrong number of dice 12

Client is responsible: Preconditions as the implementer, we can choose to make the client responsible for errors caused by using the wrong number of dice we do this by stating in the API that the method has a precondition we'll see exactly how to do this in Java shortly 13

Client is responsible: Preconditions recall that a method precondition is a condition that the client must ensure is true immediately before invoking a method if the precondition is not true, then the client has no guarantees of what the method will do for utility class methods, preconditions are conditions on the values of the arguments passed to the method e.g., in our current implementation of isthreeofakind the number of dice must be 5 14

Implementer is responsible: Validation as the implementer, we can choose to specify precisely what happens if the method cannot satisfy its postcondition given the arguments provided by the client this often requires that the method implementation validate its parameters e.g., isthreeofakind would have to check that the client has used a list argument containing 5 dice 15

public static boolean isthreeofakind(list<die> dice) { if (dice.size()!= Yahtzee.NUMBER_OF_DICE) { throw new IllegalArgumentException("wrong number of dice: " + dice.size()); List<Die> copy = new ArrayList<Die>(dice); Collections.sort(copy); boolean result = copy.get(0).getvalue() == copy.get(2).getvalue() return result; copy.get(1).getvalue() == copy.get(3).getvalue() copy.get(2).getvalue() == copy.get(4).getvalue(); 16

Documenting documenting code was not a new idea when Java was invented however, Java was the first major language to embed documentation in the code and extract the documentation into readable electronic APIs the tool that generates API documents from comments embedded in the code is called Javadoc 17

Documenting Javadoc processes doc comments that immediately precede a class, attribute, constructor or method declaration doc comments delimited by /** and */ doc comment written in HTML and made up of two parts 1. a description first sentence of description gets copied to the summary section only one description block; can use <p> to create separate paragraphs 2. block tags begin with @ (@param, @return, @throws and many others) @pre. is a non-standard (custom tag used in EECS1030) for documenting preconditions 18

Method documentation example Eclipse will generate an empty Javadoc comment for you if you right-click on the method header and choose Source Generate Element Comment /** * * @param dice * @return */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 19

Method documentation example The first sentence of the documentation should be short summary of the method; this sentence appears in the method summary section. /** * Returns true if the list dice contains a three-of-a-kind. * * @param dice * @return */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 20

Method documentation example If you want separate paragraphs in your documentation, you need to use the html paragraph tag <p> to start a new paragraph. /** * Returns true if the list dice contains a three-of-a-kind. * * <p>a three of a kind is defined as at least three dice having * the same value. * * @param dice * @return */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 21

Method documentation example You should provide a brief description of each parameter. /** * Returns true if the list dice contains a three-of-a-kind. * * <p>a three of a kind is defined as at least three dice having * the same value. * * @param dice list of dice representing the roll * @return */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 22

Method documentation example Provide a brief description of the return value if the return type is not void. This description often describes a postcondition of the method. /** * Returns true if the list dice contains a three-of-a-kind. * * <p>a three of a kind is defined as at least three dice having * the same value. * * @param dice list of dice representing the roll * @return true if dice contains three-of-a-kind, false otherwise */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 23

Method documentation example if a method has one or more preconditions, you should use the EECS1011 specific @pre. tag to document them e.g., if we were documenting our original version of isthreeofakind we would use an @pre. tag to document the precondition dice.size() == Yahtzee.NUMBER_OF_DICE 24

Method documentation example Describe any preconditions using the EECS1011 specific @pre. tag. /** * Returns true if the list dice contains a three-of-a-kind. * * <p>a three of a kind is defined as at least three dice having * the same value. * * @param dice list of dice representing the roll * @pre. dice.size() == Yahtzee.NUMBER_OF_DICE * @return true if dice contains three-of-a-kind, false otherwise */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 25

Method documentation example if a method throws an exception (perhaps as a result of failing to validate a parameter) then you should use the @throws tag to document the exception e.g., if we were documenting our second version of isthreeofakind we would use the @throws tag to document the exception that is thrown if dice.size()!= Yahtzee.NUMBER_OF_DICE 26

Method documentation example Use a @throws tag to document each exception that might be thrown by your method. /** * Returns true if the list dice contains a three-of-a-kind. * * <p>a three of a kind is defined as at least three dice having * the same value. * * @param dice list of dice representing the roll * @return true if dice contains three-of-a-kind, false otherwise * @throws IllegalArgumentException if dice.size()!= Yahtzee.NUMBER_OF_DICE */ public static boolean isthreeofakind(list<die> dice) { // implementation not shown 27

Documenting fields all public fields should have a Javadoc comment describing the field Eclipse will generate an empty Javadoc comment for you if you right-click on the field declaration and choose Source Generate Element Comment 28

Field documentation example public class Yahtzee { /** * The number of six-sided dice used in a standard game * of Yahtzee. */ public static final int NUMBER_OF_DICE = 5; 29

Documenting classes all classes should contain a description of the class Eclipse will generate an empty Javadoc comment for you if you right-click on the field declaration and choose Source Generate Element Comment the description of a class can be quite detailed for sophisticated classes e.g., java.lang.string you should describe the purpose of the class and any other information that might be important to clients but normally you do not describe the implementation details of the class 30

Class documentation example /** * A utility class that encodes a subset of the rules for * the game Yahtzee. * * <p>a description of the scoring categories can be * found on the <a href="http://en.wikipedia.org/wiki/yahtzee"> * Yahtzee Wikipedia web page</a>. * * @author EECS1011E_W15 * */ public class Yahtzee { // implementation not shown 31

javadoc Documentation Oracle's how-to page http://www.oracle.com/technetwork/articles/java/index- 137868.html also see the examples in the course notes 32