Object-oriented programming and design 1 Object Identity = vs. == copying objects Value Object ValueWithHistory.

Slides:



Advertisements
Similar presentations
Stack & Queues COP 3502.
Advertisements

ACM/JETT Workshop - August 4-5, Classes, Objects, Equality and Cloning.
Intermediate Code Generation
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Smalltalk Coding Patterns mostly from Smalltalk Best Practice Patterns Kent Beck Prentice-Hall, 1997.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Lists Introduction to Computing Science and Programming I.
Stéphane Ducasse«ChapterNr».1 Arthur Riel Design Heuristics from Object-Oriented Design Heuristics by Arthur Riel Read the Heuristics… –Find reasons why.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
03G-1 Everything is an Object Examining builtin classes All these are classes in Little Smalltalk:  Object  Class  Method  Block  Boolean True False.
Squeak Collections The Squeak collection hierarchy. Some collection operators. Working with collections. For-loops.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Object-oriented programming and design 1 Smalltalk in a Nutshell Objects & classes Messages & methods Inheritance & metaclasses.
Stéphane Ducasse«ChapterNr».1 Basic Objects, Conditionals and Loops Booleans Basic Loops Overview of the Collection hierarchy— more than 80 classes: (Bag,
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS212: Object Oriented Analysis and Design Lecture 4: Objects and Classes - I.
3E-1 Collections in Squeak What are they? Kinds of collections. Basic Operations. Usage of Inheritance in the Collections Library. Roman numbers example.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Encapsulation and Data Abstraction Testing Applications in Smalltalk.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
C++ STL CSCI 3110.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Recap Visual Perception and Data Visualization Types of Information Display Examples of Diagrams used for Data Display Planning Requirement for Data Visualization.
CIT 590 Intro to Programming Lecture 5 – completing lists.
Class Examples (Simple, Airplane, Queue, Pile) Copy vs. Clone.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Data Structures & Algorithms
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
Lecture 04 – Models of memory Mutable and immutable data.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
XP New Perspectives on XML, 2 nd Edition Tutorial 7 1 TUTORIAL 7 CREATING A COMPUTATIONAL STYLESHEET.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Object-Oriented Design.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Data Structures Intro2CS – week Stack ADT (Abstract Data Type) A container with 3 basic actions: – push(item) – pop() – is_empty() Semantics: –
S.Ducasse 1 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface.
CS314 – Section 5 Recitation 9
Yan Shi CS/SE 2630 Lecture Notes
Review Array Array Elements Accessing array elements
Week 3 - Friday CS221.
ENEE150 Discussion 13 Section 0101 Adam Wang.
Java Review: Reference Types
Namespaces, Scopes, Access privileges
CIS16 Application Development and Programming using Visual Basic.net
Object Oriented Programming in java
Classes and Objects.
Starting Out with Programming Logic & Design
ArrayLists 22-Feb-19.
Lecture Set 9 Arrays, Collections, and Repetition
Presentation transcript:

Object-oriented programming and design 1 Object Identity = vs. == copying objects Value Object ValueWithHistory

Object-oriented programming and design 2 Identity “I’ll take the same thing he is having.” Objects have identity. Their state changes, but their identity doesn’t change. You can change the value of an object, but a 3 is always 3.

Object-oriented programming and design 3 Object Protocol Operations understood by all objects: == anObjectidentity - same object = anObjectequality - same value ~~ anObjectdifferent objects ~= anObjectdifferent values

Object-oriented programming and design 4 Equality vs. Identity Equality is user defined. = anObject ^self == anObject Identity is system defined. == anObject

Object-oriented programming and design 5 Equality (Date newDay: 40 year: 1995) == (Date newDay: 40 year: 1995) is false, because they are physically two distinct objects. However, they represent the same value, so they are equal.

Object-oriented programming and design 6 Implementation of Identity Each object has its own region of memory. “Object ID” is essentially a pointer. Variable contains object ID, not the space of an object. “Passing an object as an argument” means passing the object ID. -- tests for pointers being equal.

Object-oriented programming and design 7 New Objects A new object is different from any existing object. X new == X new is almost always false. “Rectangle new = Rectangle new” is true.

Object-oriented programming and design 8 Sharing Invoice name “Ann Jones” Oct. 3, 2005 Oct. 4, 2005 “Ann Jones” “Joe Smith” name date name date

Object-oriented programming and design 9 Sharing Sharing saves space. Sharing makes changes to one object visible to another. Sharing is always safe when objects are immutable.

Object-oriented programming and design 10 What is the value of? (Point x: 3 y: 17) == (Point x: 3 y: 17) (Point x: 3 y: 17) = (Point x: 3 y: 17) 'this is a string' == 'this is a string' #aSymbol == #aSymbol

Object-oriented programming and design 11 Value Objects Some objects (numbers, symbols, Military ranks) never change state. A value object is an object that is used like a value. l Initialize variables when it is created and never change them afterwards. l Define =

Object-oriented programming and design 12 Value Objects Classes that represent special values in your domain (SocialSecurityIdentifier, Address, MusicalNote, DayOfWeek, Money) The only methods that assign to instance variables are initialization methods. Only instance creation methods should call initialization methods.

Object-oriented programming and design 13 Why Value Objects? Reveal intention Check consistency (dynamic type check) Better printing / input Disadvantages More classes

Object-oriented programming and design 14 Information Hiding An employee’s transactions are entirely hidden from clients. To add a transaction, use postTransaction: There is no way to access transactions outside Employee.

Object-oriented programming and design 15 Information Hiding Suppose you want to iterate over transactions of an employee. Alternative 1 1) Add #transactions method 2) anEmployee transactions do:

