S.Ducasse 1 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Basics Prof. Ankur Teredesai, Computer Science Department, RIT.
Advertisements

Stéphane Ducasse 1 Design Points - Subclassing vs Subtyping Stéphane Ducasse
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
Smalltalk Coding Patterns mostly from Smalltalk Best Practice Patterns Kent Beck Prentice-Hall, 1997.
Stéphane Ducasse«ChapterNr».1 Selected Design Patterns Design Patterns are recurrent solutions to design problems They are pros and cons We already saw:
4. Smalltalk Coding Idioms. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.2 Roadmap  Snakes and Ladders — Cascade and Yourself  Lots of Little Methods.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Stéphane Ducasse9.1 Inheritance Semantics and Lookup.
Stéphane Ducasse 1 The Taste of Smalltalk.
PZ06BX Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ06BX - Introduction to Smalltalk Programming Language.
Some Basic Points on Classes
8. Best Practice Patterns. © Oscar Nierstrasz ST — Best Practice Patterns 8.2 Roadmap  Naming conventions  Delegation and Double Dispatch  Conversion.
Stéphane Ducasse«ChapterNr».1 Elements of Design Instance initialization Enforcing the instance creation Instance / Class methods Instance variables /
7. Best Practice Patterns. © Oscar Nierstrasz ST — Best Practice Patterns 7.2 Roadmap  Naming conventions  Delegation and Double Dispatch  Conversion.
03G-1 Everything is an Object Examining builtin classes All these are classes in Little Smalltalk:  Object  Class  Method  Block  Boolean True False.
Chapter 10 Classes Continued
Object-oriented programming and design 1 Smalltalk in a Nutshell Objects & classes Messages & methods Inheritance & metaclasses.
Stéphane Ducasse«ChapterNr».1 Advanced Classes Indexed Classes Classes as Objects Class Instance Variables and Methods Class Variables Pool Dictionaries.
Stéphane Ducasse5.1 Smalltalk in a Nutshell OO Model in a Nutshell Syntax in a Nutshell.
4. Smalltalk Coding Idioms. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.2 Roadmap  Snakes and Ladders — Cascade and Yourself  Lots of Little Methods.
Stéphane Ducasse 1 Smalltalk in a Nutshell.
Stéphane Ducasse«ChapterNr».1 Basic Objects, Conditionals and Loops Booleans Basic Loops Overview of the Collection hierarchy— more than 80 classes: (Bag,
S.Ducasse Stéphane Ducasse 1 The Taste of Smalltalk.
S.Ducasse Stéphane Ducasse 1 Elements of Design.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns.
S.Ducasse Stéphane Ducasse 1 Smalltalk Coding Idioms.
S.Ducasse Stéphane Ducasse 1 Classes and Metaclasses - an Analysis.
S.Ducasse Stéphane Ducasse 1 Design Heuristics.
Object-oriented Programming and Design 1 Polymorphism Poly => many Morph => shape Variables take on many shapes, or many classes of objects.
Stéphane Ducasse 1 Elements of Design - Simple Smells.
Cohesion and Coupling CS 4311
Java Dynamic Proxy Bibliography: reflection/proxy.html
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Inheritance Semantics and Method Lookup.
Object-oriented programming and design 1 Object Identity = vs. == copying objects Value Object ValueWithHistory.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Stéphane Ducasse 1 Elements of Design - Inheritance/Compositio n.
Smalltalk in a.NET World How to write a Smalltalk compiler without writing a VM John Brant
Stéphane Ducasse 1 Singleton.
S.Ducasse 1 7. Understanding Metaclasses. S.Ducasse 2 Roadmap Metaclasses in 7 points Indexed Classes Class Instance Variables Class Variables Pool Dictionaries.
Object Oriented Programming
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
S.Ducasse Stéphane Ducasse 1 Common Mistakes and Debugging in VW.
Stéphane Ducasse 1 Some Advanced Points on Classes.
Stéphane Ducasse7.1 Let’s Play Objects Simulate a LAN physically Set up a context for –future chapters –Exercises Some forward references to intriguate.
1 Advanced Object Oriented Systems (CM0318) Lecture 8 (Last updated 15th February 2002)
Stéphane Ducasse 1 Some Points on Classes.
S.Ducasse Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Smalltalk in a Nutshell.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Stéphane Ducasse 1 Elements of Design - Unit of Reuse.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
Lecture 2 Intro. To Software Engineering and Object-Oriented Programming (2/2)
S.Ducasse Stéphane Ducasse 1 Some Advanced Points on Classes.
Sections Inheritance and Abstract Classes
Let’s Play Objects.
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Design Points - Law of Demeter
Inheritance and Polymorphism
2.3 Collaboration Contracts
OOP What is problem? Solution? OOP
Interfaces and Inheritance
Programming Models for Distributed Application
Inheritance, Polymorphism, and Interfaces. Oh My
Java Inheritance.
Introduction to Smalltalk
Smalltalk on a Dime.
Presentation transcript:

S.Ducasse 1 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface Providing a default value

S.Ducasse 2 Provider Responsibility This is the responsibility of the class to provide well-formed object A client should not make assumptions or been responsible to send specific sequence of messages to get a working object

S.Ducasse 3 A First Implementation of Packet Object subclass: #Packet instanceVariableNames: ‘contents addressee originator ‘ Packet>>printOn: aStream super printOn: aStream. aStream nextPutAll: ‘ addressed to: ‘; nextPutAll: self addressee. aStream nextPutAll: ‘ with contents: ’; nextPutAll: self contents Packet>>addressee ^addressee Packet>>addressee: aSymbol addressee := aSymbol

S.Ducasse 4 Packet class Definition Packet class is automatically defined Packet class instanceVariableNames: '' Example of instance creation Packet new addressee: #mac ; contents: ‘hello mac’

S.Ducasse 5 Fragile Instance Creation If we do not specify a contents, it breaks! |p| p := Packet new addressee: #mac. p printOn: aStream -> error

S.Ducasse 6 Problems Responsibility of the instance creation relies on the clients A client can create packet without contents, without address instance variable not initialized -> error (for example, printOn:) -> system fragile

S.Ducasse 7 Fragile Instance Creation Solutions Automatic initialization of instance variables Proposing a solid interface for the creation Lazy initialization

S.Ducasse 8 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface Providing a default value

S.Ducasse 9 Assuring Instance Variable Initialization How to initialize a newly created instance ? Define the method initialize Packet>>initialize super initialize. contents := ‘’. addressee := #noAd

S.Ducasse 10 The New/Initialize Couple Object>>initialize “do nothing. Called by new my subclasses override me if necessary” ^ self

S.Ducasse 11 (VW) Assuring Instance Variable Initialization Problem: By default new class method returns instance with uninitialized instance variables. In VisualWorks, initialize method is not automatically called by creation methods new/new:. How to initialize a newly created instance ?

S.Ducasse 12 new calling initialize Packet new... should invoke the initialize method Packet class>>new | inst | inst := super new. inst initialize. ^ inst Packet class>>new ^ super new initialize; yourself

S.Ducasse 13 The New/Initialize Couple Define an instance method that initializes the instance variables and override new to invoke it. (1&2)Packet class>>new “Class Method” ^ super new initialize (3)Packet>>initialize “Instance Method” super initialize. (4) contents := ‘default message’ Packet new (1-2) => aPacket initialize (3-4) => returning aPacket but initialized! Reminder: You cannot access instance variables from a class method like new

S.Ducasse 14 One single method application

S.Ducasse 15 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface Providing a default value

S.Ducasse 16 Lazy Initialization When some instance variables are: - not used all the time - consuming space, difficult to initialize because depending on other - need a lot of computation Use lazy initialization based on accessors Accessor access should be used consistently!

S.Ducasse 17 Lazy Initialization Example A lazy initialization scheme with default value Packet>>contents contents isNil ifTrue: [contents := ‘no contents’] ^ contents aPacket contents or self contents A lazy initialization scheme with computed value Dummy>>ratio ratio isNil ifTrue: [ratio := self heavyComputation] ^ ratio

S.Ducasse 18 Better Packet>>contents contents isNil ifTrue: [contents := ‘no contents’] ^ contents is equivalent to Packet>>contents ^ contents ifNil: [contents := ‘no contents]

S.Ducasse 19 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface Providing a default value

S.Ducasse 20 Strengthen Instance Creation Interface Problem: A client can still create aPacket without address. Solution: Force the client to use the class interface creation. Providing an interface for creation and avoiding the use of new: Packet send: ‘Hello mac’ to: #Mac Packet class>>send: aString to: anAddress ^ self new contents: aString ; addressee: anAddress ; yourself

S.Ducasse 21 Examples of Instance Initialization step 1. SortedCollection sortBlock: [:a :b| a name < b name] SortedCollection class>>sortBlock: aBlock "Answer a new instance of SortedCollection such that its elements are sorted according to the criterion specified in aBlock." ^ self new sortBlock: aBlock step 2. self new => aSortedCollection step 3. aSortedCollection sortBlock: aBlock step 4. returning the instance aSortedCollection

S.Ducasse 22 Another Example step 1. OrderedCollection with: 1 Collection class>>with: anObject "Answer a new instance of a Collection containing anObject." | newCollection | newCollection := self new. newCollection add: anObject. ^newCollection

S.Ducasse 23 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface Providing a default value

S.Ducasse 24 Providing a Default Value OrderedCollection variableSubclass: #SortedCollection instanceVariableNames: 'sortBlock ' classVariableNames: 'DefaultSortBlock ' SortedCollection class>>initialize DefaultSortBlock := [:x :y | x <= y] SortedCollection>>initialize "Set the initial value of the receiver's sorting algorithm to a default.” sortBlock := DefaultSortBlock

S.Ducasse 25 Providing a Default Value SortedCollection class>>new: anInteger "Answer a new instance of SortedCollection. The default sorting is a <= comparison on elements. " ^ (super new: anInteger) initialize SortedCollection class>>sortBlock: aBlock "Answer a new instance of SortedCollection such that its elements are sorted according to the criterion specified in aBlock. " ^ self new sortBlock: aBlock

S.Ducasse 26 Invoking per Default the Creation Interface OrderedCollection class>>new "Answer a new empty instance of OrderedCollection." ^self new: 5

S.Ducasse 27 Forbidding new? Problem: We can still use new to create fragile instances Solution: new should raise an error! Packet class>>new self error: 'Packet should only be created using send:to:'

S.Ducasse 28 Forbidding new Implications But we still have to be able to create instance! Packet class>>send: aString to: anAddres ^ self new contents: aString ; addressee: anAddress raises an error Packet class>>send: aString to: anAddress ^ super new contents: aString ; addressee: anAddress BAD STYLE: link between class and superclass dangerous in case of evolution

S.Ducasse 29 Forbidding new Solution: use basicNew and basicNew: Packet class>>send: aString to: anAddress ^ self basicNew contents: aString ; addressee: anAddress Conclusion: Never override basic* methods else you will not be able to invoke them later

S.Ducasse 30 How to Reuse Superclass Initialization? A class>>new ^ super new doThat; andThat; end B class>>forceClientInterface ^ self basicNew ??? Solution: Define the initialization behavior on the instance side A>>doThatAndThatEnd ^ self doThat; andThat; end A class>>new ^ super new doThatAndThatEnd B class>>forceClientInterface ^ self basicNew doThatAndThatEnd

S.Ducasse 31 Even Better...Use initialize But you cannot simply chain the calls...so use initialize A>>initialize super initialize. self doThat; andThat; end B>>initialize super initialize. self andFoo.

S.Ducasse 32 Different Self/Super Do not invoke a super with a different method selector. It’s bad style because it links a class and a superclass. It makes the code difficult to understand This is dangerous in case the software evolves.

S.Ducasse 33 Example Packet class>>new self error: 'Packet should be created using send:to:' Packet class>>send: aString to: anAddress ^ super new contents: aString ; addressee: anAddress Use basicNew and basicNew: Packet class>>send: aString to: anAddress ^ self basicNew contents: aString ; addressee: anAddress

S.Ducasse 34 Super is static! With the super foo: A new bar -> 10 B new bar -> 10 C new bar -> 10 Without the super foo: A new bar -> 10 B new bar -> 100 C new bar -> 50 super shortcuts dynamic calls