CS 151: Object-Oriented Design September 17 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak.

Slides:



Advertisements
Similar presentations
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Advertisements

Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 3 (Horstmann’s Book) Guidelines for Class Design Hwajung Lee.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Road Map Introduction to object oriented programming. Classes
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design Lecture 6, Tue Jan
1 Class design guidelines. 2 Encapsulation Classes can be implemented many different ways –each has advantages & disadvantages –improvement/revision always.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 9 Thinking in Objects.
Advanced Object Oriented Programming Chapter 3 & 4.
CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 3: Guidelines for.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 3 Introduction to Collections – Stacks Modified
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 10 Thinking in Objects.
CS 46B: Introduction to Data Structures June 16 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
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,
CS 151: Object-Oriented Design October 24 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Guidelines for class design Horstmann ch Noter ch.1.1.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
CS 153: Concepts of Compiler Design August 26 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
10-Nov-15 Java Object Oriented Programming What is it?
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 151: Object-Oriented Design September 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
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.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS 151: Object-Oriented Design October 15 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Object-Oriented Principles Applications to Programming.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Lect Chap 3 (cont.) 2/2. Chapter 3 The Importance of Encapsulation Even a simple class can benefit from different implementations Users are.
Introduction to Objects and Encapsulation Computer Science 4 Mr. Gerb Reference: Objective: Understand Encapsulation and abstract data types.
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
CS 151: Object-Oriented Design December 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
ITEC324 Principle of CS III
Guidelines for Class Design
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
CS 153: Concepts of Compiler Design August 29 Class Meeting
CMPE 135: Object-Oriented Analysis and Design September 14 Class Meeting Department of Computer Engineering San Jose State University Fall 2017 Instructor:
Chapter 10 Thinking in Objects
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Chapter 9 Thinking in Objects
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Object initialization: constructors
CMPE 152: Compiler Design August 23 Class Meeting
Chapter 9 Thinking in Objects
Outline Anatomy of a Class Encapsulation Anatomy of a Method
CMPE 152: Compiler Design January 29 Class Meeting
Chapter 9 Objects and Classes
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:
CMPE 135 Object-Oriented Analysis and Design March 7 Class Meeting
ITEC324 Principle of CS III
CS 151: Object-Oriented Design October 8 Class Meeting
CSG2H3 Object Oriented Programming
CMPE 152: Compiler Design August 27 Class Meeting
Presentation transcript:

CS 151: Object-Oriented Design September 17 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 2 CS Graduates’ Mid-Career Salaries  See /best-schools-by-major/computer-science for some surprising news about Computer Science graduates from San Jose State! _ /best-schools-by-major/computer-science

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 3 The Importance of Encapsulation  We saw three different implementations of the Day class.  Each version presented the same public interface. Encapsulation hides the implementation details.  Principles: A class should expose as few public fields and public methods as possible. All other fields and methods should be hidden from class users (i.e., other programmers) by making them private.  Supports reliability and flexibility. _

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 4 Accessors and Mutators  Java naming convention: For a private instance field named myData of type T Conventional accessor method (AKA getter): Conventional mutator method (AKA setter):  In most cases, the fields of a class should be made private and users of the class should only use the getters and setters. _ public T getMyData() public void setMyData(T value)

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 5 Accessors and Mutators  An object’s field values together constitute the current state of the object. A getter method reads the object state without changing it. A setter method can change the object state.  Don’t necessarily provide a setter for every field. For some classes, setters can be dangerous! _

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 6 Dangerous Setter Example: The Day Class  Recall that the Day class has fields year, month, day. Should there be setter methods setYear(int year), setMonth(int month), and setDay(int day) ?  Suppose that  Now we want to move the deadline a month:  But since there isn’t a February 31, the GregorianCalendar class sets the date instead to March 3. Surprise! Day deadline = new Day(2014, 1, 31); deadline.setMonth(2);

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 7 Dangerous Setter Example: The Day Class  Now suppose we just want to move the deadline one day, from January 31 to February 1: Surprise! The deadline is set instead to March 1. How did that happen?  Should we always set the date first? Surprise! The result is not April 30! What is it instead?  April 2 deadline.setMonth(2); deadline.setDay(1); Day deadline = new Day(2014, 2, 1); deadline.setDate(30); deadline.setMonth(4);

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 8 No Surprises!  Good software design has few, if any, surprises. Surprises can lead to serious programming errors. _

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 9 Immutable Classes  When you create an instance using a constructor, you also set the object’s initial state.  A class is immutable if after you create an instance using a constructor, you cannot change the state. Example: The standard Java String class is immutable.  After you create a string, you cannot change its value.  Calls to string methods such as substring() and string concatenation using + actually create new string objects.  This can cause many extra objects to be created at run time.  How can you design an immutable class? Make all the fields private. Provide getters only, no setters.

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 10 Sharing References to Mutable Objects  You have to be extra careful if your program passes around references to mutable objects. If a class contains a field of a mutable type, you might change the state of an object that you thought was immutable.

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 11 Sharing References to Mutable Objects  Example: Consider an Employee class that contains the employee’s social security number and birthdate. The social security number and birthdate of an employee should not change. Therefore, you want Employee objects to be immutable. class Employee { private String ssn; private Calendar birthdate; public String getSsn() { return ssn; } public Calendar getBirthdate() { return birthdate; } }

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 12 Sharing References to Mutable Objects  Dangerous getter! Solution: Method getBirthdate() should return a reference to a clone of the employee birthdate to protect the birthdate object that’s referenced by the employee object.  Dangerous constructor! Solution: The constructor should create a clone of the Calendar value that’s passed in and store the clone into the object. Calendar bd = employee.getBirthdate(); bd.set(Calendar.YEAR, 2000); Calendar bd = new GregorianCalendar(1975, 2, 20); Employee e = new Employee(" ", bd); bd.set(Calendar.YEAR, 2000);

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 13 Final Fields  Good programming practice: Declare immutable fields of a class to be final. Example:  The value of a final field cannot change after the object has been constructed. Field birthdate cannot be changed to refer to another birthdate object. class Employee { private final String ssn; private final Calendar birthdate; public String getSsn() { return ssn; } public Calendar getBirthdate() { return birthdate; } }

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 14 Final Fields  However, if a final field refers to a mutable object, that mutable object can still change! _ class Employee { private final String ssn; private final Calendar birthdate; public String getSsn() { return ssn; } public Calendar getBirthdate() { return birthdate; } }

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 15 Separating Accessors and Mutators  If we call a method to access an object, we don't expect the object to mutate. Example of a violation: Method next() returns the current token and advances the cursor of the scanner object. What if you want to read the current token again?  Rule of thumb: Mutator methods should return void. Scanner in =...; String s = in.next(); String getCurrent(); void next();

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 16 Separating Accessors and Mutators  Refined rule of thumb: A mutator method can return a value as a convenience, provided there is an accessor method that returns the same value without changing the object’s state. String getCurrent(); String next(); // returns the current token // for your convenience

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 17 Side Effects  A side effect is a change to an object’s state due to a method call.  Nasty side effects are unexpected by the programmer.  Examples: Calling a getter method changes the value of some object field. A method call changes the value of an actual parameter (a parameter that’s passed by the call). A method call changes a global value, such as a static object. The setter methods of the GregorianCalendar class.  Lots of surprises there! _

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 18 Example Side Effect  Basic Date formatting:  Advanced: Parse multiple dates in the string. Side effect: Method parse() updates parameter position to the string index of the first character after the date.  A better design: Add a position field to the formatter state. SimpleDateFormat formatter =...; String dateString = "January 11, 2012"; Date d = formatter.parse(dateString); FieldPosition position =...; Date d = formatter.parse(dateString, position);

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 19 The Law of Demeter  The law states that a method should only use: Instance fields of its class Parameters Objects that it constructs with new  To obey this law: A method should never return a reference to an object that is part of its internal representation. A class should have sole responsibility to interact with objects that are part of its internal representation. More a Rule of Thumb than a hard law.  The law enables you to modify the internal structure of a class without modifying its public interface. Encapsulation!

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 20 How Good is an Interface?  Who is the user of a class that you write? Other programmers Perhaps you yourself, later!  Class designer priorities Efficient algorithm Convenient coding etc.  Class user priorities Easy to use Don’t have to understand the implementation etc.  Is there a “conflict of interest” if you’re both the class designer and the class user? Can you make the right engineering tradeoffs?

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 21 Cohesion  A cohesive class implements a single abstraction or responsibility.  Methods should be related to the single abstraction. An example of a badly designed class: public class Mailbox { public addMessage(Message aMessage) {... } public Message getCurrentMessage() {... } public Message removeCurrentMessage() {... } public void processCommand(String command) {... }... } Method processCommand() doesn’t belong.  Delegate command processing to another class.

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 22 Completeness  Support operations for a well-defined abstraction.  A potentially bad example: The Date class: How many milliseconds have elapsed?  No such operation in the Date class. Does it fall outside the responsibility?  After all, we have before(), after(), getTime()  If you encounter an incomplete class: Negotiate with the class designer. Fill in what’s missing with a subclass. Date start = new Date(); // do some work Date end = new Date();

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 23 Convenience  A good interface makes all tasks possible and common tasks simple.  A bad example from before Java 5.0: Reading lines of text from System.in Why doesn't System.in have a readLine() method?  After all, System.out has println(). The new Scanner class fixes this inconvenience. _ BufferedReader in = new BufferedReader( new InputStreamReader(System.in));

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 24 Clarity  Confused programmers write buggy code.  A bad example: Removing elements from a linked list.  Reminder: The standard LinkedList class:  Iterate through the list: LinkedList letters = new LinkedList (); letters.add("A"); letters.add("B"); letters.add("C"); ListIterator iterator = letters.listIterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 25 Clarity  The iterator sits between elements, like the blinking caret in a word processor.  Method add() adds an element to the left of the iterator, like in a word processor. Add X before B :  However, method remove() is not intuitive. Both calls are illegal! ListIterator iterator = letters.listIterator(); // |ABC iterator.next(); // A|BC iterator.add("X"); // AX|BC // This is NOT how it works! iterator.remove(); // A|BC iterator.remove(); // |BC

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 26 Clarity  According to the Java API documentation: In other words, to remove the two elements, you have to first jump over each element one at a time and then remove the one you jumped over immediately afterwards. _ 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().

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 27 Consistency  Related features of a class should have matching names parameters return values behavior  A bad example: Why is month 0-based? _ new GregorianCalendar(year, month - 1, day)

SJSU Dept. of Computer Science Fall 2013: September 17 CS 151: Object-Oriented Design © R. Mak 28 Consistency  Another bad example: Java’s String class:  But:  Why not method regionMatchesIgnoreCase() ? _ s.equals(t) s.equalsIgnoreCase(t) boolean regionMatches(int toffset, String other, int ooffset, int len) boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)