Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

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

3 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. _

4 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)

5 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! _

6 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);

7 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);

8 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. _

9 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.

10 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.

11 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; } }

12 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("123-45-6789", bd); bd.set(Calendar.YEAR, 2000);

13 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; } }

14 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; } }

15 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();

16 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

17 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! _

18 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);

19 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!

20 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?

21 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.

22 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();

23 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));

24 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()); }

25 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

26 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().

27 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)

28 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)


Download ppt "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."

Similar presentations


Ads by Google