Chapter 3 (Horstmann’s Book) Guidelines for Class Design Hwajung Lee.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Building Bug-Free O-O Software: An Introduction to Design By Contract A presentation about Design By Contract and the Eiffel software development tool.
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
1 CSE 403 Design by Contract Reading: Pragmatic Programmer Ch. 4, Object-Oriented Design and Patterns, Ch. 3 (Horstmann) These lecture slides are copyright.
Practice Session 5 Java: Packages Collection Classes Iterators Generics Design by Contract Test Driven Development JUnit.
Java Review Interface, Casting, Generics, Iterator.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
The Java Assert Statement. 2 Assert A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates a particle’s.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
1 TCSS 360, Spring 2005 Lecture Notes Programming by Contract: Pre/Postconditions, Invariants and Assertions Relevant Reading: Object-Oriented Design and.
Class Design CSC 171 FALL 2004 LECTURE 11. READING Read Chapter 7 It’s abstract But it should help with project #1.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Information Hiding and Encapsulation
1 Class design guidelines. 2 Encapsulation Classes can be implemented many different ways –each has advantages & disadvantages –improvement/revision always.
Advanced Object Oriented Programming Chapter 3 & 4.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 3: Guidelines for.
Computer Science 340 Software Design & Testing Design By Contract.
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
1 Assertions. 2 assertions communicate assumptions about the state of the program, and stop processing if they turn out to be false very often comments.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
1 OPI Lecture 19 Interfaces & Design by Contract Kasper Østerbye Carsten Schuermann IT University Copenhagen.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
LinkedList Many slides from Horstmann modified by Dr V.
Guidelines for class design Horstmann ch Noter ch.1.1.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Chapter 3 Guidelines for Class Design. Objective of this chapter Have “bottom up point of view” Learn how to write a single class well.  The classes.
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Computer Science 209 Software Development Handing Errors and Creating Documentation.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Lect Chap 3 (cont.) 2/2. Chapter 3 The Importance of Encapsulation Even a simple class can benefit from different implementations Users are.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Written by: Dr. JJ Shepherd
The Java Assertion. 2 Assertion A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates the a particle’s.
CS 151: Object-Oriented Design September 17 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Reasoning and Design (and Assertions). How to Design Your Code The hard way: Just start coding. When something doesn’t work, code some more! The easier.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
ITEC324 Principle of CS III
Guidelines for Class Design
Logger, Assert and Invariants
CSE 374 Programming Concepts & Tools
CSC 480 Software Engineering
Java Programming Language
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
CMPE 135: Object-Oriented Analysis and Design February 21 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor:
Computer Science 340 Software Design & Testing
ITEC324 Principle of CS III
Presentation transcript:

Chapter 3 (Horstmann’s Book) Guidelines for Class Design Hwajung Lee

 Have “bottom up point of view”  Learn how to write a single class well.  The classes will  Be useful  Be reusable  Increased pride and satisfaction for you, the designer.

 Customers: Programmers using the class  Criteria: (5Cs)  Cohesion  Completeness  Convenience  Clarity  Consistency

 A class is an abstraction of a single concept. A class is cohesive if all of its methods are related to a single abstraction. Methods should be related to the single abstraction  Bad example: public class Mailbox { public addMessage(Message aMessage) {... } public Message getCurrentMessage() {... } public Message removeCurrentMessage() {... } public void processCommand(String command) {... }... }

 A class interface should support all operations that are a part of the abstraction that the class represents.  Potentially bad example: Date start = new Date(); // do some work Date end = new Date(); //How many milliseconds have elapsed?  No such operation in Date class  Does it fall outside the responsibility?  After all, we have before, after, getTime

 A class should be convenient to use. A good interface makes all tasks possible... and common tasks simple.  Bad example: Reading from System.in BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); Name = in.readLine();  Why didn't System.in have a readLine method?

 A class interface should be clear to understand to programmers. Confused programmers write buggy code  Bad example: Removing elements from LinkedList LinkedList countries = new LinkedList(); countries.add("A"); countries.add("B"); countries.add("C"); ListIterator iterator = countries.listIterator(); while (iterator.hasNext()) System.out.println(iterator.next());

 Iterator between elements is like blinking cursor in a word processor. Thus, if X is added before B: ListIterator iterator = countries.listIterator(); // |ABC iterator.next(); // A|BC iterator.add("France"); // AX|BC  Then, to remove first two elements, you can't just "backspace." The remove() method does not remove element to the left of the iterator.  Will the following work? iterator.remove(); //A|BC iterator.remove(); //|BC

 In fact, void remove() from API documentation says: Removes from the list the last element that was returned by next or previous. This call can only be made once per call to next or previous. It can be made only if add has not been called after the last call to next or previous. void remove()  Huh?

 The operations in a class should be consistent with each other with respect to  names  parameters  return values  behavior  Bad example: new GregorianCalendar(year, month - 1, day)  Why is month 0-based?

 Bad example:  String class s.equals(t) or s.equalsIgnoreCase(t)  But boolean regionMatches(int toffset, String other, int ooffset, int len) boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)  Why not regionMatchesIgnoreCase?

 Cohesion  Completeness  Convenience  Clarity  Consistency

 A method should only use objects that are  instance fields of its class  parameters  objects that it constructs with new  A method shouldn't use an object that is returned from a method call

 Side effect: change to another object  Explicit parameters  Avoid side effects--they confuse users  Good example, no side effect: a.addAll(b); mutates a but not b * Note: Accessor is a getter and Mutator is a setter.

 References to immutable objects can be freely shared. Don't share mutable references  Example: Class Employee {... public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDate() { return hireDate; } private String name; private double salary; private Date hireDate; }

 Pitfall: Employee harry =...; Date d = harry.getHireDate(); d.setTime(t); // changes Harry's state!!!

 Remedy: Use clone public Date getHireDate() { return (Date)hireDate.clone(); }

 Good idea to mark immutable instance fields as final private final int day;  final object reference can still refer to mutating object private final ArrayList elements;  elements can't refer to another array list  The contents of the array list can change

 Spell out responsibilities  of caller  of implementer  Increase reliability  Increase efficiency

 We will look through the ideas on  Preconditions  Postconditions  Exceptions in the Contract  Class Invariants  Assertions

 A precondition of a method  is a condition that must be fulfilled before the method may be called.  Is a condition that the method caller must fulfill.

 Why do we need to define preconditions?  Excessive error checking is costly  Returning dummy values can complicate testing  Contract metaphor  Service provider must specify preconditions ▪ If precondition is fulfilled, service provider must work correctly. Otherwise, service provider can do anything  When precondition fails, service provider may  throw exception  return false answer  corrupt data

 Example: /** Remove message at the message at the size() > 0 */ Message removeFirst() { return (Message)elements.remove(0); }

 (Ex) What should happen if a programmer attempts to remove a message from an empty queue?  What is better? ▪ MessageQueue can declare this as an error ▪ MessageQueue can tolerate call and return dummy value

 A postcondition of a method  is a condition that holds after the method has completed  is a conditions that the service provider (the method developer) guarantees  In Java doc, you can to represent a postcondition. Example: add() size() > 0  Postcondition of one call can imply precondition of another: q.add(m1); m2 = q.remove();

 Exception throw is not an error. It is a part of the contract  Example: IllegalArgumentException if queue is empty */ public Message removeFirst() { if (count == 0) throw new IllegalArgumentException(); Message r = elements[head];... }

 A class invariant is a logical condition that is  true after every constructor  preserved by every mutator (if it's true before the call, it's again true afterwards)  Useful for checking validity of operations

 Example: Circular array queue (Ch2/mail/MessageQueue.java)Ch2/mail/MessageQueue.java 0 <= head && head < elements.length  First check it's true for constructor ▪ Sets head = 0 ▪ Need precondition size() >= 0  Check mutators. Start with removeFirst() ▪ Sets head new = (head old + 1) % elements.length ▪ We know head old + 1> 0 (Why?)  % operator property: 0 <= head new && head new < elements.length  What's the use of a class invariant?  Every array access of the form element[head] is legal!

 An assertions:  is a condition that a programmer expects to be true  is a mechanism for warning programmers ▪ Useful for warning programmers about precondition failure  can be turned off after testing  Syntax: assert condition; assert condition : explanation;  Throws AssertionError if condition false and checking enabled

 Example: public Message removeFirst() { assert count > 0 : "violated precondition size() > 0"; Message r = elements[head];... }  How to execute the assertion: During testing, run with java -enableassertions MyProg or Java -ea MyProg

 Unit test = test of a single class  How to test?  Design test cases during implementation  Run tests after every implementation change  When you find a bug, add a test case that catches it  Download the JUnit tool  

 Test class name = tested class name + Test  A name of a test method starts with test  Example: import junit.framework.*; public class DayTest extends TestCase { public void testAdd() {... } public void testDaysBetween() {... }... }

 Each test case ends with assertion. Test framework catches assertion failures  Example: public void testAdd() { Day d1 = new Day(1970, 1, 1); int n = 1000; Day d2 = d1.addDays(n); assert d2.daysFrom(d1) == n; }

 Day.java Day.java  DayTest.java DayTest.java  Compiling javac –classpath.:junit.jar DayTest.java  Run java –classpath.:junit.jar –ea junit.swingui.TestRunner DayTest

 public: a field, method, or class that is accessible to every class.  protected: a field, method, or class that is accessible to the class itself, subclasses, and all classes in the same package or directory.  private: a field or method that is accessible only to the class in which it is defined. Note that a class can not be declared private as a whole.