Object-oriented programming and design 16 Violating Information Hiding An accessing method discloses information. anEmployee transactions add: (Paycheck new) anEmployee transactions remove Very dangerous!

Object-oriented programming and design 17 Information Hiding Alternative 2 transactionsDo: aBlock transaction do: aBlock Alternative 3 transactions ^transactions copy

Object-oriented programming and design 18 Copying "shallow copy" -- copy object, but not contents of object "deep copy" -- copy object and contents of object, recursively (usually VERY selectively) Copying is usually shallow copying.

Object-oriented programming and design 19 Copying In class Object: copy ^self shallowCopy postCopy Template Method pattern! Redefine postCopy to change the way to copy variables, not copy.

Object-oriented programming and design 20 OCollection transactions OCollection Timecard Employee PaycheckTimecard transactions

Object-oriented programming and design 21 | t s | t := Point x: 1 y: 17. s := t copy. s x: 5. s = t | t s | t := Point x: 1 y: 17. s := t. s x: 5. s = t | t s | t := Point x: 1 y: 17. s := t copy. s == t 2 3 1

Object-oriented programming and design 22 Classic bug aSet do: [:each | each isBold ifTrue: [aSet remove: each]] Avoid modifying a collection when you are iterating over it. aSet copy do: [:each | each isBold ifTrue: [aSet remove: each]]

Object-oriented programming and design 23 Keeping Track of Time Bug: 1. Forget to enter timecard 2. Raise salary 3. Notice that timecard is missing and enter it.

Object-oriented programming and design 24 Keeping Track of Time Problem: how do you ensure that each transaction is processed with rules in effect at the time it took place?

Object-oriented programming and design 25 Keeping Track of Time Things that are hard with current payroll design: Make a graph of salary paid per month for each person. Make a graph of vacation time taken per month for the entire company.

Object-oriented programming and design 26 ValueWithHistory I represent a (probably numerical) value that changes over time. I can answer my value at any point in time (usually a date). I can update my value at any point in time, and also add a number to my value from any point in time on into the future. My value does not change continuously, but changes at discrete points in time.

Object-oriented programming and design 27 ValueWithHistory Instead of storing a value in a variable, store it in a ValueWithHistory. earnings := ValueWithHistory zero. earnings at: today add: 50. earnings starting: endOfYear become: 0.

Object-oriented programming and design 28 ValueWithHistory protocol at: aDate- return value at aDate at: aDate add: anAmount- add anAmount to value at aDate and at all times in the future starting: aDate become: anAmount- set value from aDate to the next specificed time to anAmount

Object-oriented programming and design 29 ValueWithHistory variables date value The i'th element of value matches the i'th element of date. The date collection indicates when the value takes on the next element of the value collection.

Object-oriented programming and design 30 ValueWithHistory initialize date := SortedSequence new. value := OrderedCollection new.

Object-oriented programming and design 31 ValueWithHistory at: aDate "Return value at the date" | index | index := date indexOfStartOfIntervalContaining: aDate. index = 0 ifTrue: [self error: 'date is too early']. ^value at: index

Object-oriented programming and design 32 SortedSequence SortedSequence is a subclass of SortedCollection with one method: indexOfStartOfIntervalContaining: anElement "Return the index of anElement or, if it is not present, of the index of the largest element smaller than it."

Object-oriented programming and design 33 SortedSequence indexOfStartOfIntervalContaining: anElement self isEmpty ifTrue: [^0]. ^(self indexForInserting: anElement) - firstIndex

Object-oriented programming and design 34 ValueWithHistory at: aDate add: anAmount| start | start := (self indexForAccessing: aDate). start to: value size do: [:each | value at: each put: (value at: each) + anAmount]

Object-oriented programming and design 35 ValueWithHistory indexForAccessing: aDate "Return index of slot for aDate, creating it if necessary." | index |index := date indexOfStartOfIntervalContaining: aDate. index = 0 ifTrue: [date add: aDate. value addFirst: 0. ^1]. (date at: index) = aDate ifTrue: [^index].

Object-oriented programming and design 36 (continued) date add: aDate. value add: (value at: index) beforeIndex: index + 1. ^index + 1

Object-oriented programming and design 37 Collection methods add: anElement adds to end of OrderedCollection, to position in sort-order of SortedCollection, to random position in Set

Object-oriented programming and design 38 OrderedCollection methods addFirst: anElement adds to beginning of OrderedCollection add: anElement beforeIndex: anInteger insert element at location, moving what is there

Object-oriented programming and design 39 ValueWithHistory starting: aDate become: aValue "Change value so that it becomes aValue at aDate." | index | index := self indexForAccessing: aDate. value at: index put: aValue

Object-oriented programming and design 40 Moral It is often best not to make instance variable be simple object like number or string. 1) Make it be a domain object. (Money instead of Number) This usually is a “value object”. 2) Make it be a holder. (ValueWithHistory instead of Number or Money)

Next time "A Laboratory For Teaching Object-Oriented Thinking"-by Beck, K, Cunningham, W. Object-oriented programming and design 41