Object-Oriented Design with — a Pure Object Language and its Environment

Dr. Stéphane Ducasse [email protected] http://www.iam.unibe.ch/~ducasse/

University of Bern 2000/2001 ii. Six pseudo-variables (ii)Global VariablesThree Kinds of MessagesUnary MessagesBinary MessagesKeyword MessagesCompositionSequenceCascade 71 yourselfHave You Really Understood Yourself ? 73 Block (i): Definition 72 Block (ii): EvaluationBlock (iii) 81 74 Primitives 75 76 What You Should KnowClass Definition: The Packet 77 Named Instance VariablesMethod Definition 78 Accessing Instance VariablesMethods always Return a Value 82 79 83 Some Naming Conventions 88 80 Inheritance in Smalltalk 86 Remember...Node 89 84 91 92 Message Sending & Method Lookup 85 Method Lookup Examples (i)Method Lookup Examples (ii) 93 90 Method Lookup Examples (ii)How to Invoke Overridden Methods? 98 94 Semantics of super 102 99 100 95 101 97 96 103

7. Dealing with Classes 87

March 20, 2000

Table of Contents Everything is an objectObjects communicate via messages (i)A LAN SimulatorThree Kind of Objects 40 Interactions Between NodesNode and Packet CreationObjects communicate by messages (ii)Definition of a LANTransmitting a Packet 39 How to Define a Class? 45 How to Define a Method? 43 44 42 Syntax in a Nutshell (i) 41 Syntax in a Nutshell (ii)Messages instead of predefined SyntaxClass and Method DefinitionInstance Creation 46 47 53 48 49 Read it as a non-computer person!Literal Overview (i)Literal Overview (ii) 51 Literal Arrays and 54 52 Deep Into Literal Arrays 57 Deep into Literal Arrays (ii)Deep into Literal Arrays (iii)Symbols vs. Strings 55 Variables OverviewTemporary VariablesAssignments 58 Method Arguments 60 59 Instance Variables 61 62 Six pseudo-variables (i) 63 64 65 66 68 70 69 67

5. Smalltalk Syntax in a Nutshell6. Syntax and Messages 50 56 Table of ContentsSome Web PagesStructure of this Lecture (i)Structure of this Lecture (ii)About this lectureBasic SmalltalkSmalltalk: More than a LanguageInspirationPrecursor, Innovative and Visionary ii 9 History 10 History 8 Smalltalk’s Concepts 14 Messages, Methods and Protocols 16 Objects, Classes and Metaclasses 11 Smalltalk Run-Time ArchitectureVisualWorks Advanced Runtime Architecture 12 23 20 Mouse Semantics 21 Class MenuBarMethod MenuBar 22 15 Cross Reference Facilities 19 Filing OutHierarchy Browser 17 Debugger 18 Crash RecoveryCondensing ChangesUIBuilder 25 29 Some ConventionsHello World! 27 28 31 34 30 33 32 37 35 38

Table of Contents 1. Infos2. Smalltalk in Context 7 13 3. Quick Overview of the Environment 24 4. A Taste of Smalltalk 36 iii. CirclepoolDictionariesExample of PoolVariablesContextProgram ArchitectureSeparation of Concerns I:Separation of Concerns II:The notion of DependencyDependency Mechanism 177 Publisher-Subscriber: A Sample SessionChange Propagation: Push and Pull 176 The MVC PatternA Standard Interaction Cycle 185 181 180 175 MVC: Benefits and Liabilities 182 183 186 MVC and SmalltalkManaging Dependents 184 Implementation of Change Propagation 179 Climbing up and down the Default-LadderProblems ... 188 192 193 Dependency Transformer 189 Inside a Dependency TransformerValueHolder 187 A UserInterface WindowWidgets 191 190 The Application Model 196 The fine-grained Structure of an ApplicationMVC Bibliography 201 195 Concurrency and ParallelismLimitations 198 194 AtomicitySafety and LivenessProcesses in Smalltalk: Process class 200 197 Processes in Smalltalk: Process class 204 202 208 199 209 207 205 206

13. The Model View Controller Paradigm 178 14. Processes and Concurrency 203 Basic Example of CatchingException SetsSignaling ExceptionException EnvironmentResumable and Non-ResumableResume:/Return:Exiting Handlers Explicity 139 ExamplesExamples 143 Streams 142 An Example 141 140 printSring, printOn:Stream classes(i) 145 Stream Classes (ii)Stream tricks 144 Streams and BlocksStreams and FilesAdvanced Smalltalk 146 Types of Classes 147 Two Views on Classes 151 Indexed Classes 150 Indexed Class/Instance Variables 149 152 153 The meaning of “Instance of” (i)Lookup and Class Messages 155 The Meaning of “Instance-of” (iii) 154 157 156 Metaclass Responsibilities 162 Class Instance VariablesAbout Behavior 163 160 Class Method 159 166 classVariable 165 Class Instance Variables / ClassVariable 161 Summary of Variable VisibilityExample From The System: Geometric Class 167 172 174 168 173 169 170 171

11. Streams12. Advanced Classes 148 158 The Main Exceptions138 Let us be Absurd!Object InstantiationDirect Instance Creation: (basic)new/new:Messages to Instances that Create Objects 106 Opening the Box 107 Class specific Instantiation MessagesWhat you should knowBoolean Objects 109 Some Basic Loops 104 For the Curious! 105 CollectionsAnother ViewCollection MethodsSequenceable Specific (Array) 108 110 KeyedCollection Specific (Dictionary)Choose your Camp!Iteration Abstraction: do:/collect:Iteration Abstraction: select:/reject:/detect: 119 112 113 Iteration Abstraction: inject:into: 122 118 Collection Abstraction 114 Examples of Use: NetworkManager 121 Common Shared Behavior (i) 117 Identity vs. Equality 115 116 Common Shared Behavior (ii) 123 Essential Common Shared Behavior 120 125 What you should know 126 The Basics of Numbers 124 129 Deeper into Numbers: Double Dispatch (i) 128 Deeper into Numbers: Double Dispatch (ii) 133 Deeper into Numbers: Coercion & Generality 134 135 Deeper into Numbers: #retry:coercing: 127 130 136 132

Table of Contents 8. Basic Objects, Conditional and Loops 111 9. Numbers10. Exceptions 131 137 iv. 303 315 Why Coupled Classes are Bad?The Law ot DemeterIllustrating the Law of DemeterAbout the Use of Accessors (i)About the Use of Public Accessors (ii)Never to work that somebody else can do! 304 Provide a Complete Interface 309 Factoring Out Constants 308 306 Initializing without Duplicating 307 Constants Needed at Creation Time 305 Type Checking for Dispatching 310 Double Dispatch (i) 314 A Step Back 313 Deeper on Double Dispatch : Numbers (ii) 312 319 316 317 318 BooleanFalse and TrueCaseStudy: Magnitude:DateA First Implementation of PacketPacket CLASS DefinitionFragile Instance CreationAssuring Instance Variable InitializationOther Instance Initialization 285 288 Lazy Initialization 291 Strengthen Instance Creation Interface 284 Forbidding new 283 Class Methods - Instance Variables 294 289 Class Initialization 290 Date class>>initialize 297 292 A Case Study: Scanner 286 Scanner class>>initializeScanner 293 295 299 298 300 301 302

21. Elements of Design 287 279 Library Behavior-based BugsUse of Accessors: Protect your CientsDebugging HintsWhere am I and how did get here?Source Inspection 247 Where am I going?How do I get out? 246 249 Finding & Closing Open Files in VWThree ways to create classes:Let us CodeFormat and other 253 Object size in bytes 248 Analysis 250 251 255 Full Blocks 252 Copying BlocksClean BlocksInlined BlocksFull to CopyContexts 257 Inject:into: 258 256 About String ConcatenationStream, Blocks and Optimisation (i)Stream, Blocks and Optimisation (ii)BlockClosure Class Comments 259 263 Lexically Scope 270 262 271 Returning from a Block (i) 269 264 Returning From a Block (ii) 265 Example of Block Evaluation 272 266 Design Considerations 267 268 Case Study: Boolean, True and False 275 276 277 274 282 280

17. Internal Structure of Object18. Blocks and Optimization 254 261 19. Block Deep Understanding 273 20. Abstract Classes 281 Processes in Smalltalk: Process statesProcess Scheduling and PrioritiesProcesses Scheduling and PrioritiesThe Process Scheduling Algorithm 210 Process SchedulingSynchronization Mechanisms 211 Synchronization Mechanisms 212 Synchronization using Semaphores 213 SemaphoresSemaphores for Mutual ExclusionSynchronization using a SharedQueueDelays 215 217 Promises 216 220 214 219 The meaning of “Instance of”Concept of Metaclass & ResponsibilitiesClasses, metaclasses and method lookupResponsibilities of Object & Class classes 225 226 A possible kernel for explicit metaclassesSingleton with explicit metaclasses 227 218 224 Deeper into it 228 Smalltalk Metaclasses in 7 pointsSmalltalk Metaclasses in 7 points (iii)Smalltalk Metaclasses in 7 points (iv) 229 Behavior Responsibilities 221 222 ClassDescription Responsibilities 233 Metaclass Responsibilities 231 234 Class ResponsibilitiesMost Common Beginner BugsReturn Value 236 Take care about loops 230 235 Instance Variable Access in Class MethodAssignments Bugs 237 243 Redefinition Bugs 240 238 242 241 244 245

Table of Contents 15. Classes and Metaclasses: an Analysis 223 16. Most Common Mistakes and Debugging 239 v. ConsequencesWhen/ When NotVisualWorks ExamplesComparingHistoryTarget Application DomainsEvolutionLanguage Design GoalsUnique, Defining FeaturesOverview of Features 395 393 394 SyntaxObject Model 399 Memory ManagementDynamic Binding 396 Inheritance, Generics 401 Types, Modules 402 Exceptions, ConcurrencyReflection 403 398 Implementation Technology 400 Portability, InteroperabilityEnvironments and Tools 406 Development StylesThe Bottom Line ... 405 408 407 410 404 Syntax (i) 412 Syntax (ii) 409 413 Syntax MethodsSyntax Conditional and Loops 414 No Primitive Types Only ObjectsLiterals representing the same object 411 415 Class Definition 416 Method Definition Declaration (i) 423 421 Method Definition (i) 422 420 418 426 419 425 427

24. Comparing C++, Java and Smalltalk 397 25. Smalltalk for the Java Programmer 417 26. Smalltalk For the Ada Programmer 424 Name Well your Methods (i)do:collect:isEmpty, includes:How to Name Instance Variables?Class NamingReversing Method 357 Debug Printing MethodMethod Comment 361 Choosing MessageDelegationSimple DelegationSelf Delegation (i) 360 Self Delegation - ExamplePluggable Behavior 364 Pluggable Selector 359 358 363 Pluggable Block 362 365 Singleton Instance: A Class Behavior 366 Singleton Instance’s ImplementationSingleton 370 368 Discussion 369 375 367 Singleton Variations 376 Ensuring a Unique Instance 371 Providing Access 372 Accessing the Singleton via new?Singletons in a Single Subhierarchy 373 Instance/Class MethodsQueriesA Possible Solution 382 380 Composite Pattern 383 Implementation Issues 379 NullObject 377 Without Null Object Illustration 378 With Null Object 381 384 386 390 388 387 385 389 391

23. Some Selected Design Patterns 374 320 333 Methods are the Elementary Unit of ReuseMethods are the Elementary Unit of Reuse (ii) 321 322 Methods are the Elementary Unit of ReuseClass Factories 323 Hook and Template MethodsHook Example: CopyingHook SpecialisationHook and Template Example: PrintingOverride of the HookSpecialization of the HookBehavior Up and State Down 325 328 Guidelines for Creating Template Methods 332 326 Towards Delegation: Matching Addresses 324 Limits of such an ad-hoc solution 334 Reifyand Delegate 327 Reifying Address 331 330 329 Matching AddressAddresses 335 Trade OffDesigning Classes for ReuseBad coding practicesDifferent Self/SuperDo not overuse conversionsHidding missing information 336 Composed Method 337 341 338 Constructor MethodConstructor Parameter MethodQuery Method 342 344 Boolean Property Setting Method 339 345 Comparing Method 343 340 Execute Around MethodChoosing Message 349 351 347 348 353 350 352 354

Table of Contents 22. Selected Idioms 346 vi. Method Definition(ii)Instance Creation MethodInstance CreationA Jungle of NamesTeam Development EnvironmentsSome Free SmalltalksMain References 429 Other References (Old or Dialects)Other References (ii) 428 433 Some Web Pages 436 430 432 434 435 437 438

Table of Contents 27. References 431 1. Infos Me: Dr. Stéphane Ducasse Where: Office 101, 10 Neubrückstrasse, CH-3012 Berne EMail: [email protected] Me electronic: http://www.iam.unibe.ch/~ducasse/ Lecture Resources: http://www.iam.unibe.ch/~scg/Resources/Smalltalk/ http://brain.cs.uiuc.edu/VisualWorks/ http://www.iam.unibe.ch/~ducasse/PubHTML/Smalltalk.html http://kilana.unibe.ch:8080/SmalltalkWiki/ News groups: comp.lang.smalltalk Important Addresses to get free Smalltalks: http://www.objectshare.com/VWNC/ http://www.squeak.org/ http://www.object-arts.com/Home.htm ANSI X3j20: www.smalltalksystems.com/sts-pub/x3j20

Object-Oriented Design with Smalltalk a Pure OO Language Infos Universität Bern Ducasse Stéphane 1.7 VisualWorks /brain.cs.uiuc.edu/VisualWorks/ VisualAge /brain.cs.uiuc.edu/VisualAge/ http://kilana.unibe.ch:8080/SmalltalkWiki/ /www.stic.org/ /www.smalltalk.org/ /www.goodstart.com/stlinks.html /st-www.cs.uiuc.edu/ www.esug.org/ www.bsug.org/ www.gsug.org/ www.iam.unibe.ch/~ssug/

Some Web Pages Wikis: STIC: Cool Sites: User Groups: ESUG, BSUG, GSUG, SSUG

Object-Oriented Design with Smalltalk a Pure OO Language Infos Universität Bern Ducasse Stéphane 1.8 Basic Smalltalk Elements – History and Concepts – Syntax – Class/Method Definitions – Collections – Numbers – Streams Advanced Smalltalk Topics – Classes – MVC – Concurrency – Metaclasses – Debugging – Internals ❑ ❑

Structure of this Lecture (i)

Object-Oriented Design with Smalltalk a Pure OO Language Infos Universität Bern Ducasse Stéphane 1.9 Design Issues – Abstract Classes – Elementary Design Issues – Idioms – Some selected design patterns Comparisons – Java, C++, Smalltalk – Smalltalk for the Java Programmer – Smalltalk for the Ada Programmer ❑ ❑

Structure of this Lecture (ii)

Object-Oriented Design with Smalltalk a Pure OO Language Infos Universität Bern Ducasse Stéphane 1.10 contact me! If you have problems, Grab VisualWorks from www.cincom.com or http://brain.cs.uiuc.edu/ or from www.squeak.org Do the exercises!!! ❑ ❑ ❑

About this lecture

Object-Oriented Design with Smalltalk a Pure OO Language Infos Universität Bern Ducasse Stéphane 1.11 History and Concepts Tasting Smalltalk Syntax Class/Method Definitions Collections Numbers Streams ❑ ❑ ❑ ❑ ❑ ❑ ❑

Basic Smalltalk

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane History Context Run-Time Architecture Concepts ❑ ❑ ❑ ❑

2. Smalltalk in Context

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.13 A small and uniform language (two days to learn the syntax). A large set of reusable classes (basic data structures, UI, database access, sockets ...). A set of powerful development tools (Browsers, UIBuilder, Inspector, change management, crash recovery, project management). A run-time environment based on virtual machine technology. With Envy, team working and application management (release, versioning, deployment). ❑ ❑ ❑ ❑ ❑

Smalltalk: More than a Language

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.14 — : a desktop computer for children Flex (Alan Kay 1969) Lisp (interpreter, blocks, garbage collection) Turtle graphics (Logo Project, programming by children) Direct manipulation interfaces (Sketchpad 1960) (classes and message sending, description of a real phenomenon by means of a specification language: modelling) ☞

"making simple things very and complex possible" ❑ ❑ ❑ ❑ ❑

Inspiration

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.15 Yes a mouse !!!! It was revolutionary! Apple copied them (Lisa, then Mac). First graphical bitmap-based – multi-windowing (overlapping windows) – programming environment (debugger, compiler, editor, browser) – with a pointing device Virtual Machine + Platform independent image technology Garbage Collector Just in Time Compilation Even in 1980 you got all the source development environment!! ❑ ❑ ❑ ❑ ❑

Precursor, Innovative and Visionary

Xerox Smalltalk Team developed the mouse technology and bitmap:

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.16 CLOS Lisp Oberon Prolog Modula-2 Modula-3 COBOL Ada Ada 95 Pascal Eiffel Clu PL/1 C C++ ANSI C++ Algol 60 Algol 68 Java Objective C Self Simula 67 Smalltalk 72 Smalltalk 80

History 1960 1970 1980 1990

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.17 gc by ➜

History Internal. 1972: First interpreter; more agents than objects (every object can specify its own syntax). 1976: Redesign: Hierarchy of classes with unique root + fixed syntax (compact byte code), contexts, process + semaphores Browser UI class library. Projects: ThingLab, Visual Programming Environment by Rehearsal. 1978: Experimentation with 8086 microprocessor (NoteTaker project). External. 1980: Smalltalk-80 (Ascii, cleaning primitivesclass objects, MVC, ) for portability, metaclasses, blocks asProjects: Galley Editor (mixing text, painting and animations) + Alternate Reality Kit first- (physics simulation) 1981: books + four external virtual machines (Dec, Apple, HP and Tektronix) generation scavenging 1988: Creation of Parc Place Systems 1992: Draft Ansi 1995-6: New Smalltalk implementations (MT, dolphin, Squeak VM in Smalltalk....)

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.18 . by message passing.

(numbers, files, editors, compilers, points, tools, only

Reading an interactive Book

late binding Each object is an instance of one class (which also object). A class defines the structure and behaviour of its instances. Each object possesses its own set of values. Dynamically typed. Purely based on Everything is an object boolean). Objects communicate Reading the interface of classes: (table contents a book) Understanding the way classes are implemented: (reading chapters) Extending and changing the contents of system ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Smalltalk’s Concepts Programming in Smalltalk:

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.19 behaviour to perform to carry out the behaviour What ifTrue:[ Transcript show: 'AifFalse: [super accept: aPacket] packet is accepted by the Workstation ', self name asString] How aWorkstation accept: aPacket (aPacket isAddressedTo: self)

Messages, Methods and Protocols accept: aPacket Message: Method: Protocol: The complete set of messages an object responds to: #name #initialize #hasNextNode #connectedTo: #name:#typeName #accept: #send: #nextNode #nextNode: #printOn: #simplePrintString Often grouped into categories: accessinginitialize-release #initialize testingconnection #name privateprintingsend-receive #connectedTo: #hasNextNode #name: #nextNode #nextNode: #accept: #send: #printOn: #simplePrintString #typeName

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.20 Every object is an instance of a class A class specifies the structure and behaviour of all its instances Instances of a class share the same behaviour and have specific state Classes are objects that create other instances Metaclasses are just classes that create as instances Metaclasses described class behaviour and state (subclasses, method dictionary, instance variables...) ❑ ❑ ❑ ❑ ❑ ❑

Objects, Classes and Metaclasses

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.21 Shared by everybody Standard SOURCES + A byte-code interpreter: the virtual machine interpretes image IMAGE2.IM IMAGE2.CHA IMAGE1.IM IMAGE1.CHA One per user All the objects of system at a moment in time

Smalltalk Run-Time Architecture Virtual Machine + Image Changes and Sources The byte-code is in fact translated into native code by a just-in-time compiler. The source and the changesfor the development. Normally they are removed deployment. are not necessary for interpretingAn the application byte-code, can this be is delivered just The development image is stripped to remove the unnecessary as some byte-code filescomponents like the compiler, scanner, browser,.... that will be executed with a VM.

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.22 Change User 2

Architecture VM Image

Runtime Shared by everybody Sources piece of source (text) Source of all the objects currently in memory Parcel(pst) Change Advanced User 1 Parcels reproduce the schema of image and change: pcl are byte code, pst source code Parcels allow atomic loading/unloading and prerequisites parcels Extremely fast loading Good for dynamic loading, code management VM Image Parcel(pcl) piece of image (byte code) byte code of all the objects ❑ ❑ ❑ ❑ currently in memory

VisualWorks

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk in Context Universität Bern Ducasse Stéphane 2.23 VW2.5 not VW3.0 — sorry!!

3. Quick Overview of the Environment

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.24 Blue Operate Yellow Red Select

Mouse Semantics

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.25 Opens a canvas editor Opens a workspace Opens a System Browser Opens a file selector

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.26 LinkedOrderedCollection ('backup') SortedCollection ('sortBlock') Object () Collection () SequenceableCollection () OrderedCollection ('firstIndex' 'lastIndex') Shows the class definition and comments Opens a ClassBrowser Opens a HierarchyBrowser Ditto for class variables and class references

Class MenuBar

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.27 Opens a method browser To know the implementors of a method sent in the current method body

Method MenuBar

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.28 Launcher

Cross Reference Facilities

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.29 project protocol method class Browser category

Filing Out

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.30 Hierarchy Browser Use the Refactoring Browser instead!!!

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.31 Debugger

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.32 Crash Recovery

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.33 SourceFileManager new condenseChanges

Condensing Changes

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.34 UIBuilder

Object-Oriented Design with Smalltalk a Pure OO Language Quick Overview of the Environment Universität Bern Ducasse Stéphane 3.35 “hello world” a LAN simulator the syntax the elementary objects and classes the environment all the code examples, constructs, design decisions ... ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

4. A Taste of Smalltalk “Try not to care - Beginning Smalltalk programmers often have trouble because they think they need to understandThis all means the it details takes of quiteOne how a of a while the thing before great works leaps theywith "I don’t care"“. Alan Knight registered Guru before in can they OO master can is Transcript to use show: be it. ‘HelloTwo examples: able World’. to answer the question "How does this work?" To give you an idea of: To provide the basis for all lectures:

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.36 show: (each class name); show: (each printString); show: ‘ ‘]. “This is aexcept primitives, which aren’t very standard. It has unary, binary, and key small methodword that messages, illustrates declaresaccesses arguments every a and global part variablecharacter, temporaries of (but symbol, (but Smalltalk not string, not andnil, method integer, block instance self, float), syntax and variable), temporaries), uses super, useszero argument and one blocks. It doesn’t do anything useful, though” and the literals has pseudo (array, sequence, variable assignment, return true and false, cascade. It has both do: [:each | Transcript ^ x < y Power to Simplicity: Syntax on a PostCard exampleWithNumber: x |y| true & false not (nil isNil) ifFalse: [self halt]. y := self size + super size. #($a #a ‘a’ 1 1.0) From Ralph Johnson

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.37 ) ) Node ) #inspect #printOn: (in the class of the class Node Node Something #add: is an instance of the class

-> a Workstation with name:#pc connectedto:#mac withName: aSymbol instance method defined in the class class method defined in the class

-> aNode Transcript show: ‘Hello world’

-> 4 accept: aPacket aSomething InspectIt = send a message to an object + inspect the result ( DoIt, PrintIt, InspectIt and Accept Accept = Compile: a method or class definition DoIt = send a message to an object PrintIt = send a message to an object + print the result ( Code Return Value Method selector Method scope conventions: 1 + 3 Node new Node new PrIt Node>> Node class>> ❑ ❑ ❑ ❑ ❑ ❑

Some Conventions

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.38 instance associated with the launcher. is a special object that kind of standard output. TextCollector .

Hello World! Transcript show: ‘hello world’ Transcript During implementation, we can dynamically ask the interpreter to evaluate an expression. To evaluate an expression,doIt select it and with the middle apply It refers to a

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.39 it. modify . . . . it or even . String MemoryObject extend . Compiler ParagraphEditor instance of ApplicationWindow Parser written in itself! aString uniform , that is also an object. is an object: how it is implemented, you can Symbol consistent learn is a

Everything is an object a world #show: The mouse is an object. The parser is an object instance of + (almost) all the code is available and readable....Book concept. The text editor is an object: instance of The compiler is also an object instance of ... ⇒ you can The launcher is an object. The icons are objects. The workspace is an object. The window is an object: instance of The scrollbars are objects too. ‘hello word’ The process scheduler is also an object. The garbage collector is an object: instance of

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.40 #show: is the receiver of message ‘hello world’ Transcript is a global variable (starts with an uppercase letter) that refers to the – invoking a method in Java or C++ – calling a procedure in procedural languages – applying a function in functional languages – the object – an argument: a string – the selector of message is

Objects communicate via messages (i) Transcript show: ‘hello world’ Transcript Launcher’s report part. Vocabulary Concerns: Message passing or sending a message is equivalent to The above expression is a message: (modulo polymorphism for the last two)

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.41 node2 node3 pc lpr node1 A LAN contains nodes, , printers, file servers. Packets are sent in a LAN and each nodes treats them differently. mac

A LAN Simulator

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.42 nextNode Workstation originate: aPacket accept: aPacket Node name accept: aPacket send: aPacket hasNextNode Printer print: aPacket accept: aPacket represents how the nodes are connected. Packet NetworkManager represents the information that flows between Nodes. addressee contents originator isSentBy: aNode isAddressedTo: aNode and its subclasses represent the entities that are connected to form a LAN.

Three Kind of Objects declareNode: aNode undeclareNode: aNode connectNodes: anArrayOfAddressees Node Packet NetworkManager

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.43 node1 aPacket [false] accept: aPacket send: aPacket print: aPacket [true] isAddressedTo: nodePrinter nodePrinter accept: aPacket

Interactions Between Nodes

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.44 |macNode pcNode node1 printerNode node2 node3 packet| "nodes definition" macNode := Workstation withName: #mac. pcNode := Workstation withName: #pc. node1 := Node withName: #node1. node2 := Node withName: #node2. node3 := Node withName: #node2. printerNode := Printer withName: #lpr. "Node connections" macNode nextNode: node1. node1 nextNode: pcNode. pcNode nextNode: node2. node3 nextNode: printerNode. lpr nextNode: macNode. "packet creation" packet := Packet send: 'This travelled to the printer' to: #lpr.

Node and Packet Creation

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.45 - receiver : 1 (an instance of SmallInteger) - selector: #+ - arguments: 2 - receiver lpr (an instance of LanPrinter) - selector: #nextNode: - arguments: macNode (an instance of Workstation) - receiver: Packet (a class) - selector: #send:to: - arguments: 'This packet travelled to the printer' and #lpr - receiver: Workstation (a class) - selector: #withName: - arguments: #mac

Objects communicate by messages (ii) Message: 1 + 2 Message: lpr nextNode: macNode Message: Packet send: 'This packet travelled to the printer' to: #lpr Message: Workstation withName: #mac

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.46 aLan findNodeWithAddress: #mac | aLan aLan := NetworkManager new. aLan createAndDeclareNodesFromAddresses: #(node1 node2 node3) ofKind: Node. aLan createAndDeclareNodesFromAddresses: #(mac pc) ofKind: Workstation. aLan createAndDeclareNodesFromAddresses: #(lpr) ofKind: LanPrinter. aLan connectNodesFromAddresses: #(mac node1 pc node2 node3 lpr)

Definition of a LAN To simplify the creation and manipulation of a LAN. Now we can query the LAN to get some nodes:

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.47 -> mac sends a packet to pc -> pc sends a packet to node1 -> node1 sends a packet to node2 -> node2 sends a packet to node3 -> node3 sends a packet to lpr -> lpr is printing -> this packet travelled to lpr | aLan packet macNode| ... macNode := aLan findNodeWithAddress: #mac. packet := Packet send: 'This travelled to the printer' to: #lpr. macNode originate: packet.

Transmitting a Packet

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.48 ' addressee originator contents Packet ' LAN subclass: # instanceVariableNames: 'instVarName1 instVarName2' classVariableNames: 'ClassVarName1 ClassVarName2' poolDictionaries: '' category: 'LAN' instanceVariableNames: ' classVariableNames: '' poolDictionaries: '' category: '

How to Define a Class? NameOfSuperclass subclass: #NameOfClass Object Fill the template: For example to create the class Packet

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.49 ) self accept: thePacket] .accept(thePacket) print: thePacket] super self print(thePacket)} this. else super ifTrue: [ ifFalse: [ void accept(thePacket Packet) /*If the packet is addressed to me, print it. Else just behave like a normal node*/ if (thePacket.isAddressedTo(this)){

How to Define a Method? "comment stating purpose of message" | temporary variable names statements "If the packet is addressed to me, print it. Else just behave like a normal node" (thePacket isAddressedTo: Follow the template: message selector and argument names LanPrinter>>accept: thePacket In Java we would write

Object-Oriented Design with Smalltalk a Pure OO Language A Taste of Smalltalk Universität Bern Ducasse Stéphane 4.50 show: (each class name); show: (each printString); show: ‘ ‘]. “This is aexcept primitives, which aren’t very standard. It has unary, binary, and key small methodword that messages, illustrates declaresaccesses arguments every a and global part variablecharacter, temporaries of (but symbol, (but Smalltalk not string, not andnil, method integer, block instance self, float), syntax and variable), temporaries), uses super, useszero argument and one blocks. It doesn’t do anything useful, though” and the literals has pseudo (array, sequence, variable assignment, return true and false, cascade. It has both do: [:each | Transcript ^ x < y 5. Smalltalk Syntax in a Nutshell exampleWithNumber: x |y| true & false not (nil isNil) ifFalse: [self halt]. y := self size + super size. #($a #a ‘a’ 1 1.0) From Ralph Johnson

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.50 Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.51 return comments symbol or array string block or byte array separator and not terminator (or namespace messages to the same instance) cascade (sending several access in VW5i) local or block variable assignment character end of selector name or radix number exponent file element separator calls for VM primitive ^ “ # ‘ . ; | $ : ! := [ ] e, r

Constructs Language constructs: ^ “ # ‘’ [] . ; () | := $ : er !

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.52 1/33 10@120 #mac #+ #[1 2 3] 1, 2r101 “a comment” true, false #(1 2 3 (1 3) $a 4) 1.5, 6.03e-34,4, 2.4e7 ‘a nice string’ ‘lulu’ ‘l’’idiot’ $c $h $a $r $a $c $t $e $r $s $# $@ an element of the syntax, but just a message sent to number.

not comment: array: integer: real: float: character: string: symbol: byte array: boolean: point:

Syntax in a Nutshell (i) Note that @ is (This is the same for /, bitShift, ifTrue:, do: ...)

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.53 |tmp| :var selector receiver selector argument receiver arg2... keyword2: arg1 keyword1: receiver message ; selector ... message . result: ^ cascade: separator: parenthesis: (...) unary message: keyword based: block variable: binary message: var := aValue temporary variable: [:var ||tmp| expr...]

Syntax in a Nutshell (ii) assigment: block:

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.54 10 bitShift: 2 (1> x) ifTrue: #(a b c d) do: [:each | Transcript show: each ; cr] 1 to: 10 do: [:i | Transcript show: each printString; cr] in Java, C, C++, Ada, >>, if, for, ... are hardcoded into the grammar in Smalltalk there are just messages defined on objects (>>) bitShift: is just a message sent to numbers (if) ifTrue: is just messages sent to a boolean (for) do:, to:do: are just messages to collections or numbers => Minimal parsing => Language extensible ❑ ❑

Messages instead of predefined Syntax

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.55 ' ) self name nextNode accept: thePacket] print: thePacket] Node super ' self LAN Methods are public Instance variables are instance-based protected ifTrue: [ ifFalse: [ subclass: # ☞ ☞ "If the packet is addressed to me, print it. Else just behave like a normal node" (thePacket isAddressedTo: instanceVariableNames: ' classVariableNames: '' poolDictionaries: '' category: ' Node>>accept: thePacket

Class and Method Definition Object Class: a message sent to another class Method: normally done in a browser or (by directly invoking the compiler)

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.56 1, ‘abc’ Basic class messages creation (new, new:, basicNew, basicNew:) Packet new Class specific message creation Workstation withName: #mac

Instance Creation

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk Syntax in a Nutshell Universität Bern Ducasse Stéphane 5.57 – Literals: numbers, strings, arrays.... – Variables names – Pseudo-variables – Assignment, return – Message Expressions – Block expressions

6. Syntax and Messages The syntax of Smalltalk is simple and uniform, but it can seem strange at first sight!

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.56 (Sensor mousePoint) bunny)

transformScreenPointToScenePoint: using: camera rightNow ] (camera pointAt: duration:

Read it as a non-computer person! doEachFrame: [ bunny head | bunny bunny := Actor fromFile: ‘bunny.vrml’. bunny head

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.57 4, 2r100 (4 in base 2),3r11 3), 1232 3/4, 2.4e7, 0.75d SmallInteger, Integer, Fraction, Float, Double $F, $Q $U $E $N $T $i Unprintable characters Character space, tab, cr #class #mac #at:put: #+ #accept: #mac asString -> 'mac' 12 printString -> '12' 'This packet travelled around to the printer' 'l''idiot' String with: $A

Literal Overview (i) Numbers: Characters: Symbols: Strings: To introduce a single quote inside string, just double it.

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.58 ) ) an array of symbols. mac #node1 #pc #node2 #node3 #lpr (mac node1 pc node2 node3 lpr #(1 2 3) #('lulu' (1 3)) # When one prints it shows #(# #[1 2 255] "This is a comment"

Literal Overview (ii) Arrays: Byte Array: Comments: A comment can be onthere several lines. is Moreover, no avoid space, puttingdouble click: the entire commented expression is selected. After you can printIt or doIt. a the space system between helps the “ you and to the select first letter. a Indeed commented when expression. You just go after the “ character and

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.59 PrIt-> #('calvin' 'hobbes' 'suzie')

PrIt-> #(#calvin #hobbes #suzie)

PrIt-> #('lulu' #(1 2 3))

PrIt-> #('lulu' 1.22 1)

Literal Arrays and #('lulu' (1 2 3)) #('lulu' 1.22 1) #(calvin hobbes suzie) #('calvin' 'hobbes' 'suzie') #(Packet new) an array with two symbols and not instance of Packet Array new at: 1 put: (Packet new) is an array with one element instance of Packet #(...) considers elements as literals and false true nil #( 1 + 2 ) PrIt-> #(1 #+ 2) Array with: (1 +2) PrIt-> #(3) Heterogenous An array of symbols: An array of strings: Only the creation time differsat compile time, arrays run-time. between literal arrays and arrays. Literal arrays are known Literal or not

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.60 nil and true , false as an object the value of which always refers

literal Point inspect ->methodDict-> aCompiledMethod to see it. ifTrue:[ Transcript show: ‘this is really true’] ifFalse: [ 1/0]

'mac' asArray is an array of character (#(false true nil) at: 2 )

Deep Into Literal Arrays to the same object. This is a first approximation present concept. However, if we examine literals according to this principle, is false in VisualWorks (VisualAge as a safer definition.) Literature defines literals as numbers, characters, strings of character, arrays, symbols, and two strings, floats , arrays but they do not refer (hopefully) to the same object. In fact literals are objectsstored created into at compile-time the or compiled even methodthe bytecode translation of source code. The literal frame is a part compiled already literal exist frame. in A the system compiledmethod that stores the literals used by methods. You can do and method is an object that holds Implementation dependent technical note: Literal arrays may only contain literal objects, Literature (Goldberg book) defines a

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.61 ifTrue:[ Transcript show: ‘Put 1’;cr. anArray at: 1 put: 1.] ifTrue:[ Transcript show: ‘Put 1’;cr. anArray at: 1 put: 1]

Deep into Literal Arrays (ii) |anArray| anArray := #(nil). (anArray at: 1 ) isNil |anArray| anArray := Array new: 1. (anArray at: 1 ) isNil The following example illustrates the difference between literal array and a newly created instance of Array via new:. Let us define the following method: SmallInteger>>m1 1 m1 will only displayliteral the frame message of Put the 1 method once. andSmallInteger>>m2 Because the the #at:put: array message #(nil) modified is the stored compiled into method the itself. 1 m2 will always display the message Put because in that case array is created at run-time. Therefore itinto the literal frame of compiled method. You can find this infomation yourself by is not detected as adefining these methods on a class, inspecting the class then its method dictionary and literal at compile-time and notthen the corresponding methods. stored

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.62 ^ #(100@100 200@200) copy

Deep into Literal Arrays (iii) ar This internal representation of methodunwanted side effects objects has led to the following idioms to prevent Never give direct access to a literal array but only provide copy. For example:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.63 ) IdentityDictionary

PrIt-> false

PrIt-> true

PrIt-> 'calvinzeBest' – Symbols are used as method selectors, unique keys for dictionaries – A symbol is a read-only object, strings are mutable objects – A symbol is unique, strings are not

Symbols vs. Strings #calvin == ‘calvin’ == #calvin, #zeBest Symbols are good candidates for identity based dictionaries ( Hints: Comparing strings is a factor of 5 to 10 slower than symbols. But converting string symbol more than 100 times more expensive.

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.64 | method parameter methodTemporary | | temporaryVariable blockTemporary blockParameter | : privateVariable indexed variable instanceVariable named oolVariable P SharedVariable – Maintains a reference to an object – Dynamically typed and can reference different types of objects – Shared (starting with uppercase) or private lowercase) lobalVariable G lassVariable C Variables Overview

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.65 |aStream| ... – To hold temporary values during evaluation (method execution) – Can be accessed by the expressions composing method. |anotherStream| ...

Temporary Variables |mac1 pc node1 printer mac2 packet| aClass>>printOn: aStream aClass>>printOn: aStream Hint: Avoid using the same name for a temporary variable and an argument, instance or another temporary variable or block temporary. Your code will be more portable. Instead of : Write Hint: Avoid using the same temporary variable for referencing two different objects

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.66 100@100 100@100

PrIt-> PrIt->

Assignments variable := aValue three := 3 raisedTo: 1 variable1 := variable2 aValue p1 := p2 0@100 p1 x: 100 p1 p2 But assignment is not done by message passing. This is one of Smalltalk’s few syntactic elements. In Smalltalk, objects are manipulated via implicit pointers: everything is a pointer. So take care when different variables point to the same object!

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.67 is an instance variable: contents aString := aString, 'From Lpr'. “, concatenate strings” addresse := aString addressee := aString , 'From Lpr' contents: aString addressee: aString accept: aPacket void Printer::accept(aPacket Packet)

Method Arguments - Can be accessed by the expressions composing method. - Exist during the execution of defining method. - Method Name In C++, Java: - But their values cannot be reassigned within the method. Invalid Example, assuming Valid Example

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.68 instanceVariableNames: 'name nextNode ' ... name := aSymbol. nextNode := aNode ^name

Instance Variables Object subclass: #Node Node>>setName: aSymbol nextNode: aNode Node>>name - Private to a particular instance (not all the instances of class like in C++). - Can be accessed by all the methods of defining class and its subclasses. - Has the same lifetime as object. Declaration Scope But preferably accessed using accessor methods

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.69 the class representing it. False False True . false is the boolean value, false instead of False ifFalse: [Transcript show: ‘False’] ifFalse: [Transcript show: ‘False’] unique instance of the class unique instance of the class False false (nothing) value for the uninitialized variables. Unique instance of class

Six pseudo-variables (i) false nil true - Smalltalk expressions make references to these variables, but cannot change their values. They are hardwired in the compiler. - Hints: Don’t use So produces an error, but works UndefinedObject -

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.70 that represents the context of the message but its semantics of a message. receiver MethodContext receiver ) self was used and NOT the superclass of the receiver (see method accept: thePacket] print: thePacket] super self super refers to the instance of ifFalse: [ ifTrue: [ in the method body refers also to the in the method body refers to "If the packet is(thePacket isAddressedTo: addressed to me, print it. Else just behave like a normal node"

Six pseudo-variables (ii) PrinterServer>>accept: thePacket self thisContext super lookup semantics) affects the lookup of method. It starts in superclass class which method where the The following variables can only be used in a method body. - - - of a method (receiver, sender, method, pc, stack). Specific to VisualWorks.

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.71 ) aSystemDictionary ( Smalltalk

PrIt-> 3.14

PrIt-> 3.14

Global Variables MyGlobal := 3.14 Smalltalk at: #MyGlobal put: 3.14 MyGlobal Smalltalk at: #MyGlobal Smalltalk removeKey: #MyGlobal Smalltalk (classes + globals) Undeclared (aPoolDictionary of undeclaredTranscript (System transcript) variables accessible fromScheduledControllers (window controllers) the compiler) Processor (a ProcessScheduler list of all the process) • Accessible from everywhere • Usually not really a good idea to use them; classVariable (if shared within an hierarchy or a instance variable of class) • To remove a global variable: • Capitalized Smalltalk will ask you if want to create a new global • Store in the default environment: • Some predefined global variables:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.72 (2+3) (1+2) in a method body. self

PrIt-> 15

PrIt-> 6

-> 3 PrIt-> 15 – a receiver, always evaluated – a selector, never evaluated – and a list possibly empty of arguments that are all evaluated

Three Kinds of Messages 2.4 inspect macNode name 1 + 2 (1 + 2) * (2 3) 3 * 5 6 gcd: 24 pcNode nextNode: node2 aLan connectNodesFromAddresses: #(mac node1 pc node2 node3 lpr) Unary Binary Keyword based A message is composed of: The receiver is linked with

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.73 aReceiver aSelector

-> printerNode

-> #node3 PrIt-> Date today September 19, 1997

PrIt-> true PrIt-> 3.1415926535898d

PrIt-> 1:22:20 pm

PrIt-> SmallInteger

Unary Messages node3 nextNode node3 name 1 class false not Date today Time now Double pi

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.74 +-/\*~<>=@%|&!?, $- aReceiver aSelector anArgument – arithmetic, comparison and logical operations – one or two characters taken from: – second character is never – no mathematical precedence so take care

Binary Messages 1 + 2 >= 3 100@100 'the', 'best' 3 + 2 * 10 -> 50 3 + (2 * 10) -> 23 Binary messages: Restriction:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.75 PrIt-> (1 to: 20) PrIt-> true receiver keyword1: argument1 keyword2: argument2 ... receiver.keyword1keyword2...(argument1 type1, argument2, type2) : return-type

Keyword Messages Workstation withName: #Mac2 mac nextNode: node1 Packet send: 'This packet travelled around to the printer' to: #lw100 aLan createAndDeclareNodesFromAddresses: #(node1 node2 node3) ofKind: Node 1@1 setX: 3 #(1 2 3) at: put: 25 1 to: 10 -> (1 10) anInterval Browser newOnClass: Point Interval from:1 to: 20 12 between: 10 and: 20 x > 0 ifTrue:['positive'] ifFalse:['negative'] In C-like languages would be:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.76 does not exist. ifTrue: includes:ifTrue: is a keyword based message, it has the same precedence than ifTrue:, so it should be evaluated – (E) > Unary-E Binary-E Keywords-E – at same level, from the left to right ifTrue: [...] ifTrue: [...] is an unary message, so it evaluated prior to x isNil (x includes: 3)

Composition 69 class inspect (0@0 extent: 100@100) bottomRight 2 + 3 squared -> 11 2 raisedTo: 3 + -> 32 #(1 2 3) at: 1+1 put: 10 + * 3 -> 36 Precedence Rules: isNil includes: prior to ifTrue: because the method Hints: Use () whenfine. two keyword based messages occur within a single expression, else the precedence order is

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.77 message1. message2. message3 . is a separator, not terminator "nodes definition" macNode := Workstation withName: #mac. pcNode := Workstation withName: #pc. node1 := Node withName: #node1. node2 := Node withName: #node2. node3 := Node withName: #node2.

Sequence |macNode pcNode node1 printerNode node2 node3 packet| Transcript cr. Transcript show: 1 printString. Transcript cr. Transcript show: 2 printString

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.78 too. #add: nextNode: anOrderedCollection receiver selector1 [arg] ; selector2 ... |workst| workst := Workstation new. workst name: #mac . workst nextNode: aNode Workstation new name: #mac ; nextNode: aNode . So all the messages will be sent to result of parenthesed is sent to the newly created instance of workstation and with: Is equivalent to: (OrderedCollection with: 1) add: 25; 35 name:

Cascade Transcript show: 1 printString. cr Transcript show: 1 printString ; cr In the following exampleand not # the FIRST message involvedexpression the newly created instance in the cascade is the first Important: the semantics of cascade is to send all messages in the receiver of FIRST message involved in cascade. Examples: Is equivalent to: Where

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.79 returns the receiver of cascade. newObject newObject and not the collection! yourself 35 (OrderedCollection with: 1) add: 25; 35 PrIt-> Returns newObject

yourself "Include newObject as one of the receiver's elements. Answer newObject." ^self addLast: newObject "Add newObject to the end of receiver. Answer newObject." lastIndex = self basicSize ifTrue: [self makeRoomAtLast]. lastIndex := + 1. self basicAt: lastIndex put: newObject. ^ (OrderedCollection with: 1) add: 25; 35 ; yourself -> OrderedCollection(1 25 35) One problem: Let us analyze a bit: OrderedCollection>>add: OrderedCollection>>addLast: How can we reference the receiver of cascade? By using yourself:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.80 the newly created instance and not method is linked to this instance yourself aWorkstation of the ) Workstation. self ^ self Workstation new name: #mac ; nextNode: aNode yourself Object>>yourself

Have You Really Understood Yourself ? (OrderedCollection with: 1) add: 25; 35 ; yourself anOrderedCollection(1) = self aWorkstation Yourself returns the receiver of cascade: Here the receiver of the cascade is So if you are thatAnswer: sure that you really understand yourself, what is the code of yourself? the class ( In

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.81 [nil] ifNone: [:aNode| aNode name = aSymbol] [super accept: thePacket] [self print: thePacket] | blockTemporary1 blockTemporary2 expression1. ...variable1 ... ] ifTrue: ifFalse: [ :variable1 :variable2 | (thePacket isAddressedTo: self)

Block (i): Definition “return the first node having address aSymbol” ^self detectNode: • A deferred sequence of actions • Return value is the result of last expression block • = Lisp Lambda-Expression, ~ C functions, anonymous functions or procedures Two blocks without arguments and temporary variables PrinterServer>>accept: thePacket A block with one argument and no temporary variable NetworkManager>>findNodeWithAddress: aSymbol

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.82 PrIt-> 420

PrIt-> 6 or value: or value:value: or value:value:value: or valueWithArguments: anArray

PrIt-> aBlockClosure

Block (ii): Evaluation [....] value |fct| fct:= [:x | x * + x]. fct value: 2 fct value: 20 fct The value of a block is the value of its last statement,Blocks are first class objects. except if there is anThey are created, passed as argument, stored into variables... explicit return ^ fct(x) = x ^ 2 + fct (2) = 6 fct (20) = 420

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.83 -> 4

Block (iii) |index bloc | index := 0. bloc := [index index +1]. index := 3. bloc value Integer>>factorial "Answer the factorial of receiver. Fail if receiver is less than 0. " | tmp .... tmp := 1. 2 to: self do: [:i | tmp := * i]. ^tmp For performance reasons, avoid referring to variables outside a block.

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.84 Primitives "Answer a new Point whose x value is the receiver and y argument." ^Point x: self y: y "Answer true if the receiver and argument are same object (have object pointer) and false otherwise. Do not redefine the message == in any other class! No Lookup." self primitiveFailed For optimization, if a primitive fails the code following is executed. Integer>>@ y World limits: We need some operations that are not defined as methods on object but direct calls on the underlying implementation language (C, Assembler,...)! == anObject + - < >* / = == bitShift:\\ bitAnd: bitOr: >= <= at: at:put: new new:

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.85 Syntax Basic objects Message constituants Message semantics Message precedence Block definition Block use yourself semantics pseudo-variables ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

What You Should Know To learn all that, the best thing to do is start up Smalltalk, type in some expressions, and look at the return values.

Object-Oriented Design with Smalltalk a Pure OO Language Syntax and Messages Universität Bern Ducasse Stéphane 6.86 Class definition Method definition Inheritance semantics Basic class instantiation ❑ ❑ ❑ ❑

7. Dealing with Classes

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.87 ' ' ' . ” is created. Packet class NameOfClass ' # instVarName1 instVarName2 contents addressee originator ' ' ' Packet class '' '' '' Packet # CategoryName LAN-Simulation ' ' is the unique instance of classVariableNames: poolDictionaries: instanceVariableNames: category: NameOfSuperclass subclass: Object subclass: instanceVariableNames: category: Class Definition: The Packet classVariableNames: 'ClassVarName1 ClassVarName2 poolDictionaries: A template is proposed by the browser: Example: Automatically a class named “ (To see it, click on the class button in browser) Packet

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.88 ' nil contents addressee originator ' Packet # ... instanceVariableNames:

Named Instance Variables NameOfSuperclass subclass: #NameOfClass instanceVariableNames: 'instVarName1 instVarName2' ... Object subclass: But instance variables cannot be accessed by class methods. • A client cannot directly access instance variables. No private, protected like in C++ • Need accessor methods to access instance variable. • Private to the instance: instance based (vs. C++ class-based) • Can be accessed by all the methods of class and subclasses (instance methods) • • Begins with a lowercase letter • Explicitly declared: a list of instance variables • Name should be unique / inheritance • Default value of instance variable is

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.89 self "comment stating purpose of message" | temporary variable names statements message selector and argument names “returns the default contents of a Packet” ^ ‘contents no specified’ aPacket originator: self. self send: aPacket “returns true if I’m addressed to the node aNode” ^ self addressee = aNode name

Method Definition Packet>>defaultContents Workstation>>originate: aPacket Packet>>isAddressedTo: aNode Follow the template: For example: How to invoke a method on the same object? Send message

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.90 ^ originator = aNode ^ originator ^ self originator = aNode ^ addressee addressee := aSymbol Packet>>isSentBy: aNode Packet>>originator Packet>>isSentBy: aNode Packet>>addressee Packet>>addressee: aSymbol

Accessing Instance Variables Using direct access for the methods of class is equivalent to use accessors Some accessors for the class Packet Hints: Do not directlynot be strongly linked at the structure level. access instance variables of a superclass from the subclass methods. This way classes will

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.91 #send: self expression returns the value of the expression as the result of ^ self send: thePacket.

Methods always Return a Value "Having received the packet, send it on. This is default behavior" self send: thePacket "Having received the packet, send it on. This is default behavior" self send: thePacket. ^self "Having received the packet, send it on. This is default behavior" ^ • Message = effect + return value • By default, a method returns Node>>accept: thePacket is equivalent to: Node>>accept: thePacket If we want to return the value returned by Node>>accept: thePacket • In a method body,the method execution. the

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.92 has or is #openOn: as

Some Naming Conventions ^ addressee addressee := aSymbol • Shared variables begin with an upper case letter • Private variables begin with a lower case letter • Use imperative verbs for methods performing an action like For accessors, use the same name as instance variable accessed: addressee addressee: aSymbol • For predicate methods (returning a boolean) prefix the method with isNil, isAddressedTo:, isSentBy: • For converting methods prefix the method with asString

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.93 Inheritance in Smalltalk • Single inheritance • Static for the instance variables. At class creation time theclass. No repetition of instance variables. instance variables are collected from the superclasses and the • Dynamic for the methods. Late binding (all virtual) methods are looked up at run-time depending on the dynamic type of the receiver.

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.94 node1 aPacket [false] accept: aPacket send: aPacket print: aPacket [true] isAddressedTo: nodePrinter nodePrinter accept: aPacket nextNode Workstation originate: aPacket accept: aPacket Node name accept: aPacket send: aPacket hasNextNode Printer

Remember... print: aPacket accept: aPacket

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.95 ifTrue: [self send: aPacket] self hasNextNode

Node instanceVariableNames: 'name nextNode ' ... "Having received the packet, send it on. This is default behavior subclasses will probably override me to do something special" "Precondition: there is a next node. Send packet to the node" self nextNode accept: aPacket

Object subclass: #Node Node methodsFor: ‘accessing’ .... Node methodsFor: ‘printing’ .... Node methodsFor: ‘send-receive’ accept: aPacket send: aPacket

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.96 ifTrue:[ Transcript show: 'A packet is accepted by the Workstation ', self name asString] ifFalse: [super accept: aPacket]

Workstation instanceVariableNames: '' ... “when a workstation accepts a(aPacket isAddressedTo: self) packet that is addressed to it, it just prints some trace in the aPacket originator: self. self send: aPacket

Node subclass: #Workstation Node methodsFor: ‘printing’ .... Node methodsFor: ‘send-receive’ accept: aPacket transcript” Node methodsFor: ‘send-receive’ originate: aPacket

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.97 ), Object is sent to the receiver, ⇔ #doesNotUnderstand: If no method is found and there superclass to explore (class a new method called with a representation of the initial message.

Message Sending & Method Lookup the lookup starts in class of receiver. If the method is defined in class dictionary, it returned. Else the search continues in superclasses of receiver's class. sending a message: receiver selector args applying a method looked up associated with selector to the receiver and args Looking up a method: When a message (receiver selector args) is sent, the method corresponding to message selector is looked up through the inheritance chain. ⇒

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.98 Node Node lookup stops + ⇒ Workstation Node Node lookup continues in is defined in ⇒ is an instance of is looked up in the class Workstation is an instance of Workstation lookup stops + method executed ⇒ accept: node1 macNode accept: Workstation. lookup stops + method executed 3. method executed macNode accept: aPacket 1. node1 accept: aPacket 1. 2. ⇒ Node Workstation Node nextNode Workstation originate: aPacket accept: aPacket is defined in is looked up in the class is an instance of is looked up in the class is not defined in is defined in Node accept: accept: macNode name: name name name accept: aPacket send: aPacket hasNextNode Printer 3. 2. 1. 2. 3. Method Lookup Examples (i) 4. print: aPacket accept: aPacket macNode name

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.99 Object is executed is looked up in the Object lookup continues in lookup stops + method ⇒ ⇒ Node Object lookup stops + exception ⇒ doesNotUnderstand: lookup continues in Node ⇒ so Node Object Node is not defined in is defined in Node node1 doesNotUnderstand: #(#print aPacket) is looked up in the class is not defined in is not defined in is an instance of Node is an instance of class doesNotUnderstand: node print: print: print: node1 doesNotUnderstand: executed (open a dialog box) 7. 1. 2. 3. 4. 6. 5. message: Method Lookup Examples (ii) 8. node1 print: aPacket

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.100 6 5 doesNotUnderstand: doesNotUnderstand: print: 3 print: 2 #node1 1 1 Object Node name accept: aPacket send: aPacket hasNextNode doesNotUnderstand: aMessage #(print: aPacket) node1 print: aPacket 4 node1 doesNotUnderstand:

Method Lookup Examples (ii)

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.101 ] super super accept: aPacket accept: aPacket ifTrue:[Transcript show: 'A packet is accepted by the Workstation ', self name asString] ifFalse: [

How to Invoke Overridden Methods? “when a workstation accepts packet that is addressed to it, it just prints some trace in the transcript” (aPacket isAddressedTo: self) When a packet is notnext node, i.e. to perform the default behavior defined by Node. addressed to a workstation, we just want to pass the packet to the Send messages to Workstation>> Hints: Do not send messages to super with different selectors than the original one. It introduces implicit dependency between methods with different names.

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.102 . class of the receiver super the lookup of method begins in superclass class is a pseudo-variable that refers to the receiver of message. , the lookup of method begins in self super super , causes the method lookup to begin searching in superclass of class self

Semantics of super super • Like • Used to invoke overridden methods. • When using • When using the method containing super expression and NOT in superclass of receiver class. Otherwise said: • the method containing

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.103 t super accept: aPacke Node Workstation <> accept: aPacket accept: aPacket DuplexWorkstation agate lookup ⇒ lookup stops + ⇒ hypothesis: WRONG is an instance of DuplexWorkstation continues in Workstation method executed the receiver class. The superclass of class = Workstation agate 3. accept: is defined in Workstation 4. Workstation>>accept: does a super accept: 5. By our hypothesis: super = lookup in the superclass of accept: is looked up in the class DuplexWorkstation 2. accept: is not defined in DuplexWorkstation Let us be Absurd! 1. That's loop ⇒ So that hypothesis is WRONG !! Let us suppose the “IF super semantics = starting the lookup of method in superclass of the receiver class” agate accept: aPacket

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.104 (basic)new/new: – Direct Instance creation: – Messages to instances that create other objects – Class specific instantiation messages

Object Instantiation Objects can be created by:

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.105 are class methods be overridden

never returns a newly and UNINITIALIZED instance basicNew: / ⇒ should

-> OrderedCollection () new: to specify the size of created instance (indexed variable) and basicNew /

-> aPacket can be specialized to define customized creation #basicNew: / basicNew: / #new: basicNew / /

Direct Instance Creation: (basic)new/new: OrderedCollection new Packet new Packet new addressee: #mac ; contents: ‘hello mac’ Array new: 4 -> #(nil nil nil) new basicNew new aClass new #new: • Instance variable values = nil • • # • # • #

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.106 Messages to Instances that Create Objects 1 to: 61@2(0@0) extent: (100@100) (a rectangle) #lulu asString (a string) 1 printString (a string) 3 asFloat (a float) #(23 2 3 4) asSortedCollection (a sortedCollection) (an interval) (a point)

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.107 . WriteStream on: (String new: 16) -> aString

-> an Interval to: stop

aPoint Interval from: self to: stop by: 1 Point x: self y: y -> ^ | aStream aStream := ^ Opening the Box self printOn: aStream. ^aStream contents "Answer an Interval from the receiver up to argument, stop, with each next element computed by incrementing the previous one 1." 1 to: 6 Number>> 1 printString Object>>printString "Answer a String whose characters are description of the receiver." Number>>@ y "Answer a new Point whose x value is the receiver and y argument." 1@2

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.108 -> 179@95 corner: 409@219 Array with: 1 'lulu' OrderedCollection with: 1 2 3 Rectangle fromUser Browser browseAllImplementorsOf: #at:put: Packet send: ‘Hello mac’ to: #mac Workstation withName: #mac

Class specific Instantiation Messages

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.109 self super Defining a class Defining methods Semantics of Semantics of Instance creation ❑ ❑ ❑ ❑ ❑

What you should know

Object-Oriented Design with Smalltalk a Pure OO Language Dealing with Classes Universität Bern Ducasse Stéphane 7.110 , Set , SortedCollection , OrderedCollection ...) , Array , Bag Booleans Basic loops Overview of Collection — the superclass more than 80 classes: ( Dictionary Loops and Iteration abstractions Common object behavior ❑ ❑ ❑ ❑ ❑

8. Basic Objects, Conditional and Loops

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.111 False and true True , false Boolean is the class of true, its unique instance! True

PrIt-> false and not an error is the boolean value and are objects described by classes true true 1 < 2 ifTrue: [...] ifFalse: 1 < 2 ifFalse: [...] ifTrue: 1 < 2 ifTrue: [...] 1 < 2 ifFalse: [...] - uniform but optimized and inlined (macro expansion at compile time) orBlock will only be valued if aBooleanExpression is andBlock will only be valued if aBooleanExpression is false and: [1 error: 'crazy'] and aBooleanExpression comparison anotherBooleanExpression (1 isZero) & false aBooleanExpression and: andBlock, or: orBlock aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock aBoolean ifFalse: aTrueBlock ifTrue: aFalseBlock aBoolean ifTrue: aTrueBlock aBoolean ifFalse: aFalseBlock

Boolean Objects false - Logical Comparisons &, |, xor:, not - - Lazy Logical operators - Conditionals Hints: Take care — Hints: Why do conditional expressionsments of the message are evaluated. So blocks necessary to avoid evaluating both branches. use blocks? Because, when a message is sent, the receiver and the argu-

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.112 [x

Some Basic Loops

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.113 [aBlock value. count := + 1] self whileTrue: aBlock] whileTrue: whileTrue: aBlock whileTrue timesRepeat: aBlock

For the Curious! BlockClosure>> ^ self value ifTrue:[aBlock value. BlockClosure>> ^ [self value] whileTrue:[] Integer>> "Evaluate the argument, aBlock, the number of | count times represented by count := 1. the receiver." [count <= self]

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.114 String ArrayCharacterArrayIntegerArray elements = character SortedCollection any kind of elements explicit order IdentityDictionary key based on identity

Collections ArrayedCollection fixed size + key = integer IntervalLinkedListOrderedCollectionIdentitySet size dynamic + arrival order Dictionary dynamic chaining of the element arithmetique progression identification based on identity element = associations + key based • Only the most important • Some criteria to identify them. Access: indexed, sequential or key-based. Size: fixed or dynamic. Element type: any well-defined type. Order: defined, defineable or none. Duplicates: possible not Sequenceable ordered BagSet possible duplicate + no order no duplicate + order

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.115 n Bag Set y Duplicates Allowed n n Keyed y y UniqueKey n Dictionary Identity Dictionary Integer Key y Array String n n Collection Ordered y Adds Allowed Sorted y

Another View Collection Sorted

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.116 in subclasses #asBag, #asSet, #asOrderedCollection, #size, #capacity, #at: anInteger, anInteger put: #remove: anElement, #remove:anElement ifAbsent: aBlock, #with: anElement, #with:with:, #with:with:with:, #isEmpty, #includes: anElement, #contains: aBlock, #add: anElement, #addAll: aCollection defined, redefined, optimized or forbidden

Collection Methods Will be Accessing: anElement Testing: occurencesOf: anElement Adding: Removing: #with:with:with:with:, #with:All: aCollection #removeAll: aCollection Enumerating (See generic enumerating) #do: aBlock,#detect:, #detect: aBlock ifNone: aNoneBlock, #inject: avalue #collect: aBlock,into: aBinaryBlock #select: aBlock, #reject: aBlock, Converting: #asSortedCollection, #asArray, #asSortedCollection: aBlock Creation:

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.117 PrIt-> #(#calvin #loves #suzie) |arr| arr := #(calvin hates suzie). arr at: 2 put: #loves. arr

Sequenceable Specific (Array) Accessing: #first, #last, #atAllPut: anElement, #atAll: anIndexCollection: put: anElement Searching (*: + ifAbsent:) #indexOf: anElement, anElement ifAbsent: aBlock Changing: #replaceAll: anElement with: anotherElement Copying: #copyFrom: first to: last, copyWith: anElement, copyWithout: anElement

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.118 -> 4

-> Set ('titi') |dict| dict := Dictionary new. dict at: 'toto' put: 3. dict at: 'titi' ifAbsent: [4]. dict at: 'titi' put: 5. dict removeKey: 'toto'. dict keys

KeyedCollection Specific (Dictionary) Accessing: #at: aKey, aKey ifAbsent: aBlock, ifAbsentPut: aBlock, #at: aKey put: aValue, #keys, #values, #associations Removing: #removeKey: aKey, aKey ifAbsent: aBlock Testing: #includeKey: aKey Enumerating: #keysAndValuesDo: aBlock, #associationsDo: #keysDo: aBlock

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.119 [ :each | result at: each put: (aCollection each) abs]. |result| result := aCollection species new: size. 1 to: aCollection size do: ^ result ^ aCollection collect: [:each| each abs]

Choose your Camp! absolute: aCollection absolute: aCollection

You could write: Sure! Or Really important: Contrary to the first solution, this solution works well for indexable collections and also for sets.

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.120 do: [:x :y| Transcript show: (y ** x) printString ; cr ]

PrIt-> #(true false true false) aCollection do: aOneParameterBlock aCollection collect: aOneParameterBlock aCollection with: anotherCollection do: aBinaryBlock

Iteration Abstraction: do:/collect: #(15 10 19 68) do: [:i | Transcript show: i printString ; cr ] #(15 10 19 68) collect: [:i | i odd ] #(1 2 3) with: #(10 20 30)

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.121 PrIt-> 1

PrIt-> 19 detect: aOneParameterPredicateBlock ifNone: aNoneBlock aCollection select: aPredicateBlock aCollection reject: aPredicateBlock aCollection detect: aOneParameterPredicateBlock aCollection

Iteration Abstraction: select:/reject:/detect: #(15 10 19 68) select: [:i|i odd] -> 19) #(15 10 19 68) reject: [:i|i odd] -> #(10 #(12 10 19 68 21) detect: [:i|i odd] #(12 10 12 68) detect: [:i|i odd] ifNone:[1]

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.122 aCollection inject: aStartValue into: aBinaryBlock

Iteration Abstraction: inject:into: |acc| acc := 0. #(1 2 3 4 5) do: [:element | acc := + element]. acc -> 15 #(1 2 3 4 5) inject: 0 into: [:acc :element| acc + element] -> 15

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.123 -> true

-> true

-> false

-> 5 #(1 2 3 4 5) includes: #(1 2 3 4 5) size #(1 2 3 4 5) isEmpty #(1 2 3 4 5) contains: [:each | each isOdd] aCollection includes: anElement aCollection size aCollection isEmpty aCollection contains: aBooleanBlock

Collection Abstraction

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.124 ] ] aBlock ] ifNone: self declareNode: (aNodeClass withName: each) aNodeClass) do: [:each | includes: aNode name = aSymbol aLan findNodeWithAddress: #mac detect: [:aNode| aLan createAndDeclareNodesFromAddresses: #(node1 node2 node3) ofKind: Node ifTrue: [anArrayOfAddresses ifFalse: [self error: aNodeClass name , ' is not a class of nodes']

Examples of Use: NetworkManager ^self findNodeWithAddress: aSymbol ifNone: [nil] ^nodes "given a list of addresses, create the corresponding nodes aNodeClass kind" (Node withAllSubclasses NetworkManager>>findNodeWithAddress: aSymbol NetworkManager>>findNodeWithAddress: aSymbol ifNone: aBlock NetworkManager>>createAndDeclareNodesFromAddresses: anArrayOfAddresses ofKind: aNodeClass

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.125 #shallowCopy is #copy #==, #~~, #=, #=~, #isNil, #notNil #shallowCopy, #copy : the copy shares instance variables with receiver. 161 instance methods + 19 class ⇒ a a copy

Common Shared Behavior (i) #shallowCopy #class - Comparison of objects: - Copying of objects: - - Object is the root of inheritance tree. - Defines the common and minimal behavior for all objects in system. default implementation of

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.126 . #== too! is

PrIt-> false

#= PrIt-> true

PrIt-> true #hash . One should override #= not == is should never be overridden. On Object ~~ if the structures are equivalent (the same hash number) , #== true not = is

Identity vs. Equality (Array with: 1 2) = with:1 with:2) (Array with: 1 2 ) == with:2) (Array with: 1 2 ) = with:2) = anObject returns == anObject returns true if the receiver and argument point to same object. ~= Take care when redefining

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.127 , #printString, #printOn: aStream #browse, #inspect '((OrderedCollection new) add: 4; 3; yourself)' #storeString, #storeOn: aStream -> OrderedCollection (4 3) #(123 1 2 3) printString -> '#(123 3)' Date today printString -> 'October 5, 1997' Date today storeString -> '(Date readFromString: ''10/5/1997'')' OrderedCollection new add: 4 ; 3 storeString ->

Common Shared Behavior (ii) Object readFromString: '((OrderedCollection new) add: 4; 3; yourself)' #error: aString, #doesNotUnderstand: aMessage, #halt, #shouldNotImplement, #subclassResponsibility readFrom: aStream, readFromString: aString Print and store objects: But you need to have the compiler, so for a deployed image this is not convenient Create instances from stored objects: class methods Notifying the programmer: Examing Objects:

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.128 ) returns a string representing the object recreates an object #printOn: (calls returns a string whose evaluation recreates an object equal to the opens an inspector opens a browser returns the class of object stops the execution and opens a debugger (to be inserted in a body of a method)

Essential Common Shared Behavior #class #inspect #browse #halt #printString receiver #readFromString: aStream #storeString

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.129 Boolean protocol Collection protocol Conditionals Loops and Iteration Abstractions Common object protocol ❑ ❑ ❑ ❑ ❑

What you should know But the best way to learn is play with a Smalltalk system! Yes, again!

Object-Oriented Design with Smalltalk a Pure OO Language Basic Objects, Conditional and Loops Universität Bern Ducasse Stéphane 8.130 9. Numbers

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.131 30 \\ 9 , modulo 30 // 9 3 squared , square , integer division 9 sqrt 30 / 9 5 + 6, - * division square root 30 between: 5 and: 40 3.8 ceiling -> 4 3.8 floor -> 3 3.811 roundTo: 0.01 -> 3.81 3.8 isInteger 3.8 even, odd positive, negative, sign, negated

The Basics of Numbers min:, max:, cos, ln, log, log: arcSin, exp, ** • Arithmetic • Range • Tests • Signs • Other • Rounding

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.132 ? argument AND the receiver

passing the receiver as an argument ifTrue: [ aNumber asFloat + self] ifFalse: [ self addPrimitive: aNumber] ifTrue: [aNumber asFloat + self] ifFalse: [self addPrimitive: aNumber] (aNumber isKindOf: Float) (aNumber isKindOf: Integer)

Deeper into Numbers: Double Dispatch (i) How to select a method depending on the Send a message back to the argument Example: Coercion between Float and Integer A not very good solution: Integer>>+ aNumber Float>>+ aNumber

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.133 ^ anInteger asFloat + self ^aFloat + self asFloat (c) Integer>>sumFromInteger: anInteger (d) Float>>sumFromInteger: anInteger (e) Integer>>sumFromFloat: aFloat (f) Float>>sumFromFloat: aFloat ^ aNumber sumFromInteger: self ^ aNumber sumFromFloat: self

Deeper into Numbers: Double Dispatch (ii) (a) Integer>>+ aNumber (b) Float>>+ aNumber Some Tests: 1 + 1: (a->c) 1.0 + 1.0: (b->f) 1 + 1.0: (a->d->b->f) 1.0 + 1: (b->e->b->f)

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.134 Generality

&

Coercion

Numbers:

into

Deeper "Answer a number representing the argument, aNumber, that is same kind of Number as the receiver. Must be defined by all Number classes." ^self subclassResponsibility "Answer the number representingin this hierarchy coerces to numbers the ordering higher in of hierarchy the (i.e., receiver with in larger generality the^self subclassResponsibility numbers)." generality hierarchy. A number "Convert a number to compatible form" ^aNumber asInteger ^40 SmallInteger 20 Integer 40 Fraction 60 FixedPoint 70 Float 80 Double 90 ArithmeticValue>>coerce: aNumber ArithmicValue>>generality Integer>>coerce: aNumber Integer>>generality Generality

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.135 ifTrue: [^(aNumber coerce: self) perform: aSymbol with: aNumber]. ifTrue: [^self perform: aSymbol with: (self coerce: aNumber)].

Deeper into Numbers: #retry:coercing: "The argument anInteger, known to be a kind of integer, encountered a problem on addition. Retry by coercing either anInteger or self, whichever is the less general arithmetic value." Transcript show: 'here arthmeticValue>>sunFromInteger' ;cr. ^anInteger retry: #+ coercing: self "Arithmetic represented byargument, the aNumber, symbol, because aSymbol,the of could argument, depending the not onsame, then this message should not have been sent so an error notification is provided." differences be which performed in has with representation. higher the generality, and receiver Coerce tryself generality < aNumber and either again. the the If the receiver generalities or are the self generality > aNumber self error: 'coercion attempt failed' ArithmeticValue>>sumFromInteger: anInteger ArithmeticValue>>retry: aSymbol coercing: aNumber

Object-Oriented Design with Smalltalk a Pure OO Language Numbers Universität Bern Ducasse Stéphane 9.136 is executed when an exception occurs string describing the actual exception is the root of exception hierarchy: 84 predefined exceptions Error Notification defaultAction description ❑ ❑

10. Exceptions Standardized by ANSI and available since VW3.0 Exception The two most important classes are: Specialised into predefined exceptions Subclass them to create your own exceptions Some methods of Exception:

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.137 Inherited from Error Inherited from Error Do nothing continuing executing Display Yes/No dialog and return a boolean value t the signaler ArithmeticError Exceptional Eventarithmetic Default Action object that did not define a corresponding method not impair continued execution of the program user should be informed about Exception class

The Main Exceptions ErrorArithmeticError Any error evaluating an Any program error Open a Notifier MessageNotUnderstood A message was sent to an NotificationWarningZeroDivide Any unusual event that does An unusual event that the Inherited from

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.138 ] 0....] Transcript show: exception description, cr. on:do: Transcript show: ‘ division by zero’ ZeroDivide ] on: do: [:exception| is defined using is composed by an exception class and a handler block x/y |x y| x := 7. y 0. [ ZeroDivide [:theException|

Basic Example of Catching an Exception Handler An Exception Handler completes by returning the value of handler block in place the value of protected block (here [x/y]). We can exit the current method by putting an explicit return inside handler block

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.139 on: ZeroDivide, Warning do: [ :ex| what you want] on: exceptionSets do: [ :ex| what you want]

Exception Sets [do some work] |exceptionSets| exceptionSets := ExceptionSet with: ZeroDivide Warning. [do some work] Or

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.140 Signaling Exception Error raiseSignal Warning raiseSignal: ‘descriptionexception’ that you will get by asking description to the

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.141 Error,bbb added to the beginning of list ⇒ list empty ⇒ Process starts [aaaa] on: Error do: [bbb] When an exception is signaled, theof the exception handler. system sends a message to theIf the handler cannot handle exception, next one is asked first handler If no handler can handle the exception then default action is performed ❑ ❑ ❑ ❑ ❑

Exception Environment Each process has its own exception environment: an ordered list of active handlers.

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.142 ’] ’]) Value from protected block Value from handler ‘Value from handler’ ‘Value from protected block’ on: Error do: [:ex|ex return: ‘ on: Notification do: [:ex|ex resume: ‘Value from handler’]) Nonresumable: like Error ☞ Resumable: like Warning, Notification ☞ Here Notification raiseSignal raises an exception, then the context is restored and the value normally returned ([Error raiseSignal. ‘Value from protected block’] ([Notification raiseSignal. ‘ ❑ ❑

Resumable and Non-Resumable A handler block completes by executing the last statement of block. The value of the last statement is then returned by handler block. Where this value should be returned depends:

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.143 '] '. '5']) Value from protected block Value from handler Value from handler Value from protected block : 'Value from handler'. '5']) resume on: Notification do: [:ex| Transcript show: 'Entering handler '. 'Value from handler'. '5']) on: Notification do: [:ex| Transcript show: 'Entering handler '. ex on: Notification do: [:ex| Transcript show: 'Entering handler '. ex return: ' ([Notification raiseSignal. 'Value from protected block'] ([Notification raiseSignal. ' ([Notification raiseSignal. 'Value from protected block'] -> Entering handler Resume:/Return: Transcript show: -> Entering handler 5 Transcript show: -> Entering handler Transcript show:

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.144 Attempts to continue processing the protected block, ends processing the protected block that triggered (VW specific) Resumes on a resumable and returns resignal the exception as another one evaluates a new block in place of the protected resume: return: exit: or or as with pass, except will regain control if the outer handler resumes re-evaluates the protected block exit the current handler and pass to the next outer handler, control does or exit nonresumable exception resume immeditely following the message that triggered exception. return exception retry retryUsing: resignalAs: pass not return to the passer outer ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Exiting Handlers Explicity exit:, resume: and return:of the final statement handler block return their argument as the return value, instead of the value

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.145 ] do: Number divisionByZeroSignal [:ex | Transcript cr; show: 'divideByZero abort'. ex return ] on: 10.0 / i. Transcript cr; show: i printString [ [ :i | ] -2.0 to: 2.0 do:

Examples -2.0 -1.0 divideByZero abort 1.0 2.0 Look in Exception class examples categories

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.146 y := 0.00001. exception retry] recreates the exception environment of active handlers on: ZeroDivide do: [:exception|

Examples [ x /y] retry

Object-Oriented Design with Smalltalk a Pure OO Language Exceptions Universität Bern Ducasse Stéphane 10.147 11. Streams

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.148 ExternalStream InternalStream ExternalReadAppendStream ExternalReadWriteStream ExternalReadStream ExternalWriteStream ReadWriteStream ReadStream WriteStream ExternalStream InternalStream PositionableStream (abstract) - collection is a Smalltalk collection: - collection is a file or an object that behaves like collection: PeekableStream (abstract)

Streams • Allows the traversal of a collection • Associated with a collection Stream (abstract) • Stores the current position

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.149 PrIt-> OrderedCollection (1 4 8 2 6 7)

-> 1 -> 2 -> 1

An Example |st| st := ReadWriteStream on: (OrderedCollection new: 5). st nextPut: 1. st nextPutAll: #(4 8 2 6 7). st contents. st reset. st next. st position: 3. st next. st := #(1 2 5 3 7) readStream. st next.

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.150 . aStream aStream nextPutAll: ' and next node:'; print: self nextNode name] nextPutAll: ' with name:'; print: self name. printOn: aStream. aStream aStream self hasNextNode ifTrue: [ "Answer a String whose characters are description of the receiver." | aStream aStream := WriteStream on: (String new: 16). self ^aStream contents super printOn:

printSring, printOn: Object>>printString Node>>printOn:

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.151 (index elements included) inserts the collection element from next position increases the position after anElement inserts element at the next position returns all the elements increases the position of n returns the n next elements returns true if at the end of collection returns the next element

Stream classes(i) #atEnd PeekableStream. Access to the current without passing next #peek #skipFor: anArgument #skip: n #skipUpTo: anElement Creation #on: aCollection, #on: aCol from: firstIndex to: lastIndex #nextPutAll: aCollection Stream. #next #next: n #contents #nextPut: anElement

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.152 (without reinitializing the stream) #with: returns the size of internal collection

Stream Classes (ii) PositionableStream #skipToAll: #throughAll: #upToAll: #position #position: anInteger #reset #setToEnd #isEmpty InternalStream #size Creation ReadStream WriteStream and ReadWriteStream ExternalStream and subclasses

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.153 instead of #endEntry + #nextPutAll: that has aStream TextCollector is a via dependencies asks for refreshing the window self nextPutAll: aString. self endEntry

Stream tricks TextCollector>>show: aString |st sc| st := ReadStream on: ‘we are the champions’. sc := Scanner new on: st. [st atEnd] whileFalse: [ Transcript nextPutAll: sc scanToken, ‘ * ‘]. Transcript endEntry #show: Transcript #endEntry If you want to speed up a slow trace, use

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.154 ] readStream close ] valueNowOrOnUnwindDo: [ whileFalse: [....] How to ensure that the open files are closed How to find open files (VW specific) [readStream atEnd] |readStream| readStream := aFilename readStream. [ (ExternalStream classPool at: #OpenStreams) copy inspect ❑ ❑

Streams and Blocks MyClass>readFile: aFilename

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.155 “do not forget to close the files too” outStream nextPutAll: (inStream upTo: $”). inStream skipTo: $”].

Streams and Files #appendStream (addition + creation if file doesnot exists) #newReadAppendStream, #newReadWriteStream (if receiver exists, contents removed) #readAppendStream, #readWriteStream, #readStream, #writeStream |inStream outStream | inStream := (Filename named: ‘/home/ducasse/test.st’) readStream. outStream := (Filename named: ‘/home/ducasse/testout.st’) writeStream. “(or ‘/home/ducasse/ducasse’ asFilename)” [inStream atEnd] whileFalse: [ ^outStream contents Filename. Example: removing Smalltalk comments of a file

Object-Oriented Design with Smalltalk a Pure OO Language Streams Universität Bern Ducasse Stéphane 11.156 Advanced Classes MVC Concurrency Metaclasses Debugging Internals ❑ ❑ ❑ ❑ ❑ ❑

Advanced Smalltalk

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane Indexed Classes Class as Objects Class Instance Variables and Methods ClassVariables PoolDictionary ❑ ❑ ❑ ❑ ❑

12. Advanced Classes

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.158 can only have: subclasses support any kind of subclasses #subclass: #variableSubclass: #variableByteSubclass #isPointers, #isBits, #isBytes, #isFixed, variableByteSubclass: or #subclass:...#variableSubclass:#variableByteSubclass String, ByteArray Array, CompiledMethod Packet, Workstation classes defined using classes defined using classes defined using – can only be defined if the superclass has no instance variable – pointer classes and byte don’t mix – only byte subclasses ❑ ❑ ❑

Types of Classes Indexed Named Definition MethodNoYesYes Yes Yes No Method related to class types: #isVariable, #kindOfSubclass Examples variableSubclass:

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.159 Packet of Array ‘addressee’ Named or indexed instance variables Named: Indexed: Or looking at them in another way: Objects with pointers to other objects Objects with arrays of bytes (word, long) ❑ ❑

Two Views on Classes Difference for efficiency reasons: arrays of bytes (like Cto a single byte. strings) are faster than storing an array of pointers, each pointing

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.160 -> true Array

-> #(nil nil nil)

Indexed Classes ArrayedCollection variableSubclass: #Array instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed' Array new: 4 #(1 2 3 4) class isVariable For classes that need a variable number of instance variables Example: the class

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.161 max #at:put: and #new: anInstance at: 1 #at: answers the value not receiver) returns the number of indexed instance variables #at:put: ( First access: #size Instantiated with Indexed variable is implictly added to the list of instance variables Only one indexed instance variable per class Access with Subclasses should also be indexed ❑ ❑ ❑ ❑ ❑ ❑ ❑

Indexed Class/Instance Variables |t| t := (Array new: 4). t at: 2 put: 'lulu'. t at: 1 -> nil

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.162 Node Workstation name accept: aPacket send: aPacket hasNextNode originate: aPacket accept: aPacket instance of ). macNode name Object is link. (except name ⇒ Object lookup continues in instance of ⇒ Workstation lookup stops + method ⇒ Workstation Node is an instance of is not defined in Workstation is defined in Every object is an instance of a class. Every class is ultimately a subclass of When anObject receives a message,in its class and/or superclasses. the method is lookup A class defines the structure and behavior of all its instances. Each instance possesses its own set of values. Each instance shares the behavior withbevahior defined in its class via the other instances the macNode looked up in the class name Node name executed ❑ ❑ ❑ ❑ ❑ ❑ 1. 2. The meaning of “Instance of” (i) 3. Example: macNode name

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.163 is withName: ⇒ lookup continues in the ⇒ is looked up in the class lookup stops + method executed withName: ⇒ lookup stops + method executed ⇒ ⇒ Node class Workstation class Workstation class class = Node class Node class Node class Workstation class is an instance of Workstation is not defined in defined in is defined in is an instance of A class is an object too, so messages sent to it are looked up into the of the class, its metaclass. Every class (X) is the unique instance of its associated metaclass named X class Node Node class withName: Workstation looked up in the class withName: superclass of withName: ❑ ❑ Node withName: #node1 1. 2. Workstation withName: #mac 1. 2. 3.

The meaning of “Instance of” (ii) Example:

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.164 instance of method lookup class Workstation withName: #mac Node class Object class withName: Workstation class Node Object Workstation name accept: aPacket send: aPacket hasNextNode originate: aPacket accept: aPacket macNode name instance method lookup

Lookup and Class Messages

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.165 Node Behavior , is looked up in the class lookup continues in the superclass of new: ⇒ lookup continues in the superclass of ⇒ ⇒ lookup stops + method executed. ⇒ ClassDescription , Node class Node class Object class Behavior Class Object class .... = is not defined in is defined in is an instance of is not defined in new: is defined in Behavior (the ancestor of Array class) Node class new: Node class new: Node class new: 4. Node new: #node1 1. 2. The Meaning of “Instance-of” (iii) 3. This is the same for Array new: 4 Hints: Behavior is the essence of a class. ClassDescription represents extra functionality for browsing the class. Class supports poolVariable and classVariable.

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.166 instance of its associated metaclass sole Everything is an object Each object is instance of one class A class (X) is also an object, the named X class An object is a class if and only it can create instances of itself. instance creation class information (inheritance link, instance variables, method compilation...) ❑ ❑ ❑ ❑ ❑ ❑

Metaclass Responsibilities Node allSubclasses -> OrderedCollectionServer PrintServer) (WorkStation OutputServer Workstation File- LanPrint allInstances -> #() Node instVarNames -> #('name' 'nextNode') Workstation withName: #mac -> aWorkstation Workstation selectors -> IdentitySet (#accept: #originate:) Workstation canUnderstand: #nextNode -> true Concept: Metaclass Responsibilities: Examples:

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.167 has an instance NetworkManager class being an instance of uniqueInstance. instanceVariableNames: 'uniqueInstance'

Class Instance Variables NetworkManager class Like any object, a class is an instance of that can have variables represent the state of a class. Singleton Design Pattern: a class with only one instance NetworkManager variable named Hints: An instance variable ofHowever, a you class should can use be class used...) and use classVariable instead. instance to variables represent to information represent shared state by about all the the class instances (like of the the number class. of instances,

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.168 #isAddressedTo: #originator #initialize #contents #contents:) is the first metaclass. All other metaclasses inherit from it describes the minimal structure of a class: Behavior Behavior – superclass – subclasses – method dictionary – format (instance variable compressed description) instanceVariableNames: 'superclass methodDict format subclasses ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Classes' Object subclass: #Behavior ❑ ❑

About Behavior Packet superclass -> Object Packet subclasses - #() Packet selectors -> IdentitySet (#originator: #addressee: #addressee #isOriginatedFrom: #printOn: Packet allInstVarNames -> OrderedCollection ('addressee'Packet isDirectSubclassOf: Object -> true 'originator' 'contents' 'visitedNodes') Example of Queries

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.169 class new uniqueInstance NetworkManager findNode... nodes NetworkManager can only access class instance variable and not variables ). NetworkManager class>>new nodes Packet new Packet send: ‘Smalltalk is fun’ to: #lpr Workstation withName: #mac Workstation withName: #mac connectedTo: #lpr As any object a metaclass can have methods that represent the behavior of class. Some examples of class behavior: - class definition, finding all instances of a - navigation in the hierarchy, - finding the instance variable names,- instance creation, compiling methods methods Can only access instance variable of the class: Examples: uniqueInstance (like Default Instance Creation class method: - new/new: and basicNew/basicNew: (see Direct Instance Creation) Specific instance creation method ❑ ❑ ❑ ❑ ❑

Class Method

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.170 Shared Variables and directly accessible by all the instances of NameOfClass begins with an uppercase letter # shared ⇒ NetworkManager # a classVariable is a classVariable can be directly accessed in instance methods and class methods Sometimes classVariable can be replaced by class methods class and subclasses A pretty bad name: should have been called Shared Variable ... classVariableNames: 'ClassVarName1 ClassVarName2' ...... classVariableNames: ‘Domain’ ❑ ❑ ❑ ❑ ❑ NameOfSuperclass subclass: NetworkManager class>>domain ^ ‘iam.unibe.ch’ classVariable Object subclass: How to share state between all the instances of a class: Use classVariable

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.171 class a table describes the types of characters and directly accessible by all the instances shared Scanner a classVariable is (strings, comments, binary....). The originalits value is loaded into the instance variable. It then possible to change table is stored intovalue of the instance variable to have a different scanner. a classVariable, subclasses Class instance variables, just like normal can be accessed only via class message and accessors: – an instance variable of a class is private to this class. – an instance Take care when you changetree is impacted! the value of a classVariableClassVariables can be used in conjunction with instance variables to cache the whole inheritance some common values that can be changed locally in the classes. Examples: in the instanceVariableNames: 'source mark prevEnd hereChar token tokenType buffer typeTable ' classVariableNames: 'TypeTable ' category: 'System-Compiler-Public Access' ❑ ❑ ❑ ❑ ❑

Class Instance Variables / ClassVariable Object subclass: #Scanner

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.172 . uniqueInstance class instance variables class methods ifTrue:[ uniqueInstance := super new] uniqueInstance uniqueInstance isNil ^ NetworkManager class>>new classVariables Domain instance methods nodes nodes detect: aBoolBlock ^ Summary of Variable Visibility instance variables NetworkManager>>detectNode: aBoolBlock

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.173 Example From The System: Geometric Class instanceVariableNames: '' classVariableNames: 'InverseScale Scale ' ... "Reset the class variables." Scale := 4096. InverseScale := 1.0 / Scale Object subclass: #Geometric Geometric class>>initialize

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.174 Circle instanceVariableNames: 'center radius' classVariableNames: '' ^center center := aPoint. radius := aNumber | r r := self radius asLimitedPrecisionReal. ^r class pi * r ^self radius * 2 ^self basicNew setCenter: aPoint radius: aNumber Geometric subclass: #Circle Circle>>center Circle>>setCenter: aPoint radius: aNumber Circle>>area Circle>>diameter Circle class>>center: aPoint radius: aNumber

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.175 begins with a uppercase letter. ⇒ instanceVariableNames: 'string runs ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Collections-Text' Also called Pool Variables. Shared variable Variable shared by a group of classes not linked inheritance. Each class possesses its own pool dictionary. They are not inherited. Examples of PoolDictionaries from the System:Text ❑ ❑ ❑ ❑ ❑ ❑

poolDictionaries CharacterArray subclass: #Text Elements stored into TextConstants likefrom all the classes like ParagraphEditor.... Ctrl, CR, ESC, Space canOn VW poolDictionary should not be an IdentityDictionary be directly accessed

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.176 . ' NetworkConstant dictionary global poolDictionaries contents addressee originator ' 'NetworkConstant' Packet # is directly accessed in the ... NetworkConstant at: #rates Smalltalk at: #NetworkConstant put: Dictionary new. NetworkConstant at: #rates put: 9000. Node>>computeAverageSpeed classVariableNames: ‘Domain’ poolDictionaries: ... .. rates Example of PoolVariables instanceVariableNames: Instead of Write: Object subclass: Node>>computeAverageSpeed rates As a beginner policy, do not use

Object-Oriented Design with Smalltalk a Pure OO Language Advanced Classes Universität Bern Ducasse Stéphane 12.177 Not a tutorial on how to build (look at the exercises) => Observer pattern in Smalltalk ❑ ❑

13. The Model View Controller Paradigm

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.178 How can we reduce the complexity of developing such applications? Modularity Interface Code can get very complex ➪ ➪ Building interactive applications with a Event driven user interaction, not predictable ☞ Interfaces are often subject of changes ❑ ❑

Context Obvious example: the Smalltalk Development Environment Characteristics of such applications: Question: Answer:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.179 is a collection of and system components, manageable complexity reusability of the individual components pluggability, i.e. an easy realization of the connections between components – Model – View – Controller ❑ ❑ ❑

Program Architecture Software Architecture A connections between them and a number of constraints they have to fullfill. Goals we want to achieve with our architecture: The Solution for the domain of GUI-driven applications: We partition our application as follows:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.180 Functionality vs. User Interface takes place – Domain specific information – Core functionality, where the computation/data processing – Presentation of the data in various formats – dealing with user input (Mouse, Keyboard, etc.)

Separation of Concerns I: Model: User Interface:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.181 Display vs. Interaction or the model (e.g. modification of data) the same view with different controllers (different modes of interaction) the same controller for different views (Action Button/Radio Button) – displaying the data from model – relaying the user input to View (e.g. Scrolling) – reusability of the individual components and freedom choice is better:

Separation of Concerns II: View: Controller: View and Controller are very much related. There is always a 1:1 relationship between views and controllers. There arenot separated. also examples of systems where view and controller are Rationale for separating View and Controller:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.182 B

change propagation

2 another object A must be informed about changes in the A Subject depends on Decoupling of subject and dependent

modification

1 ☞

The notion of Dependency state of A, in order to be able adapt its own state. Dependencies that are realised viavery reusable and are likely to break in times of change. messages sent directly to dependent objects are not An object B that

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.183 adding and removing dependents change propagation changes state, all its dependents are notified and updated automatically. ❑ ❑

Dependency Mechanism The Publisher-Subscriber Pattern (a.k.a. Observer Pattern) Intent: Define a one-to-many dependency between objects so that when one object The publisher (subject) has a list of subscribers (observers, dependents). A subscriber registers with a publisher. Protocol: The pattern ensures the automatisation of

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.184 Subscriber2 addDependent:Subscriber2 Subscriber1 update update update addDependent:Subscriber1 removeDependent:Subscriber1 Publisher changed changed Publisher-Subscriber: A Sample Session

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.185 : Either the publisher knows for each subscriber what data : a lot of messages have to be exchanged.

How is the changed data transferred from the publisher to subscriber? only one message per subscriber needed. : Only the necessary amount of data is transferred. the publisher sends changed data along with update message : the subscriber, after receiving the update message, asks the publisher for Push: Mixture: the publisher sends hints (“Aspects” in ST terminology) and other parameters along with the update messages Advantages: Disadvantage it needs which increases coupling between publisher and subscriber, or many subscribers receive unnecessary data. Pull the specific data he is interested in Advantage Disadvantage ❑ ❑ ❑

Change Propagation: Push and Pull

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.186 user input View Controller display output

view messages View Controller

change propagation

and

model access Model editing messages Model

The MVC Pattern Dependencies: Other Messages:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.187 A Standard Interaction Cycle

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.188 Increased complexity Potential for excessive number of updates Intimate connection between view and controller Close coupling of views and controllers to a model Inefficiency of data access in view Inevitability of change to view and controller when porting ❑ ❑ ❑ ❑ ❑ ❑ Liabilities: 75 Multiple Views per Model 75% Multiple views of the sameSynchronized views model ‘Pluggable’ views and controllers Exchangeability of ‘look and feel’ ❑ ❑ ❑ ❑

MVC: Benefits and Liabilities Benefits:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.189 ET++ User Interface Framework (C++) Swing-Toolkit in the Java Foundation Classes 1.0 (due mid February 98) MVC was invented by a Smalltalker () first implemented in Smalltalk-80; the Application Framework of Smalltalk is built around it The first implementations of MVC in Smalltalk have undergone a strong evolution. Newer Implementations (for examplethe problems of first, straightforward implementations. in VisualWorks) solve many of ❑ ❑ ❑ ❑ ❑

MVC and Smalltalk MVC is a pattern and can be also applied with other programming languages. Examples: Nevertheless, the ties between MVC and Smalltalk are exceptionally strong:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.190 . ): DependentsField . , where the keys are variable class dependents Object>>dependents access variable IdentityDictionary anObject anObject is an instance : keeps all its dependents in a : defines an access is much more efficient than looking up the dependents in a class variable. addDependent: removeDependent: – – Object DependentsField the objects themselves and thefor the corresponding objects. values are the collections of dependents Model ☞ ❑ ❑

Managing Dependents Attention: Storage of Dependents ! Protocol to manage dependents (defined in

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.191 : : Object>>changing Object>>updating "The receiver changed. The change is denoted by the argument anAspectSymbol. Usu- self myDependents update: anAspectSymbol ifTrue: [self doUpdate].

Implementation of Change Propagation changed: anAspectSymbol ally the argumentis, is some a aspect SymbolInform all of the dependents." of that the is object’s part behavior, of and aParameter the is dependent’s additional change information. protocol, that update: anAspectSymbol “Check anAspectSymbol to seeform the necessary action” if itequals some aspect of interest and ifanAspectSymbol == anAspectOfInterest it does, per- Change methods are implemented in Update methods are implemented in

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.192 ^self update: anAspectSymbol ^self ^self update: anAspectSymbol with: aParameter update: anAspectSymbol with: aParameter from: aSender update: anAspectSymbol with: aParameter update: anAspectSymbol self changed: nil self changed: anAspectSymbol with: nil self myDependents update: anAspectSymbol with: aParameter from: changed changed: anAspectSymbol changed: anAspectSymbol with: aParameter

Climbing up and down the Default-Ladder

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.193 . ) that since there anAspect update:with:from: self changed, methods are often long lists of tests complex objects depending on other objects. update: anAspect might just be some dependent that is interested in change danger of name clashes between apsects that are defined in different models that have to work together (can be solved by using publisher: send messages only to interested dependents subscriber: being notified directly by a call to the method that handles specific change every dependent is notified about all(broadcast). the changes, even if they arethe not interested This is not clean object-oriented programming. all the methods changing something have to send ❑ ❑ ❑ ❑ ❑ ❑

Problems ... We need means to be more specific: General problem: Problems with the Vanilla Change Propagation Mechanism:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.194 object interested dependency transformer on its model: message update: #anAspect is an intermediate object between a model and its DependencyTransformer update: anAspect changed: #anAspect for: self sendBack: aChangeMessage waits for a specific sends a specific method to object ❑ ❑

Dependency Transformer model expressInterestIn: anAspect dependents collection DependencyTransformer model A dependent. It A dependent that is onlyhandle the update installs a interested in a specific aspect of its model and has a method to

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.195 anObject] : message: update: DependencyTransformer receiver := aReceiver. aspect := anAspect. selector := aSymbol. numArguments := selector numArgs. numArguments > 2 ifTrue: [self error: ’selector expects too many arguments’] aspect == anAspect ifFalse: [^self]. numArguments == 0 ifTrue: [^receiver perform: selector]. numArguments == 1 ifTrue: [^receiver perform: selector with: parameters]. numArguments == 2 ifTrue: [^receiver perform: selector with: parameters

Inside a Dependency Transformer setReceiver: aReceiver aspect: anAspect selector: aSymbol update: anAspect with: parameters from: anObject Initializing a Transforming an

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.196 ; the ValueHolder any more self changed : : is an object that encapsulates a value and allows it to behave like ValueHolder ValueHolder change propagation is triggered automatically by the programmer does not have to do objects can become dependents only of the values they are interested in (reduces broadcast problem) ❑ ❑

ValueHolder ValueHolder Accessing a Advantages: A model, i.e. it notifies the dependents of model automatically when is changed. Creating a

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.197 The widgets that make up the UI

A UserInterface Window

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.198 for ValueHolder , which can be a

aspect model

Value Model Protocol the widget does not have to know any specifics about its model A widget can display an aspect of a model A widget can bethe aspect of model displayed by widget. combined with a controller, in which case the user can modify Each component of a User Interface is widget Each component of a model is an attribute or operation Most widgets modify an attribute or start operation ☞ ❑ ❑ ❑ ❑ ❑

Widgets A widget is responsible for displaying some aspect of a User Interface. The connection between widgets and the model: The communication between a widgetstandardized: and the model component it represents visually is Each model component is put into an example. The Widget deals only with this aspect model.

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.199 User Interfaces Models Application Models Domain

The Application Model Customer BankAccount Transaction An ApplicationModel is a modeluser interface, usually consisting of a single window. It manages only application that is responsible forinformation. It leaves the domain information to its aspect models. creating and managing a runtime

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.200 attributes value models widgets User Model Model Domain Interface Application

The fine-grained Structure of an Application

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.201 , (available online) , SIGS Books, 1995 (available online) , Addison Wesley, 1995

Chapter 18, Application Framework

Part II, User Interface

A System of Patterns. Pattern-Oriented Software Architecture

Design Patterns Model-View-Controller, p. 125 Publisher-Subscriber, p. 339 Observer, p. 239 The Smalltalk Developer’s Guide to VisualWorks ☞ ☞ ☞

MVC Bibliography The Pattern: E. Gamma et. al.: Wiley, 1996 The VisualWorks Application Framework: VisualWorks Users Guide: Visual Works Cookbook: Tim Howard: F. Buschmann et. al.:

Object-Oriented Design with Smalltalk a Pure OO Language The Model View Controller Paradigm Universität Bern Matthias Rieger 13.202 Class Process, Process States, Scheduling and Priorities Semaphores, Mutual Exclusion SharedQueues - Concurrency and Parallelism - Applications of Concurrency - Limitations - Atomicity - Safety and Liveness - Processes in Smalltalk: - Synchronization Mechanisms in Smalltalk: - Delays - Promises

14. Processes and Concurrency

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.203 processes share one or more processors each process runs on its own processor but with shared memory connected by a network to others : each process runs on its own processor

Multiprogramming: Multiprocessing: Distributed processing

Concurrency and Parallelism 1. 2. 3. 1. Parallelism for faster execution 2. Improving processor utilization 3. Sequential model inappropriate “A sequential program specifies sequentialis execution called of a a process. list A of concurrentmay be executed concurrently as parallel processes” statements; program its specifies execution two or more sequential programs that A concurrent program can be executed by: Motivations for concurrent programming:

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.204 synchronization mechanisms are needed to maintain consistency special techniques may be needed to guarantee progress debugging is harder because results may depend on “race conditions” process creation, context switching and synchronization take time

Limitations But concurrent applications introduce complexity: - Safety - Liveness - Non-determinism - Run-time overhead

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.205 are treated atomically.

critical section are needed to restrict the possible interleavings of final value of x? { x = 0 } { x = ? } ensures that statements within a

intended P1:P2: x := + 1 x := + 2

Atomicity processes so that sets of actions can be seen as atomic. Programs P1 and P2 execute concurrently: What are possible values of x after P1 and P2 complete? What is the Synchronization mechanisms Mutual exclusion

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.206 - operations may need to be delayed if shared - shared resources must be updated atomically - all processes can eventually access shared resources - some process can always access a shared resource : how is concurrent execution specified? : how is consistency maintained? : how do processes communicate?

mutual exclusion condition synchronization resources are not in an appropriate state (e.g, read from empty buffer) No Deadlock No Starvation ☞ ☞ ☞ ☞ Process creation Communication Synchronization

Safety and Liveness 1. 2. 3. Liveness - ensuring progress: There are two principal difficulties in implementing concurrent programs: Safety - ensuring consistency: Notations for expressing concurrent computation must address:

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.207 runnable fork represents a sequence of actions which can be Process is to send a block the message # [ Transcript cr; show: 5 factorial printString ] fork aProcess

Processes in Smalltalk: Process class - A Smalltalk system supports multiple independent processes. - Each instance of class - The new process is(i.e scheduled for execution) and will start executing as soon the current process added to the listreleases the control of processor. of scheduled processes. This process is executed by the virtual machine concurrently with other processes. - Processes share a common address space (object memory) - Blocks are used as the basis for creating processes in Smalltalk. The simplest way to create

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.208 message. . Once a process #resume message. A suspended #terminate message. which is not scheduled by sending the #suspend until it receives the #resume Process

runnable message it cannot be restarted any more. newProcessWithArguments: #(5). #terminate message to a block: | aProcess aProcess := [ Transcript cr; show: 5 factorial printString ] newProcess aProcess resume aProcess := [ :n | Transcript cr; show: n factorial printString ]

Processes in Smalltalk: Process class - We can create a new instance of class - The actual process is not actually - A process can be created with any number of arguments: - A process can be temporarily stopped using a process can be restarted later using the - A process can be stopped definitely using a message has received the #newProcess

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.209 1. suspended 2. waiting 3. runnable 4. running, or 5. terminated A process may be inthe five states: one of fork yield scheduled by the VM resume runnable running *sent to aSemaphore suspend suspend suspended signal* terminate wait* waiting terminated

Processes in Smalltalk: Process states newProcess

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.210 Used by Processes that arereal time. dependent on Used by user Processes desiring immediate service normal Used by processes governing user interaction Priority Name Purpose 100 timingPriority 9890 highIOPriority70 lowIOPriority50 userInterruptPriority 30 Used by time-critical I/O userSchedulingPriority 10 Used by most I/O Processes 1 userBackgroundPriority systemBackgroundPriority Used by user background processes Used by system background processes systemRockBottonPriority possible priority The lowest

Process Scheduling and Priorities - Process scheduling is based on priorities associated to processes. - Processes of high priority run before processes lower priority. - Priority values go between 1 and 100. - Eight priority values have assigned names.

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.211 (50) #forkAt: message ProcessorScheduler #priority: userSchedulingPriority .

The default process priority is forkAt: Processor userBackgroundPriority. [ Transcript cr; show: 5 factorial printString ] | process1 process2 Transcript clear. process1 := [ Transcript show: ‘first’] newProcess. process1 priority: Processor systemBackgroundPriority. process2 := [ Transcript show: ‘second’ ] newProcess. process2 priority: Processor highIOPriority. process1 resume. process2 resume. Processor

Processes Scheduling and Priorities - Processes are scheduled by the unique instance of class message: - The priority of a process can be changed by using called - A runnable process can be created with an specific priority using the

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.212 nil 50 nextLink priority myList Process suspendedContext Process Process Process firstLink firstLink lastLink lastLink ... 50 3 ... 1 99 2 activeProcess quiescentProcessList 100 Array (indexed by priority) Processor(ProcessorScheduler) . #yield

The Process Scheduling Algorithm Processor activeProcess The active process can be identified by the expression: The processor is given to the process having highest priority. A process will run until it is suspended, terminated or pre-empted by a higher priority process, before giving up the processor. When the highest priorityheld is by multiple processes, the active process canup the processor by using give the message

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.213 fork newProcess 0 P y 1 P Processes Suspended resume 50 x P ...... 1 P suspend 100 activeProcess quiescentProcessList Processor 0 P yield scheduled by the VM Active Process

Process Scheduling

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.214 Transcript cr; show: ‘P1 running’. i := 1. temp 0. [ i <= n ] whileTrue: temp := + i. 1 ]. Transcript cr; show: ‘P1 sum is = ‘; temp printString ] forkAt: 60.

Synchronization Mechanisms | n n := 100000. [ | i temp P1 running P1 sum is = 5000050000 Concurrent processes typically have references to some shared objects. Such objects may receive messages from these processes in an arbitrary order, which can lead to unpredictable results. Synchronization mechanisms serve mainly to maintain consistency of shared objects. We can calculate the sum of first N natural numbers:

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.215 : 60. forkAt : 50. forkAt (i = 5000) ifTrue: [ d wait ]. i := + 1 ]. Transcript cr; show: ‘P1 running’. i := 1. temp 0. [ i <= n ] whileTrue: temp := + i. Transcript cr; show: ‘P1 sum is = ‘; temp printString ] | n d n := 100000. d := Delay forMilliseconds: 400. [ | i temp [ Transcript cr; show: ‘P2 running’. n := 10 ] Synchronization Mechanisms P1 running P2 running P1 sum is = 12502500 What happens if at the same time another process modifies value of n?

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.216 has to the #signal #signal to the semaphore. Another process #wait message is suspended. from two or more processes, it resumes only one #wait message for which no corresponding #wait #wait Transcript show: ‘fox’. sem signal ] fork. sem wait. Transcript show: ‘jumps over the lazy dog’; cr ] fork

Synchronization using Semaphores | sem Transcript clear. sem := Semaphore new. [ Transcript show: ‘The’] fork. [ Transcript show: ‘quick’. sem wait. [ Transcript show: ‘brown’. sem signal. semaphore. - Each semaphore maintains a linked list of suspended processes. - If a semaphore receives process for each signal it receives - A semaphore pays no attention to the priority of a process. Processes are queued in the same order in which they “waited” on semaphore. been sent, the process sending A semaphore is an object used to synchronize multiple processes. process waits for an event to occur by sending the message then signals that the event has occurred by sending message - If a semaphore receives a

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.217 fork newProcess 0 P y 1 P Processes resume Suspended * 50 x P resume z P ...... 1 P suspend 100 activeProcess quiescentProcessList Processor 0 P aSemaphore 0 yield P Waiting Processes for aSemaphore wait scheduled by the VM signal* ActiveProcess

Semaphores

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.218 : 60. : 50. forkAt , otherwise the ] forkAt #signal n := 10 ] . The block argument is only executed ]. sem critical: [ #critical: . (i = 5000) ifTrue: [ d wait ]. i := + 1 ]. [ i <= n ] whileTrue: temp := + i. forMutualExclusion Transcript cr; show: ‘P1 running’. i := 1. temp 0. sem critical: [ Transcript cr; show: ‘P1 sum is = ‘; temp printString ] Semaphore

Semaphores for Mutual Exclusion | n d sem n := 100000. d := Delay forMilliseconds: 400. [ | i temp [ Transcript cr; show: ‘P2 running’. Semaphores are frequently used tois provide supported mutual by exclusion the instance forwhen no other critical blocks sharing the same semaphore are evaluating. method a “critical section”. This A semaphore for mutual exclusion must start with one extra critical section will never be entered. A special instance creation method is provided:

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.219 (1) and #isEmpty is received, the (3). #nextPut: #next #next enables synchronized communication between processes. It works like protects itself against possible concurrent accesses (multiple writes

suspended.

Synchronization using a SharedQueue | aSharedQueue d d := Delay forMilliseconds: 400. aSharedQueue := SharedQueue new. [ 1 to: 5 do:[:i | aSharedQueue nextPut: i ] fork. [ 6 to: 10 do:[:i | aSharedQueue nextPut: i. d wait ] forkAt: 60. [ 1 to: 5 do:[:i | Transcript cr; show:aSharedQueue next printString] ] forkAt: 60. SharedQueue A read objects from the shared queue by sending message - If no object isprocess is available in the shared queue when- We can query whether the shared queue is empty or not with message the messsage a normal queue (First inaSharedQueue First Out, reads andand/or multiple reads). writes), with the main difference being that Processes add objects to the shared queue by using message

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.220 and . Delays created by suspending the #forMilliseconds: #wait #untilMilliseconds: will respond to the message are used to delay the execution of a process. Delay Delay . | minuteWait minuteWait := Delay forSeconds: 60. minuteWait wait.

Delays Instances of class active process for a certain amount of time. The time at which to resume is specified when the delay instance created. Time can be specified relative to the current time with messages #forSeconds: The resumption time can also be specified at an absolute with respect to the system’s millisecond clock with thein this way can be sent the message wait at most once. message An instance of class

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.221 to a block: #promise can be used to specify the priority of the process created. provides a means to evaluate block within concurrent process. #promiseAt: #hasValue Promise

Promises [ 5 factorial ] promise | promise promise := [ 5 factorial ] promise. Transcript cr; show: promise value printString. - An instance of Promise can be created by sending the message - Class - The message If the block has not completed evaluation, then process that attempts to read value of a promise will wait until the process evaluating block has completed. A promise may bemessage interrogated to discover if the process has completed by sending the - The result of the block can be accessed by sending the message value to the promise:

Object-Oriented Design with Smalltalk a Pure OO Language Processes and Concurrency Universität Bern Juan-Carlos Cruz 14.222 — Francis Bacon, Of Studies

Some books are to be tasted, others to be swallowed, and some few to be chewed digested At first sight, a difficult topic! You can live without reallya understanding uniform model, them, and but you metaclasses willand you will really understand the object model provide made less errors if you learn how they work, Recap on Instantiation Recap on Inheritance ❑ ❑

15. Classes and Metaclasses: an Analysis

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.223 subclass of ..... send:.... instance of Printer self subclass send:... Node aPrinter send:...

The meaning of “Instance of” - Every object is an instance of a class. - Every class (except Object) is- ultimately When anObject a receives subclass a ofin its class and/or superclasses. message, Object. the method is looked up - A class defines the structure and behavior of all its instances. - Each instance possesses its own set of values. - Each instance shares its behavior with other instances. This behavior is defined in its class,of link. and is accessed via the instance

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.224 - Everything is an object - Every object is instance of exactly one class - A class is also an object, and instance of its bmetaclass - An object is a class if and only it can create instances of itself. - instance creation - method compilation (different semantics can be introduced) - class information (inheritance link, instance variable, ...)

Concept of Metaclass & Responsibilities Concept: Metaclass Responsibilities: Examples: Node allSubclasses -> OrderedCollection (WorkStation OutputServer WorkstationPrintServer allInstances -> #() FileServer PrintServer) Node instVarNames -> #('name' 'nextNode') Workstation withName: #mac -> aWorkstation Workstation selectors -> IdentitySet (#accept: #originate:) Workstation canUnderstand: #nextNode -> true

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.225 Classes are Objects too!! OrderedCollection allInstVarNames OrderedCollection class allInstVarNames Try And try to understand Look at Class class!

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.226 inherits from class Workstation class instance of Workstation selector is looked up in the class of Workstation withName: #mac withName: #mac #withName: receives Workstation class : Workstation

Classes, metaclasses and method lookup Workstation When anObject receives a message,method the is looked up insuperclasses. its class and/or its So when aClass receives a message,method is looked up in its class (a the metaclass) and/or its superclass Here The method associated with

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.227 Workstation inherits from Node Node inherits from Object

Responsibilities of Object & Class classes Class knows how to create instances - So all the classes should inherit ultimately from Class Object - represents the common behaviorinstances and classes) (like error, halting...) shared by all- so all the classes should inherit ultimately from Object the instances (final Class - represents the common behavior of all classes (compilation, method storing, instance variable storing) - Class inherits from Object because is an Object, although a special one. ⇒

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.228 instance of Class instance of inherits from Object inherits from instance of Workstation aWorkstation

A possible kernel for explicit metaclasses The kernel of CLOS and ObjVlisp but not the Smalltalk

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.229 instance of Lan aLan instance of Unique Instance Class instance of from inherits instance of Object inherits from Special Workstation inherits from aSpecWork Workstation aWork2

Singleton with explicit metaclasses aWork1

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.230 new uniqueInstance isNil... ^ uniqueInstance Unique Instance Class new returns a new instance SpecialWorkstation new instance of instance of Special Workstation inherits from Workstation Workstation new

Deeper into it

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.231 instance of another class (a metaclass). to a class. sole #class Class Metaclass

Smalltalk Metaclasses in 7 points ClassDescription - no explicit metaclasses, only implicit non sharable metaclasses. (1): Every class is ultimately a subclass of Object (except itself) Behavior (2) Every object is an instance of a class. Every class is an instance of a which its metaclass. (3) Every class is an instance of a metaclass. Every user defined class is the Metaclasses are system generated so they unnamed. You can access them by sending the message

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.232 Object Object class . ? Number Number class Object Object class Class Object Number Number class Class Integer Integer class class is Integer Integer class Object SmallInteger SmallInteger class Class Class class SmallInteger SmallInteger class The superclass of (4) All metaclasses are (ultimately) subclasses of But metaclasses are also objects so they should be instances of a Metaclass Smalltalk Metaclasses in 7 points (ii) If X is a subclass of Y then class class. But what is the superclass of metaclass

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.233 Object Object class is an instance of itself Metaclass Number Number class . So Metaclass Integer Integer class SmallInteger SmallInteger class : common metaclass behavior (no name, unique instance) : common object behavior : common class behavior (name, multiple instances) Class Class class Metaclass Metaclass class

Smalltalk Metaclasses in 7 points (iii) (5) Every metaclass is instance of Object Class Metaclass (6) The methods of Class and its superclasses support the behavior common to those objects that are classes.

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.234 , is available as a Object Object class class Behavior Behavior ClassDescription add the behavior specific to particular or Metaclass Behavior #new, #new: ) ClassDescription ClassDescription class #withName: Class Class class Metaclass Metaclass class

Smalltalk Metaclasses in 7 points (iv) Methods of instance Metaclass = methods “Packet class” class (for example classes. ⇒ An instance method defined in (7) The methods of instances class method. Example:

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.235 ) ) ) #compile: #allInstances, #instVArNames, ) #superclass, #allSuperclasses, #subclasses, superclass:, #addSubclass:) #new, #basicNew, #new:, #basicNew: ) #hasMethods, #includesSelector, #canUnderstand:,

Behavior Responsibilities - instance creation ( - accessing (#selectors, #allSelectors, #compiledMethodAt: ) - accessing instances and variables ( #allSubclasses - testing ( - class into hierarchy ( # #allInstVarNames, #classVarNames, #allClassVarNames - accessing clas hierarchy ( #inheritsFrom:, #isVariable - Minimum state necessary for objects that have instances. - Basic interface to the compiler. - State: class hierarchyand number) link, method dictionary, description ofMethods: instances (representation - creating a method dictionary, compiling (

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.236 : Behavior . Metaclass and is an abstract class: its facilities are intended for inheritance by the adds a number of facilities to basic #addInstVarName: #removeInstVarName: Class - named instance variables - category organization for methods - the notion of a name this class (implemented as subclass responsibility) - the maintenance of Changes set, and logging changes on a file - most of the mechanisms needed for fileOut

ClassDescription Responsibilities ClassDescription two subclasses, ClassDescription Subclasses must implement Instance Variables: - instanceVariables names of instance fields - organization provides organization of message protocol

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.237 ....) ) #name:inEnvironment:subclassOf: #subclassOf:

Metaclass Responsibilities - initialization of class variables - creating initialized instances of the metaclass’s sole instance - instance creation ( - metaclass instance protocol (

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.238 ) adds naming for class adds the representation for classVariable names and shared pool variables

Class Responsibilities #addClassVaraNames, #addSharedPool:, #initialize Class Class (

Object-Oriented Design with Smalltalk a Pure OO Language Classes and Metaclasses: an Analysis Universität Bern Ducasse Stéphane 15.239 16. Most Common Mistakes and Debugging • Preventing: Most Common Mistakes • Curing: Debugging Fast (from ST Report July 93) • Extras

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.239 ifTrue: its class

will damage your system True receiver must be a block inLibrary := True inLibrary := true is the boolean value, is not an acceptable receiver for Book>>initialize Book>>initialize Object subclass: #View OrderedCollection := 2

Most Common Beginner Bugs [x

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.240 for returning something else. ^ and not the newly created instance !!! Packet is returned by default. Do not forget self : the class method do not forget the ^ to return newly created instance super new initialize Packet class>>new ^ super new initialize self ^ self addressee = aNode name Packet class>>new #new Write: Return Value Packet>>isAddressedTo: aNode - In a method - In a returns

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.241 to create the new will be called twice! basicNew initialize or to invoke super ^super new initialize method do not forget to use ^self new initialize Packet class>>new ^ self basicNew initialize or ^ super new initialize new

Take care about loops Packet class>> new Packet class>> new -Ina instance. Example: The following loops! You should write: check if this is not already done by super. If so, - Before redefining new as follows:

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.242 method. You do not new method on instances. initialize method can only access class instance variables and Define and invoke an new ⇒ contents := aString. addressee := anAddress self new contents: aString; addressee: anAddress

Instance Variable Access in Class Method Packet class>>send: aString to: anAddress Packet class>>send: aString to: anAddress have the right. The classVariables. - Do not try to access instance variables to initialize them in the Instead create an instance and invoke methods Example: Do not write

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.243 will damage your system super and self aString := aString, 'Device'. name := aString OrderedCollection := 2 setName: aString

Assignments Bugs - Do not try to modify - Do not try to assign a method argument - Do not assign to a class

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.244 so that if a = b then hash #= ==, #basicNew, #basicNew:, #basicAt:, -methods (# when you redefine ...) #class basic #hash ^self title = aBook & (self author author) ^self title hash bitXor: self author redefine redefine Book>>=aBook Book>>hash

Redefinition Bugs Never Never - Redefine - #basicAt:Put: -

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.245 to get the yourself when adding named instance variables instance variables (subclasses of Collection) #copyEmpty indexed do:[:aTimer| copy returns the argument and not receiver, so use aTimer isActive ifFalse: ‘timers remove: aTimer] aTimer isActive ifFalse: ‘timers remove: aTimer] first the collection

Library Behavior-based Bugs timers do:[:aTimer| timers #add: - Copy - Take care, since the iteration can involve various methods and modifications may not be obvious! to a subclass having - Never iterate over a collection which the iteration somehow modifies. collection back. - Do not forget to specialize

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.246 everything breaks. ⇒ tasks := OrderedCollection new. ^tasks ... model tasks add: newTask tasks add: aTask ... model addTask: newTask is now a dictionary Schedule>>initialize Schedule>>tasks ScheduleView>>addTaskButton Schedule>>addTask: aTask ScheduleView>>addTaskButton

Use of Accessors: Protect your Cients tasks Provide an adding method The literature says: “Access instance variables using methods” However, accessors methods should be PRIVATE by default. If accessors would be public, a client could write What happens if we change the representation of tasks? If

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.247 ifTrue:[Transcript cr; show: ‘The total= ’, self total printString]

Debugging Hints Transcript cr; show: ‘The total= ’, self total printString. Debug ifTrue:[Transcript cr; show: ‘The total= ’, self total printString] Debug > 4 Debug print:[Transcript cr; show: ‘The total= ’, self total printString] Smalltalk removeKey: #Debug Object>>inspect MyInspector new inspect: anObject Basic Printing Use a global or class to control printing information Inspecting you can create your own inspect method Naming: useful to add an id for debugging purposes

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.248 Where am I and how did get here? Transcript show: thisContext sender home printString; cr] (VW2.5) Emergency stop (VW3.0) Emergency stop Identifying the current context “if this is not a block” Transcript show: thisContext printString; cr. Debug ifTrue:[ “use this expression in a block” Audible Feedback Screen default ringBell Catching It in the Act Suppose that you cannot open a debugger Transcript cr; show: (Notifierview shortStackFor: thisContext ofSize: 5) Or in a file |file| file := ‘errors’ asFilename appendStream. file cr; nextPutAll: (NotifierView shortStackFor: thisContext ofSize: 5). file close

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.249 implementors of ‘*enu*’ UIVisualILauncher and LauncherView

Source Inspection arrayConst := #(1 2 3 4) Source Code for Blocks aBlockClosure method getSource aMethodContext sourceCode Decompiling a Method Shift + select the method in browser Interesting for modifying literals or fixing MethodWrapper bugs: initialize then somebody somewhere does arrayConst at:1 put:100 So your array is polluted. Note that if you recompile the method original contents of the literal array are restored. So always consider returning copies of your literals. Entry Points How is a window opened or what happens when the menu invoked? look into

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.250 Where am I going? i > 10 ifTrue:[self halt] InputState default shiftDown ifTrue:[self halt] InputState default altDown ifTrue:[self halt] InputState default metaDown ifTrue:[self halt] [ScheduledControllers activeController sensor waitNoButton; waitClickButton] Breakpoints self halt. self error: ‘ invalid’ Conditional halt In a controller: self sensor shiftDown ifTrue:[self halt] Slowing Down Actions: useful for complex graphics Cursor wait showWhile: [(Delay forMilliseconfs: 800) wait] (Do not forget the wait) Until a mouse button is clicked. Cursor crossHair showWhile:

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.251 How do I get out? 1 Emergency Debugger 2 ObjectMemory quit 3 to evaluate the expression An Advanced Emergency Procedure: recompile the wrong method if you know it! aClass compile: ‘methodname methodcode’ classified: ‘what you want’ ex: Controller compile: ‘controlInitialize ^self’ classified: ‘basic’ Graphical Feedback Where the cursor is: ScheduledControllers activeController sensor cursorPoint Position the cursor explicitly ScheduledControllers activeController sensor cursorPoint: aPoint Rectangle fromUser Indicating an area with a filled rectangle ScheduledControllers activeController view graphicsContext display Rectangle: (0@0 extent: 10@100)

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.252 ]. #valueOnUnwindDo: or close "Answer the result ofbe abandoned, evaluate aBlock. " evaluating the receiver. If an exception would cause the evaluation to #valueNowOrOnUnwindDo:

Finding & Closing Open Files in VW ExternalStream classPool at: #openStreams |stream| [ stream := (Filename named: aString) readStream. ... ] valueNowOrOnUnwindDo: [stream "Answer the result of evaluating receiver. If an exception would cause evaluation to be abandoned, evaluate aBlock. The logic for this is in Exception. If no exception occurs, also evaluate aBlock." How to ensure that an open file will be closed in case of error? Use BlockClosure>>valueOnUnwindDo: aBlock BlockClosure>>valueNowOrOnUnwindDo: aBlock

Object-Oriented Design with Smalltalk a Pure OO Language Most Common Mistakes and Debugging Universität Bern Ducasse Stéphane 16.253 #(1 2 3) at: aPacket name => for example SmallInteger are defined as any other objects but => in memory they are different than objects => the object pointer represents SmallInteger indexable non indexable

17. Internal Structure of Object Smalltalk gives to the programmer illusion of uniformity In the memory representation Smalltalk objects can be pointer type, non-pointer index type, non-index type or immediate type. This difference is transparent for the programmer today job but if we want to do some optimizations, analysis.... how can we compute the size in bytes of an object?

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.254 Three ways to create classes: instanceVariableNames: 'contents addressee originator ' classVariableNames: '' poolDictionaries: '' category: 'Demo-LAN' instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed' instanceVariableNames: '' classVariableNames: 'Pi RadiansPerDegree ' poolDictionaries: '' category: 'Magnitude-Numbers' Non indexable, pointer Object subclass: #Packet Indexable pointer ArrayedCollection variableSubclass: #Array Indexable, non pointer LimitedPrecisionReal variableByteSubclass: #Float Not possible to defined named instance variable

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.255 [:each | |boolean| boolean := each isMeta not and: [each isObsolete not]. boolean := and: [each isFixed]. boolean ifTrue: [collection add: each name]]. boolean := each isMeta not and: [each isObsolete not]. boolean := and: [each isPointers]. boolean := and: [each isVariable]. boolean ifTrue: [collection add: each name]] boolean := each isMeta not and: [each isObsolete not]. boolean := and: [each isBits]. boolean := and: [each isVariable]. boolean ifTrue: [collection add: each name]]

Let us Code Identifying subclass:.... | collection collection := SortedCollection new. Smalltalk allBehaviorsDo: ^collection Identifying variableSubclass:... Identifying variableByteSubclass:...

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.256 immediate [hasImmediateInstances] subclass:... indexable type [isVariable] variableSubclass:... non-index type [isFixed] subclass:... index type [isVariable] variableByteSubclass:... non-index type [isFixed] subclass:...

Format and other "Answer whether the receiver contains just bits (not pointers)." ^format noMask: self pointersMask The information for distinguishing between these three type is stored in the format instance variable of Behavior. Behavior>>isBits Behavior>>hasImmediateInstancesBehavior>>isFixedBehavior>>isPointers immediate type object? Behavior>>isVariablepointer type [isPointers] pointers type object? non-indexable type object? non-pointer [isBits] indexable type object?

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.257 (bytesInOOP -1) bitAnd: bytesInOOP negated] ifTrue: [indexableFieldSize := anObject basicSize * bytesInOOP] ifFalse: [indexableFieldSize := 0]] ifTrue: [indexableFieldSize := anObject basicSize + ifFalse:[indexableFieldSize := 0]]. [instVarFieldSize := aClass instSize * bytesInOOP. aClass isVariable [instVarFieldSize := 0. aClass isVariable ifTrue: ifFalse:

Object size in bytes |bytesInOTE bytesInOOP aClass indexableFieldSize instVarFieldSize size| bytesInOTE := ObjectMemory current bytesPerOTE. bytesInOOP := ObjectMemory current bytesPerOOP. aClass := anObject class. aClass isPointers size := bytesInOTE + instVarFieldSize indexableFieldSize. ^size objectSizeInBytes: anObject

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.258 = 2 inst variable and 10 indexes

Analysis pointer, instSize = 3 (dependents name nextNode) * 4 12 not indexable idem, because not recursive 20 : 12 + 2 * 4 OrderedCollection new: 10 class instSize = 2 * 4 basicSize = 10 * 4 60 bytes OTE (ObjectTable Entry)gc flags, ....) = 12 bytes: OTE isOOP (Object Oriented Pointer) = 4 bytes a description of an Object (class,Pointers Type iv, hash, Internals new objectSizeInBytes: WorkStation Internals new objectSizeInBytes: (WorkStation name: #abc) Internals new objectSizeInBytes: 1@2 Indexable and Pointers Type Internals new objectSizeInBytes: (OrderedCollection new: 10)

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.259 4 indexed variable * 16 = 12 but the code should use isImmediate Indexable pure Internals new objectSizeInBytes: Float pi Non pointer, non Index = immediate but an immediate type object has no table entry the immediate object is stored into OOP. Internals new objectSizeInBytes: 1

Object-Oriented Design with Smalltalk a Pure OO Language Internal Structure of Object Universität Bern Ducasse Stéphane 17.260 value value: value: value: valueWithArguments: Full Blocks, Copying Blocks, Clean Blocks, Inlined Blocks. [ :x :y | |tmp| ...] ❑ ❑ ❑ ❑

18. Blocks and Optimization Recall: In VisualWorks there are four types of blocks: The programmer does not have toby the compiler. However, knowing subtle differences allows programmer to be explicitly mention which one ismore efficient. needed. This is inferred

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.261 MethodContext or BlockContext object explicit ifTrue: [1] ifFalse: [2] ifTrue: [^ 1] ifFalse: [^ 2] instead of using a pseudo-object contained in the stack. Most costly arg1 isNil ^ arg1 isNil Read and assign temporary variables. Block containing explicit return ^. Compiled in a BlockClosure. Evaluation by the creation of an m1: arg1 m1: arg1 ❑ ❑ ❑ ❑ ❑

Full Blocks Instead of: Better:

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.262 Read temporary variables but do not assign them. No explicit return. Access instance variables of self and assign them. Not compiled into a BlockClosure. They are compiled by copying everyreferences to a context where the copied variables appear. access into the block, thus avoidingTheir arguments and temporaries are merged into the enclosing method’s explicit context as “compiler-generated temporaries”. ❑ ❑ ❑ ❑ ❑ ❑

Copying Blocks

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.263 Contain only reference block temporary variables or global variables. No reference to self or instance variables. nodes do: [:each | each name = #stef] nodes select: [:each | each isLocal] ❑ ❑

Clean Blocks

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.264 Code of certain methods, like whileFalse: ifTrue:, is directly inlined into the code of the calling method. The literal blocks (without arguments) passed as argument to such methods are also inlined in the byte-code of calling method. Inlined methods are whileTrue, whileTrue:, whileFalse, whileFalse:, and: or:, ifTrue:, ifFalse:, ifTrue:ifFalse:, ifFalse:ifTrue:, to:do:, to:do:by: Look in MessageNode>>transform* methods to see the inlining 1 to: 5 do: [:x| ] ❑ ❑ ❑ ❑

Inlined Blocks | t1 t1 := 1. [t1 <= 5] whileTrue: := t1 + 1]. testInLined Compiled into : But no BlockClosure is created (look into the byte codes)

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.265 The reference to t inside the block makes it at least a copying block. t := makes it full. ❑ ❑

Full to Copy |t| [:x | t := x foo] value: 1. t := * 2. ^t |t| t := [:x | x foo] value:1. t := * 2. ^t Instead of: With the following we have a clean block.

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.266 Contexts |outerContext answer| outerContext := thisContext. (1 to: 1) do: [:i | answer := thisContext == outerContext]. answer |outerContext answer| outerContext := thisContext. 1 to: do: [:i | answer := thisContext == outerContext]. answer Full blocks are evaluated in a separate context. The following code evaluates to false: But the following evaluates to true because: to:do: is an inlined block So this is better to use to:do: than (to:) do:

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.267 no need the temporary variable full blocks to clean block ❑ ❑

Inject:into: |maxNumber| maxNumber := 0. #(1 2 43 56 49 3 0 ) do: [:each| maxNumber := each max: maxNumber]. maxNumber #(1 2 43 56 49 3 0 ) inject: into: [:maxNumber :ele| maxNumber max: ele] Instead of: Write

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.268 to: self size with: aSequenceableCollection str1 , str2 creates a new structure in which and elements are stored " "Answer a copy of the receiver concatenated with argument, a SequenceableCollection." ^self copyReplaceFrom: self size + 1 "Answer a copy of the receiver satisfying following conditions: .. ❑

About String Concatenation SequenceableCollection>>, aSequenceableCollection SequenceableCollection>>copyReplaceFrom: start to: stop with: replacementCollection

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.269 Stream, Blocks and Optimisation (i) |bigString| bigString := String new. Smalltalk keys do: [:aString | bigString := bigString, aString]. |aStream| aStream:= WriteStream on: String new. Smalltalk keys do: [:aString | aStream nextPutAll: aString]. (from Alan Knight) Suppose that we want tothe Smalltalk dictionary. concatenate a pretty long list of strings for example the keys of Here the assignment of bigString leads to a Full Block We can suppress the assignment like that: We obtain a copying block.

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.270 cumul].

Stream, Blocks and Optimisation (ii) |aStream| aStream:= WriteStream on: String new. Smalltalk keys inject: aStream into: [:cumul :aString| cumul nextPutAll: aString. |aReadStream aWriteStream| aReadStream := ReadStream on: Smalltalk keys asArray. aWriteStream := WriteStream on: String new. [aReadStream atEnd] whileFalse: [aWriteStream nextPutAll: a ReadStream next]. inject:into: allows us to suppress the reference variables that are outside block and to obtain a clean block. Now if we use a stream for the Smalltalk keys can avoid iteration method. With whileFalse: that is inlined the block will be inlined. Optimization Yes, but Readibility First

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.271 - "Clean" closure with no references to anything from outer scopes. A clean - "Copying" closure that copies immutable values from outer scopes when the -"Full" closure that retains a reference to the next outer scope. A full closure has method outerContext copiedValues

BlockClosure Class Comments Instance Variables: There are currently three kinds of closures: closure has outerContext = nil and copiedValues empty Array. closure is created. Aor Array. copying closure has outerContext = nil and copiedValues = Object outerContext ~= nil and copiedValues = nil. As an optimization, copiedValues holdsan Array of values if there is more than one. Note that a single copied value, the single copied valuethe if value there being is copied exactly can one, beof nil, or classifying so closures. testing for The nilits method whether numCopiedValues > 0. way in to copiedValues is check not whether a a reliable means closure has copied values is to ask

Object-Oriented Design with Smalltalk a Pure OO Language Blocks and Optimization Universität Bern Ducasse Stéphane 18.272 – for method MethodContext – for block BlockContext – the context from which it is invoked, – the receiver – arguments – temporaries in the Context

19. Block Deep Understanding VM represents the state of execution as Context objects aContext contains a reference to We called home context the in which a block is defined

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.273 "self new testScope" |t| t := 15. self testBlock: [Transcript show: t printString] |t| t := 50. aBlock value -> 15 and not 50

Lexically Scope Test>>testScope Test>>testBlock:aBlock Test new testBlock Arguments, temporaries, instance variables are lexically scoped in Smalltalk These variables are bound in the context which block is defined and not in the context which block is evaluated

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.274 ^ self]]. ifFalse: [ 0 isZero ifTrue: Transcript show: 'two'. Transcript show: ' not printed' "self new test" Transcript show: 'one'. 1 isZero [ Transcript show: 'two'. ^ self. Transcript show: 'not printed'] -> one two Returning from a Block (i) test ^ should be the last statement of a block body ^ return exits method containing it.

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.275 Simple block [:x :y| x *x. + y] returns the value of last statement to method that send it the message value Continuation blocks [:x :y| ^@@not clear activated@@ its homeContext x + y] returns the value to the method that activated ^[^self] ❑ ❑

Returning From a Block (ii) Object>>returnBlock Object new returnBlock |b| b:= [:x| Transcript show: x. x]. b value: ‘ a’. b’. b:= [:x| Transcript show: x. ^x]. b value: ‘ a’. b’. Taking returning as a differenciator As a block is alwaysa method which has already returned using other return. This runtime error condition is evaluated in its homeContext,trapped by the VM. it is possible to attempt to return from -> Exception Continuation blocks cannot be executed several times!

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.276 ^self ] |t| t := 50. aBlock value. self halt. -> 15 and not halt!! "self new testScope" |t| t := 15. self testBlock: [Transcript show: t printString. Test>>testBlock:aBlock Test new testBlock Example of Block Evaluation Test>>testScope

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.277 |goSoon| goSoon := Dialog confirm: 'Exit now?'. goSoon ifTrue: [exit value: 'Bye']. Transcript show: 'Not exiting'. 'last value'] valueWithExit. ^self value: [:arg| ^arg ] |val| val := [:exit | Transcript show: val BlockClosure>>valueWithExit

Creating an escape mechanism yes -> print Bye no -> print Not Exiting last value

Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.278 Object-Oriented Design with Smalltalk a Pure OO Language Block Deep Understanding Universität Bern Ducasse Stéphane 19.279 Abstract Classes Design Issues Elementary Design Issues Idioms Some selected design patterns ❑ ❑ ❑ ❑ ❑

Design Considerations

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane . to produce an error. self subclassResponsibility #new

20. Abstract Classes logical operations &, not, | controlling and:, or:, ifTrue:, ifFalse:, ifTrue:ifFalse:, ifFalse:ifTrue: • Should not be instantiated (abstract in Java). • Defines a protocol common to hierarchy of classes that is independent from the representation choices. • A class is considered as abstract soon one of the methods to which it should respond to is not implemented (can be a inherited one). • Deffered method send the message • Abstract classes are not syntactically distinguable from instantiable classes. BUT as conventions use class comments: So look at the comment. and write in the comment which methods are abstract should be specialized. Advanced tools check this situation. Class Boolean is an abstractare True and False. Subclasses must implement methods for class that implements behavior common to true and false. Its subclasses • Depending of the situation, override

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.281 r

) and:, or:,ifTrue:,ifFalse:, ifTrue:ifFalse:,ifFalse:ifT &, not, | True

&, not, |, and:, or:,ifTrue:, Boolean eqv:, xor:, storeOn:, shallowCopy

Object () Boolean ( ifFalse:,ifTrue:ifFalse:,ifFalse:ifTrue: False () True () False

Case Study: Boolean, True and False and:, or:,ifTrue:,ifFalse:, ifTrue:ifFalse:,ifFalse:ifTrue: &, not, |

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.282 is automatically defined #xor: will be defined, #not self subclassResponsibility "Negation. Answer true if the receiver is false, answer false if the receiver is

Boolean Boolean>>not true." Boolean>>xor: aBoolean "Exclusive OR. Answer true if the receiver is not equivalent to aBoolean." ^(self == aBoolean) not Abstract method Concrete method efined in terms of an abstract When Note that VisualWorks introduced acompilation. A method is executed once and after it compiled in native code. So the second time invoked kind of macro expansion,the native code is executed. optimisation for essential methods and Just In Time

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.283 "Answer the value of trueBlock. This method is typically not invoked because ^falseBlock value ^trueAlternativeBlock value

False and True False>>not "Negation -- answer true since the receiver is false." ^true True>>not "Negation--answer false since the receiver is true." ^false False>>ifTrue: trueBlock ifFalse: falseBlock "Answer the value of falseBlock. This method is typically not invoked because ifTrue:/ifFalse: expressions are compiled in-line for literal blocks." True>>ifTrue: trueBlock ifFalse: falseBlock ifTrue:/ifFalse: expressions are compiled in-line for literal blocks."

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.284 ^self subclassResponsibility ^(self > aMagnitude) not ^aMagnitude < self ^(self < aMagnitude) not ^self >= min and: [self <= max]

CaseStudy: Magnitude: 1 > 2 = < false Magnitude>> < aMagnitude ^self subclassResponsibility Magnitude>> = aMagnitude Magnitude>> <= aMagnitude Magnitude>> > aMagnitude Magnitude>> >= aMagnitude Magnitude>> between: min and: max 1 <= 2 = (1 > 2) not = false not = true

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.285 year = aDate self species = aDate

Date Date>>< aDate "Answer whether the argument, aDate, precedes date of receiver." ifTrue: [^day < aDate day] ifFalse: [^year < aDate year] Date>>= aDate "Answer whether the argument, aDate, is same day as receiver. " ifTrue: [^day = aDate day & (year year)] ifFalse: [^false] Date>>hash ^(year hash bitShift: 3) bitXor: day

Object-Oriented Design with Smalltalk a Pure OO Language Abstract Classes Universität Bern Ducasse Stéphane 20.286 Class definition Instance initialisation Enforcing the instance creation Instance/Class methods Instance variable/ Class instance variables Class initialisation Law of Demeter Factoring Constants Abstract Classes Template Methods Delegation Bad Coding Style ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

21. Elements of Design

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.287 A First Implementation of Packet instanceVariableNames: ‘contents addressee originator ‘ classVariableNames: ‘’ poolDictionaries: ‘’ category: ‘Lan-Simulation’ super printOn: aStream. aStream nextPutAll: ‘ addressed to: ‘; self addressee. aStream nextPutAll: ‘ with contents: ’; self contents ^addressee addressee := aSymbol Object subclass: #Packet One instance method Packet>>printOn: aStream Some Accessors Packet>>addressee Packet>>addressee: aSymbol

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.288 defined Automatically

Packet CLASS Definition Packet class instanceVariableNames: '' Packet new addressee: # mac ; contents: ‘hello mac’ Packet Class is Example of instance creation

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.289 ) printOn: system fragile => can create packet without contents, address Automatic initialization of instance variables Proposing a solid interface for the creation Lazy initialization responsibility of the instance creation relies on clients instance variable not initialized -> error (for example, ❑ ❑ ❑ ❑ ❑ ❑

Fragile Instance Creation Packet new addressee: # mac ; contents: ‘hello mac’ |p| p := Packet new addressee: #mac. p printOn: aStream -> error Solutions: If we do not specify a contents, it breaks! Problems of this approach:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.290 #new Class Method Instance Method method is not automatically called by creation class method returns instance with uninitialized #initialize #new super new initialize ^ super initialize. Defines an instance method that initializes the instance variables and override By default #new/new: How to initialize a newly created instance ? You cannot access instance variable from a class method like to invoke it. 12 Packet class>>new 3 Packet>>initialize Assuring Instance Variable Initialization 4Packet new (1-2) -> aPacket initialize (3-4) returning anInitializedPacket contents := ‘default message’ Problem. Remind. variables. Moreover, methods Solution. #new

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.291 #new without address. aPacket Packet send: ‘Hello mac’ to: #Mac A client can still create Force the client to use class interface creation. Providing an interface for creation and avoiding the use of ^ self new contents: aString ; addressee: anAddress ❑ ❑

Strengthen Instance Creation Interface Packet class>>send: aString to: anAddress Problem. Solution. First try:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.292 self new = aSortedCollection aSortedCollection sortBlock: aBlock Instance method SortedCollection sortBlock: [:a :b| a name < b name] returning the instance aSortedCollection

Other Instance Initialization step 1. according to the criterion specified in aBlock." ^self new sortBlock: aBlockstep 2. step 3. step 4. step 1. OrderedCollection with: 1 | newCollection Class method SortedCollection class>>sortBlock: aBlock "Answer a new instance of SortedCollection such that its elements are sorted Collection class>>with: anObject "Answer a new instance of Collection containing anObject." newCollection := self new. newCollection add: anObject. ^newCollection

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.293 Use lazy initialization based on accessors But lazy initialization should be used consistently! ifTrue: [contents := ‘no contents’] ifTrue: [ratio := self heavyComputation] not used all the time consuming space, difficult to initialize because depending on other need a lot of computation ☞ ☞ contents isNil ^ contents ratio isNil ^ ratio ❑ ❑ ❑

Lazy Initialization Packet>>contents Dummy>>ratioBetweenThermonuclearAndSolar When some instance variables are: A lazy initialization scheme with default value A lazy initialization scheme with computed value

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.294 Providing a Default Value instanceVariableNames: 'sortBlock ' classVariableNames: 'DefaultSortBlock ' DefaultSortBlock := [:x :y | x <= y] "Set the initial value of receiver's sorting algorithm to a default." sortBlock := DefaultSortBlock "Answer a new instance^(super new: anInteger) initialize of SortedCollection. The default sorting is a <= comparison on"Answer a new instance of SortedCollection such that its elements elements." are sorted according to the criterion specified in aBlock." ^self new sortBlock: aBlock The case of SortedCollection OrderedCollection variableSubclass: #SortedCollection SortedCollection class>>initialize SortedCollection>>initialize SortedCollection class>>new: anInteger SortedCollection class>>sortBlock: aBlock

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.295 "Answer a new empty instance of OrderedCollection." ^self new: 5

Invoking per default the creation interface OrderedCollection class>>new

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.296 to create fragile instances basicNew: #new contents: aString ; addressee: anAddress and should raise an error! basicNew #new We can still use => raises an error => bad style: link class and superclass dangerous in case of evolution self basicNew self error: 'Packet should only be created using send:to:' ^ self new contents: aString ; addressee: anAddress ^ super new contents: aString ; addressee: anAddress ^

Forbidding new Packet class>>new Packet class>>send: aString to: anAddress Packet class>>send: aString to: anAddress Packet class>>send: aString to: anAddress Problem. Solution. But we still have to be able create instance! Solution: use

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.297 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.298 class ). Packet ) represents class ( Packet class Classes ( Class instance variable are of class => should represent the state ofmessages sent, superclasses, subclasses.... class: number of created instances, numberClass methods represent CLASS behavior: instance creation, of initialization, counting the number of instances.... If you weaken the secondcommon properties shared by all the instances point: class state and behavior can be used to define aNode nextNode isNil not => aNode hasNextNode ^ self nextNode = noNextNode ^self class noNextNode ^ nil ❑ ❑ ❑ ❑

Class Methods - Instance Variables Node>>hasNextNode Node>>noNextNode Node class>>noNextNode Ex: If we want to encapsulate the way “no next node” is coded. Instead of writing:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.299 or explicitly by the programmer. load time ’ at the end of saved files. Date

Class Initialization Magnitude subclass: #Date instanceVariableNames: 'day year' classVariableNames: 'DaysInMonth FirstDayOfMonth MonthNames SecondsInDay WeekDayNames' poolDictionaries: '' category: 'Magnitude-General' Classname initialize Automatically called by the system at - Used to initialize a classVariable, pool dictionary or class instance variables. - ‘ Example:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.300 305 335 ). Friday Saturday Sunday ) June July August September October November December ). "Initialize class variables representing the names of the months and days and the

Date class>>initialize Date class>>initialize number of seconds, days in each month, and first day month. " "Date initialize." MonthNames := #(January February March April May SecondsInDay := 24 * 60 60. DaysInMonth := #(31 28 31 30 ). FirstDayOfMonth := #(1 32 60 91 121 152 182 213 244 274 WeekDayNames := #(Monday Tuesday Wednesday Thursday

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.301 ' ' TypeTable typeTable TypeTable is used to initialize once the table typeTable is used by every instance and each can customized the table (copying). scanTokens: 'identifier keyword: 8r31 ''string'' embedded.period key:word: . ' instanceVariableNames: 'source mark prevEnd hereChar token tokenType saveComments classVariableNames: ' poolDictionaries: '' category: 'System-Compiler-Public Access' ❑ ❑

A Case Study: Scanner Scanner new -> #(#identifier #keyword: 25 'string' 'embedded.period' #key:word: #'.') Object subclass: #Scanner currentComment buffer Class Definition Why having an instance variable and a classVariable denoting the same object (the scanner table)?

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.302 255 withAll: #xDefault. "default" " Scanner initialize

Scanner class>>initialize " | newTable newTable := ScannerTable new: newTable atAllSeparatorsPut: #xDelimiter. newTable atAllDigitsPut: #xDigit. newTable atAllLettersPut: #xLetter. newTable at: $_ asInteger put: #xLetter. '!%&*+,-/<=>?@\~' do: [:bin | newTable at: bin asInteger put: #xBinary]. "Other multi-character tokens" newTable at: $" asInteger put: #xDoubleQuote. ... "Single-character tokens" newTable at: $# asInteger put: #literalQuote. newTable at: $( asInteger put: #leftParenthesis. ... newTable at: $^ asInteger put: #upArrow. "spacing circumflex, formerly up arrow" newTable at: $| asInteger put: #verticalBar. TypeTable := newTable

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.303 ^super new initScanner buffer := WriteStream on: (String new: 40). saveComments := true. typeTable := TypeTable super initScanner typeTable := copy. typeTable at: $( asInteger put: #xDefault. typeTable at: $) asInteger put: #xDefault

Scanner Scanner class>> new Scanner>>initScanner MyScanner>>initScanner Instances only access the typehas been initialized once. table via the instance variable that points to the table that A subclass just has to specialize initScanner without copying the initialization of the table

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.304 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.305 self name asString] ifTrue:[ Transcript show: 'A packet is accepted by the Workstation ', ifFalse: [super accept: aPacket] aPacket addressee = self name Workstation, Node, PrinterServer have to be changed too ^addressee

Why Coupled Classes are Bad? Packet>>addressee Workstation>>accept: aPacket If Packet changes the way addressee is represented

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.306 - an argument passed to you - an object you create - self, super - your class self foo. super someMethod: aParameter. self class foo. self instVarOne foo. instVarOne foo. self classVarOne foo. classVarOne foo. aParameter foo. thing := Thing new. thing foo

The Law ot Demeter someMethod: aParameter You should only send messages to: Avoid global variables Avoid objects returned from message sends other than self

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.307 ifTrue: [ aNode certified]. at: self creatorKeyput: self creator “that data is a dictionary” |nodeDescription| (aNode isValid)nodeDescription := NodeDescription for: aNode. nodeDescription localTime.self addNodeDescription: nodeDescription. “I can talk to myself“ nodeDescription data “I created it” “Ok passed as an argument to me” “Wrong I should not know”

Illustrating the Law of Demeter NodeManager>>declareNewNode: aNode

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.308 be invoked by clients not methods that should private Only when necessary put accessors in accessing protocol Be consistent inside a class, do not mix direct access and accessor use First think accessors as tasks := OrderedCollection new. ^tasks tasks isNil ifTrue: [task := ...]. ^tasks ❑ ❑ ❑

About the Use of Accessors (i) Scheduler>>initialize Scheduler>>tasks Schedule>>tasks Literature says: “Access instance variables using methods” BUT: accessors methods should be PRIVATE by default at least the beginning. Accessors are good for lazy initialization

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.309 ... model tasks add: newTask tasks add: aTask This is not because accessors are methods that you provide a good data encapsulation. If they are mentionned as public (no inforcement in Smalltalk) you could be tempted to write in a client: ScheduledView>>addTaskButton ===>IT BREAKS!!!. Take care about the coupling between your objects and provide a good interface! Schedule>>addTask: aTask ❑ ❑ ❑ ❑

About the Use of Public Accessors (ii) Returns consistenly the receiver orcan look inside and modifies it) or returns a copy of it. the element but the not the collection (else people What’s happen if we change the representation of tasks? If tasks is now an array

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.310 ifTrue: [total := total + each amount]]. total := 0. aPlant bilings do: [:each | (each status == #paid and: [each date>startDate]) total := aPlant totalBillingsPaidSince: startDate

Never do the work that somebody else can do! XXX>>m XXX>m Alan Knight Instead write

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.311 self name asString] ifTrue:[ Transcript show: 'A packet is accepted by the Workstation ', ifTrue:[ Transcript show: 'A packet isifFalse: [super accept: aPacket] accepted by the Workstation ', self ifFalse: [super accept: aPacket] aPacket addressee = self name (aPacket isAddressedTo: self) ^addressee ^ addressee = aNode name

Provide a Complete Interface Packet>>addressee Workstation>>accept: aPacket Packet>>isAddressedTo: aNode Workstation>>accept: aPacket name asString] => This is the responsibility of an object to propose a complete interface that propects itself from client intrusion. Shift the responsibility to Packet object

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.312 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.313 ...... ^ nextNode aNode nextNode = ‘no next node’ aNode hasNextNode ^ (self nextNode = self class noNextNode) not ^ ‘no next node’ Node>>nextNode NodeClient>>transmitTo: aNode NodeClient>>transmitTo: aNode Node>>hasNextNode Node class>>noNextNode

Factoring Out Constants Ex: If we want to encapsulate the way “no next node” is coded. Instead of writing: Write:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.314 ‘local’ ‘local’ ‘local’ accessType := ... ^ accessType = accessType := self localAccessType ^ accessType = self localAccessType ^

Initializing without Duplicating Node>>initialize Node>>isLocal Node>>initialize Node>>isLocal Node>>localAccessType => Ideally you could be able to change the constant without having any problems. You may have to haveconstants. mapping tables from model constants to UI constants or database

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.315 localAccessType self accessType: localAccessType inst aString name: aString accessType: aType name: |inst| inst := self new. inst name: aString. inst type: ^self new name: aString ; accessType: aType ^self ^ ‘local’ ^self class localAccessType

Constants Needed at Creation Time Node class>>localNodeNamed: aString Node class>> Node class>>name: aString Node class>>localAccessType Node>>localAccessType Works well for: If you want to have the following creation interface You need: => Factor the constant between class and instance level => you could also use a ClassVariable that are shared between class and their instances

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.316 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.317 ifTrue: [self printFromPS: aDocument] ifFalse: [self printFromPS: aDocument asPS] ifTrue: [self printFromPDF: aDocument asPDF] ifFalse: [self printFromPDF: aDocument] ^ aDocument isPS ^ aDocument isPS PSPrinter>>print: aDocument PSPrinter>>printFormPS: aPSDoc PdfPrinter>>print: aDocument PdfPrinter>>printFormPS: aPdfDoc

Type Checking for Dispatching How to invoke a method depending on the receiver and an argument? A not so good solution: As we do not know howbetween documents. to coerce form the PSPrinter to a PdfPrinter we only use coercion

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.318 aPSprinter print: self asPS aPdfPrinter print: self asPdf (c) PSDoc>>printOnPSPrinter: aPSPrinter (d) PdfDoc>>printOnPdfPrinter:aPSPrinter (e) PSDoc>>printOnPSPrinter: aPdfPrinter (f)PdfDoc>>printOnPdfPrinter:aPdfPrinter ^ aDoc printOnPSPrinter: self ^ aDoc printOnPdfPrinter: self

Double Dispatch How to invoke a method depending on the receiver and an argument? Solution: use the information given by single dispatch and redispatch with argument (send a message back to the argument passing the receiver as an argument) (a) PSPrinter>>print: aDoc (b) PdfPrinter>>print: aDoc Some Tests: psptr print: psdoc =>(a->c) pdfptr print: pdfdoc => (b->f) psptr print: pdfdoc => (a->d->b->f) pdfptr print: psdoc => (b->e->b->f)

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.319 ifTrue: [ aNumber asFloat + self] ifFalse: [ self addPrimitive: aNumber] ifTrue: [aNumber asFloat + self] ifFalse: [self addPrimitive: aNumber] (aNumber isKindOf: Float) (aNumber isKindOf: Integer)

A Step Back Example: Coercion between Float and Integer Not a really good solution: Integer>>+ aNumber Float>>+ aNumber Here receiver and argument are the same, we can coerce in both sense.

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.320 ^ anInteger asFloat + self ^aFloat + self asFloat (c) Integer>>sumFromInteger: anInteger (d) Float>>sumFromInteger: anInteger (e) Integer>>sumFromFloat: aFloat (f) Float>>sumFromFloat: aFloat ^ aNumber sumFromInteger: self ^ aNumber sumFromFloat: self

Deeper on Double Dispatch : Numbers (ii) (a) Integer>>+ aNumber (b) Float>>+ aNumber Some Tests: 1 + 1: (a->c) 1.0 + 1.0: (b->f) 1 + 1.0: (a->d->b->f) 1.0 + 1: (b->e->b->f)

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.321 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.322 (self bandWidth * averageRatio / defaultWindowSize) (self bandWidth * averageRatio / defaultWindowSize) UINode new with: UINode new with: |averageRatio defaultNodeSize| averageRatio := 55. defaultNodeSize := self mainWindowCoordinate / maximiseViewRatio. self window add: ... |averageRatio defaultNodeSize| averageRatio := 55. defaultNodeSize := self mainWindowCoordinate +self window add: minimalRatio / maximiseViewRatio. ...

Methods are the Elementary Unit of Reuse Node>>computeRatioForDisplay SpecialNode>>computeRatioForDisplay We are forced to copy the method!

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.323 (self bandWidth * averageRatio / defaultWindowSize) self mainWindowCoordinate / maximiseViewRatio UINode new with: ^ ^self mainWindowCoordinate + minimalRatio / maximiseViewRatio |averageRatio defaultNodeSize| averageRatio := 55. defaultNodeSize := self defaultNodeSize. self window add: ... Node>>defaultNodeSize SpecialNode>>defaultNodeSize

Methods are the Elementary Unit of Reuse (ii) Node>>computeRatioForDisplay Self sends = planning for Reuse

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.324 new with: (self bandWidth * averageRatio / defaultWindowSize). (self bandWidth * averageRatio / defaultWindowSize). UINode new with: ExtendedUINode |averageRatio defaultNodeSize| averageRatio := 55. defaultNodeSize := self mainWindowCoordinate / maximiseViewRatio. self window add: ... |averageRatio defaultNodeSize| averageRatio := 55. defaultNodeSize := self mainWindowCoordinate / maximiseViewRatio. self window add:

Methods are the Elementary Unit of Reuse Node>>computeRatioForDisplay SpecialNode>>computeRatioForDisplay We are forced to copy the method!

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.325 (self bandWidth * averageRatio / self defaultWindowSize) UINode self UIClass new with: ^ ^ExtendedUINode |averageRatio | averageRatio := 55. self window add: ... Node>>UIClass SpecialNode>>UIClass

Class Factories Node>>computeRatioForDisplay

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.326 ... self hookMethod1 ... self hookMethod2 ConcreteClass hookMethod1 hookMethod2

AbstractClass template Method hookMethod1 hookMethod2 Hook methods do notno behavior at all. have to be abstract, theyThis has an influence on the instanciability of superclass. may define default behavior or ❑ ❑

Hook and Template Methods

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.327 postCopy

Hook Example: Copying " Answer another instance just like the receiver. Subclasses normally^self shallowCopy override the postCopy mes- "Answer a copy of the receiver which shares receiver's instance variables." .... " Finish doing whatever is required, beyond a shallowCopy, to implement 'copy'. Answer the receiver. This message is only intended to be sent newly created instance. Subclasses may add functionality, but they should always do super postCopy first. " " Note that anyvariable) must include the equivalent of 'self breakDependents'" subclass that 'mixes in Modelness' (i.e., implements^self dependents with an instance Object>>copy sage, but some objects that should not be copied override copy. " Object>>shallowCopy Object>>postCopy

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.328 [:obj :count | new at: obj put: count].

Hook Specialisation "Make sure to copy the contents fully." | new super postCopy. new := contents class new: capacity. contents keysAndValuesDo: contents := new. Bag>>postCopy

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.329 ((title at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']).

Hook and Template Example: Printing "Answer a String whose characters are description of the receiver." | aStream aStream := WriteStream on: (String new: 16). self printOn: aStream. ^aStream contents "Append to the argument aStream a sequence of characters that describes the receiver." | title title := self class name. aStream nextPutAll: aStream print: self class Object>>printString Object>>printOn: aStream

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.330 [aStream nextPutAll: '...(more)...)'. ^self]. ifTrue: aStream position > tooMany element printOn: aStream] separatedBy: [aStream space].

Override of the Hook "Append to the argument, aStream, elements of Array enclosed by parentheses." | tooMany tooMany := aStream position + self maxPrint. aStream nextPutAll: '#('. self do: [:element | aStream nextPut: $) "Print false." aStream nextPutAll: 'false' Array>>printOn: aStream False>>printOn: aStream

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.331 Specialization of the Hook "Append to the argument aStream a statement of which superclass the receiver descends from." aStream nextPutAll: 'a descendent of '. superclass printOn: aStream The class Behavior that representsdefault one. a class extends the default hook but still invokesBehavior>>printOn: aStream the

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.332 each] anExceptionBlock [self notFoundError] remove: ifAbsent: ifAbsent: oldObject anObject oldObject remove: remove: remove: Define classes by behavior, not state Implement behavior with abstract state: if you need state do it indirectly via messages not referencing the state variables directly Identify message layers: implement class’s behavior through a small set of kernel method Defer identification of state variable: The abstract messages become kernel methods that require state variables.and defer the kernel methods’ implementation to subclasses Declare the variable in the subclass aCollection do: [:each | self self subclassResponsibility ^ aCollection self ❑ ❑ ❑ ❑ Collection>>removeAll: aCollection Behavior Up and State Down Collection>> Collection>> 4 steps

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.333 Simple implementation. Implement all the cod in one method. Break into steps. Comments logical subparts Make step methods. Extract subparts as method Call the step methods. (including when using refactoring browser) Make constant methods. Methods doing nothing else than returning. Repeat step 1-5 if necessary on the methods created ❑ ❑ ❑ ❑ ❑ ❑

Guidelines for Creating Template Methods

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.334 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.335 ifTrue: [self print: thePacket] ifFalse: [super accept: thePacket]] A document can be printed on different printers for example lw100s show: self name ; ‘***** printing *****‘;cr show: aPacket contents ;cr ifTrue: [ self print: thePacket] ifFalse: [ (thePacket isAddressedTo: self) (thePacket addressee = #*lw*) Transcript

Towards Delegation: Matching Addresses LanPrinter>>accept: aPacket LanPrinter>>print: aPacket New requirement: or lw200s depending on which printer is first encountered. => Packet need more than one destination Ad-hoc Solution

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.336 is not general brittle because based on convention adding a new kind of address behavior require editing the class Printer ❑ ❑ ❑

Limits of such an ad-hoc solution

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.337 node1 anAddress aPacket [false] accept: aPacket send: aPacket print: aPacket [true] isAddressedTo: nodePrinter nodePrinter accept: aPacket

Reifyand Delegate An alternative solution: isAddressedTo: could be sent directly to the address With the current solution, packet can still control process if needed

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.338 Reify: v. making something an object (philosophy) NodeAddress is responsible for identifying the packet receivers name was not a good name, and now it is really an address -> we should rename it. ❑

Reifying Address instanceVariableNames: ‘id‘ ^ self id = aNodeAddress ^ self addressee isAddressedTo: aNode name Object subclass: #NodeAddress NodeAddress>>isAddressedTo: aNodeAddress Packet>>isAddressedTo: aNode Having the same name for packet and address is not necessary but meaningful! Refactoring Remark:

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.339 #*lw*) isAddressedTo: aNode name self addressee ^ Packet>>isAddressedTo: aNode Works for packets with matchable addresses Packet send: ‘lulu’ to: (MatchingAddress with: #*lw*) Does not work for nodes with matchable addresses because the match is directed. But it corresponds to the requirements! Node withName: (MatchingAddress with: inheritance class relationship is not really good because we can avoid duplication (coming soon) Creation interfaces could be drastically improved ❑ ❑ ❑ ❑

Matching Address instanceVariableNames: ‘’ ^ self id match: aNodeAddress Address subclass: #MatchingAddress NodeAddress>>isAddressedTo: aNodeAddress Remarks

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.340 Addresses instanceVariableNames: ‘id‘ ^self subclassResponsibility instanceVariableNames: ‘‘ instanceVariableNames: ‘‘ Object subclass: #Address Address>>isAddressedTo: anAddress Address subclass: #NodeAddress Address subclass: #MatchingAddress

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.341 No blob class: one class responsibility Variation possibility Pluggable behavior without inheritance extension Runtime pluggability Difficult to follow responsibilities and message flow Adding new classes = adding complexities (more names) New object ❑ ❑ ❑ ❑ ❑ ❑ ❑

Trade Off Delegation Pros Delegation Cons

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.342 Encapsulation principle: minimize data representation dependencies – Complete interface – No overuse of accessors – Responsibility of the instance creation Lose coupling between classes Methods are units of reuse (self send) Use polymorphism as much possible avoid type check Behavior up and state down Use correct names for class Use correct names for methods ❑ ❑ ❑ ❑ ❑ ❑ ❑

Designing Classes for Reuse

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.343 Bad coding practices

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.344 => remove all the duplicated nodes (if node knows how to compare) But a systematic use of asSet to protect yourself from duplicate is not good => returns an ordered collection after removing duplicates => look for the real source of duplication if you do not want it!!!! nodes asSet nodes asSet asOrderedCollection

Do not overuse conversions

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.345 raises an error if the key is not found allows one to specify action be done when the key does not exist Dictionary>>at: aKey Dictionary>>at: aKey ifAbsent: aBlock nodes at: nodeId ifAbsent:[]

Hidding missing information Do not overuse it!!! This is bad because at least we should know that the nodeId was missing

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.346 (another name allocate only create instance basicNew: and contents: aString ; addressee: anAddress basicNew: and basicNew => bad style: link class and superclass dangerous in case of evolution self basicNew self error: 'Packet should only be created using send:to:' ^ super new contents: aString ; addressee: anAddress ^ basicNew

Different Self/Super Packet class>>new Packet class>>send: aString to: anAddress Packet class>>send: aString to: anAddress Do not do a super with different method selector Use Never override without instance variable initialization)

Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.347 Object-Oriented Design with Smalltalk a Pure OO Language Elements of Design Universität Bern Ducasse Stéphane 21.348 Never do the job that you can delegate to another one! Never let someone else plays with your private data Say something only once ❑ ❑ ❑

22. Selected Idioms The Object Manifesto Be lazy: Be private: The Programmer Manifesto

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.346 Messages take time Flow of control is difficult with small methods Reading is improved Performance tuning is simpler (Cache...) Easier to maintain / inheritance impact self controlInitialize. self controlLoop. self controlTerminate ❑ ❑ ❑ ❑ ❑

Composed Method Controller>>controlActvity How do you divide a program into methods? But: Divide your program into methods that perform one identifiable task. Keep all of the operations in a method at same level of abstraction.

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.347 Packet new addressee: # mac ; contents: ‘hello mac’ x: radiusNumber * thetaNumber cos y: radiusNumber * thetaNumber sin

Constructor Method ^ self basicNew contents: aString ; addressee: anAdress yourself ^ self Good if there are differentunderstand how to create an instance. combinations of parameters. But you haveAlternative: make sure that there is a method to represent each valid way create an to read the codeinstance. to Provide methods in class “instance creation” protocol that create well-formed instances. Pass all required parameters to them How do you represent instance creation? Most simple way: Packet class>>send: aString to: anAddress Point class>>x:y: Point class>> r: radiusNumber theta: thetaNumber SortedCollection class>>sortBlock: aBlock

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.348 , because the return value setContents:addressee (Interesting Result) in contents: aString ; addressee: anAdress ; yourself self

Constructor Parameter Method ^ self basicNew ^ self basicNew setContents: aString addressee: anAddress contents:= aString. addressee := anAddress. ^self of the method will be used as return caller Once you have the parameters of a Constructor Method to class, how pass them to the newly created instance? Packet class>>send: aString to: anAddress But violates the “say things only once and once” rule (initialize) Code a single methodits name with “set”, then the names of variables. in the “private” procotol that sets all the variables. Preface Packet class>>send: aString to: anAddress Packet>>setContents: aString addressee: anAddress Note

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.349 ”- is, was, will, has has ” or “ be

Query Method status := #on status := #off ^status self switch status = #on ifTrue: [self light makeOn] self switch status = #off ifTrue: [self light makeOff] Switch>>isOn, Switch>>isOff How do you represent testing a property of an object? What to return from a method that tests property? Instead of: Switch>>makeOn Switch>>makeOff Switch>>status Client>>update Defines Provide a method that returns Boolean in the “testing” protocol. Name it by prefacing the property name with a form of “ Switch>>on is not a good name... #on: or #isOn ?

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.350 isOn := aBoolean

Boolean Property Setting Method Switch>>on: aBoolean beVisible/beInvisible/toggleVisible How do you set a boolean property? • Expose the representation of status to clients • Responsibility of who turn off/on the switch: client and not object itself Create two methods beginning with “be”.negation. Add “toggle” if the client doesn’t want to know about current state One has the property name, the other the

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.351 SortedCollection class of sortBlock:

Comparing Method ...sortBlock: [:a :b | a income > b income] How do we order objects? <,<=,>,>= are defined on Magnitude and its subclasses. Implement “<=” in “comparing” protocol to return true if the receiver should be ordered before the argument But also we can use

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.352 [oldcursor show] valueNowOrOnUnwindDo:

Execute Around Method self open.aBlock value.self close| oldcursor oldcursor := self class currentCursor. self show. ^aBlock [aBlock value] self open. valueNowOrUnwindDo: [self close] How do represent pairs of actions that have to be taken together? When a filed is opened it has to be closed.... Basic solutions: under the client responsibility,Code he a should method invoke that takes them a“During: aBlock” to the name of first method that have be invoked. In on Block the as right an order. argument. Namebody of the Execute Around Method, invoke first method, evaluate block, the method by appending then invoke the second method. File>>openDuring: aBlockCursor>>showWhile: aBlock File>>openDuring: aBlock

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.353 Choosing Message ifTrue:[anEntry producer] ifFalse:[anEntry author] ^self producer ^self author How do you execute one of several alternatives? responsible := (anEntry isKindOf: Film) Use polymorphism Film>>responsible Entry>>responsible responsible := anEntry Send a message to onealternative of several different of objects, eachExamples: of which executes one Number>>+ aNumber Object>>printOn: aStream Collection>>includes: A Choosing Message can be sent to self in anticipation of future refinement by inheritance. See also the State Pattern.

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.354 , the system will run in same #reverse: by #highlight: self reverse: aRectangle ^self size = 0 ^ 1 / self

Intention Revealing Message How do you communicate your intent when the implementation is simple? We are not writing for computer but reader ParagraphEditor>>highlight: aRectangle If you would replace way but you would reveal the implementation of method. Send a message to self.rather than how it is to be done. Code a simple method for the message. Name the message so it communicates what is to be done Collection>>isEmpty Number>>reciprocal

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.355 Collection>>searchFor: Collection>>includes:

Intention Revealing Selector How do you name a method? If we choose to name after HOW it accomplished its task Array>>linearSearchFor: Set>>hashedSearchFor: BTree>>treeSearchFor: These names are not good because you have to know the type of objects. Name methods after WHAT they accomplish Better: Even better: Try to see if the name of selector would be same in a different implementations.

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.356 Name Well your Methods (i) "compute and store the variable type" self addTypeList: (ArrayType with: aVal). currentType := (currentType computeTypes: (ArrayType with: aVal)) "compute and store the variable type" self addTypeList: (ArrayType with: aVal). currentType := (currentType computeTypes: (ArrayType with: aVal)) "add the aList elt to Set of type taken by variable" typeList add: aList. "add the aList elt to Set of type taken by variable" typeList add: aList. Not precise, not good setType: aVal Precise, give to the reader a good idea of functionality and not about implementation computeAndStoreType: aVal Instead Of: setTypeList: aList Write: addTypeList: aList

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.357 [... aCollection at: index... index := + 1]

do: |index| index := 1. [index <= aCollection size] whileTrue: aCollection do: [:each | ...each ...] Instead of writing that: Write that

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.358 [ :each | result at: each put: (aCollection each) abs]. |result| result := aCollection species new: size. 1 to: aCollection size do: ^ result ^ aCollection collect: [:each| each abs]

collect: absolute: aCollection absolute: aCollection Instead of : Write that: Note that this solution works well for indexable collection and also sets. The previous one not!!!

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.359 detect: [:each| each | anObject] ifNone:[ nil]) notNil.

isEmpty, includes: Instead of writing: ...aCollection size = 0 ifTrue: [...] ...aCollection size > 0 ifTrue: [...] Write: ... aCollection isEmpty Instead of writing: |found| found := false. aCollection do: [:each| each = anObject ifTrue: [found : true]]. ... Or: |found| found := (aCollection Write: |found| found := aCollection includes: anObject

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.360 instead of nodes nodeArray

How to Name Instance Variables?

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.361 Name a superclass with single word that conveys its purpose in the design Number Collection View Model Name subclasses in your hierarchy by prepending an adjective to the superclass name OrderedCollection SortedCollection LargeInteger ❑ ❑

Class Naming

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.362 Reversing Method x printOn: aStream aStream nextPutAll: ‘ @’. y printOn: aStream anObject printOn: self aStream print: x; nextPutAll: ‘ @’; y How to code a smooth flow of messages? Point>>printOn: aStream Here three objects receive different messages. Code a method on thethe parameter. original Derive receiver its name as form asending the original message to receiver. the parameter original to message. the Take new method. Implement the method by But creating new selectors just ofr fun is not a good idea. Each selector must justify its existence. Stream>>print: anObject Point>>printOn: aStream Note that the receiver can now change without affecting other parameters

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.363 -you (a lot of information) -your clients (should not be aware of the internal) displayString for clients printString for you (call printOn:)

Debug Printing Method How do you code the default printing method? Two audiences: Override printOn: to provide information about object’s structure the programmer In VisualWorks, two needs are supported

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.364 Method Comment ifTrue:[...] ^(self flags bitAnd: 2r1000) = 1 ifTrue:[...] How do you comment methods? Templates are not a good idea. Uses: - Intention Revealing Selector says what the method does - Type Suggesting Parameter Name says what the arguments are expected to be..... Communicate important information that is not obvious from the code in a comment at the beginning of method Example of important information: - Method dependencies, preconditions - To do - Reasons for change (in a base class) (self flags bitAnd: 2r1000) = 1 “Am I visible?” isVisible self isVisible

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.365 Pass part of its work on to another object - code in written context of superclasses - in rich hierarchies, you may to read and understand many superclasses - how to simulate multiple inheritance (if this is really necessary)

Delegation How does an object share implementation whitout inheritance? With inheritance Many object need to display, all objects delegate a brush-like (Pen in VisualSmalltalk, GraphicsContext in VisualAge and VisualWorks) All the detailed codesimplified view of the displaying. is concentrated in a single class and the rest of the system have a

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.366 Delegate messages unchanged

Simple Delegation How do you invoke a disinterested delegate? Some important question on delegation: - is the identity of delegating object important? e.g. the delegating object can pass itself to be notified by delegate.The delegate could not want to have an explicit reference the delegating but still need access it. - is the state of delegating object important to delegate? If the delegate has no reason to need identity of delegating object and it is self- contained to accomplish its task without additional state: Simple Delegation Suppose an object that acts a LITTLE as collection but has lots of other protocols, instead fo inheriting from a collection, delegates to collection. Collection doesn’t care who invoked it. No state from the delegating is required.

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.367 Self Delegation (i) - extra complexity, - each time the delegate changes,- each delegate can only be used by one delegating, one should destroy the old reference- If creating multiple copies of the delegate is expensive or impossible, this does not and set a new How do you implement delegation to an object that needs reference the delegating object? One way is to have a reference in the delegate delegating. Drawbacks: work Pass along the delegating object (i.e. self ) in an additional parameter called “for:”

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.368 Self Delegation - Example self hashTable at: key put: value for: |hash| hash := aCollection hashOf: key ... ^anObject hash ^anObject basicHash In VisualSmalltalk, hashed collections (dictionaries) use a hash table. Variants of the hash table can be used depending on different criterias. Hash value is implemented differently byby sending “hash” and IdentityDictionaries “basicHash” different collections. Dictionaries compute hash Dictionary>>at: key put: value HashTable>>at: key put: value for: aCollection Dictionary>>hashOf: anObject IdentityDictionary>>hashOf: anObject The hierarchy of hashed Collections is then independent the HashTable

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.369 Add a variable that will be used to trigger different behavior

Pluggable Behavior How do you parameterize the behavior of an object? In the class based model instances have private values and share behavior.When you want a different behavior create new class. But creating class is not always valuable: imagine a large number of classes with only single method. Questions to consider: how much felxibility you need? How many methods will need vary dynamically? How hard is it to follow the code? Will client specify code be plugged? Typical examples are user-interface object that have to display the contents of many dfferent objects

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.370 Pluggable Selector ^anObject printString ^anObject asDollarFormatString ^ anObject description ^anObject perform: printMessage printMessage := #printString How do you code simple instance specific behavior? The simplest way to implement Pluggable Behavior is store a selector. Add a variable that conatinsRole a Suggesting selector Instance to Variable be Name.performs the selector. performed. Create Append a “Message” Composed to Method the ListPane>>printElement: anObject that simply And subclasses only specializing DollarListPane>>printElement: anObject DescriptionListPane>>printElement: anObject ListPane>>printElement: anObject ListPane>>initialize Readibility: harder to follow than simple class-based behavior Extent: if you need more than twice per object use State Object

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.371 getBlock: [self speed] putBlock: [:newSpeed| self speed: newSpeed]

Pluggable Block ^PluggableAdaptor ^getBlock value putBlock value: anObject How do you code COMPLEX Pluggable Behavior that is not quite worth its own class? Add an instance variable toInstance Variable Name. Create aComposed Method to evaluate the Block store a Block. Append “Block”invoke the Pluggable Behavior. to the Role Suggesting Drawbacks: Enormous cost, readibility is worse, blocks are difficult to store PluggableAdaptor in VisualWorks allows one to map any interface the value model. An simplified version: Car>>speedAdaptor PluggableAdaptor>>value PluggableAdaptor>>value: anObject

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 1.372 Singleton Template Method (already seen) Composite Null Object ❑ ❑ ❑ ❑

23. Some Selected Design Patterns

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.374 -> true class method so that if one instance already exists this #new

-> true We specialize the We want a class with unique instance. .

Singleton Instance: A Class Behavior |aLan| aLan := NetworkManager new aLan == LAN new aLan uniqueInstance == NetworkManager new #new Problem. Solution. will be the only one.of When the first instance is created, we store and returned it as result

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.375 is: initialize]. uniqueInstance and # new self basicNew only returns the unique instance there is no initialization. ifTrue: [ uniqueInstance := potentially initializes a new instance. ^uniqueInstance instanceVariableNames: 'uniqueInstance ' self error: ‘should use uniqueInstance’ uniqueInstance isNil

Singleton Instance’s Implementation NetWorkManager class NetworkManager class>>new NetworkManager class>>uniqueInstance new uniqueInstance Providing access to the unique instance is not always necesssary. It depends what we want to express. The difference between # - # - #

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.376 ifTrue:[UniqueInstance := self basicNew] UniqueInstance isNil ^UniqueInstance Singleton class uniqueInstance new self error: ‘....’ Singleton uniqueInstance singletonMethod «unique Instance»

Singleton Client clientMethod Singleton singletonMethod singletonState «shared variable» UniqueInstance Intent Ensure a class has only one instance, and provide global point of access to it A Possible Structure

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.377 Global Variable Access is dangerous: if we reassign Notifier lose all references to current windows. Class Method is betterresponsible for the singleton instance (cretaion, initialization....). because it provides a single access point. This class is “Private - Perform OS window system startup” |oldWindows| ... Notifier initializeWindowHandles. ... oldWindows := Notifier windows. Notifier initialize. ... ^oldWindows ❑ ❑

Discussion SessionModel>>startupWindowSystem In some Smalltalk singletons areuniqueInstance notifier). accessed via a global variable (ex: NotificationManager Global Variable or Class Method Access

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.378 Persistent Singleton: only one(ex: Notifier Manager in Visual Smalltalk) instance exists and its identity does not change Transient Singleton: only one instance exists at any timebut that changes (ex: SessionModel in VisualVisualWorks) Smalltalk, SourceFileManager, Screen in Single Active Instance Singleton: abut other dormant instances may also exist. Project in VisualWorks, single instance is active atControllerManager. any point in time, ❑ ❑ ❑

Singleton Variations

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.379 instanceVariableNames: ‘’ classVariableNames: ‘UniqueInstance’ poolDictionaries: ‘’ self error: ‘Class ‘, name, ‘ cannot create new instances’

Ensuring a Unique Instance Object subclass: #Singleton Singleton class>>new In Smalltalk we cannot prevent a client to send message (protected in C++) => To prevent additional creation: redefine new/new:

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.380 if the initialization was done using initialize is bad practice and may break ifTrue:[UniqueInstance := self basicNew]. ifTrue: [UniqueInstance := self basicNew initialize] ifTrue: [UniqueInstance := super new]

Providing Access UniqueInstance isNil ^UniqueInstance Lazzy Access Singleton class>>uniqueInstance With this solution we lose the initialization part of superclass

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.381 Accessing the Singleton via new? ^self uniqueInstance Singleton class>>new The intent (singletoness) is not clear anymore! New is used to return newly created instances. |screen1 screen2| screen1 := Screen new. screen2 := Screen new |screen1 screen2| screen1 := Screen uniqueInstance. screen2 := Screen uniqueInstance

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.382 instanceVariableNames: ‘’ classVariableNames: ‘UniqueInstance’ poolDictionaries: ‘’ instanceVariableNames: ‘’ classVariableNames: ‘’ poolDictionaries: ‘’ ifTrue:[uniqueInstance := self basicNew]. Singleton for an entire subhierarchy of classes: ClassVariables are shared by all the subclasses Singleton for each of the classes in an hierarchy uniqueInstance isNil ^uniqueInstance Object subclass: #Singleton Object subclass: #Singleton Singleton class instanceVariableNames: ‘uniqueInstance’ Singleton class>>uniqueInstance ❑ ❑ ❑

Singletons in a Single Subhierarchy Instances variables of classes are private to the class

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.383 Theoritically: classes behavior represents of class “Ordinary objects are used to model the real world. MetaObjects describe these ordinary objects” => Do not mess up this separation. => DO not mix domain objects with metaconcerns. Pratical: What’s happen if later the object can have multiple instances? You have to change a lot of client code! ❑ ❑

Instance/Class Methods When a class should only haveat the class level. one instance, it could be tempting toBut this is not that good: define all its behavior

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.384 Specify different queries over a repository q1 := PropertyQuery property: #HNL with: #< value: 4. q2 := PropertyQuery property: #NOM with: #> value: 10. q3 := MatchName match: ‘*figure*’ Compose these queries and manipulate composites as one query (e1 e2 e3 e4 ... en)((q1 and q2 q4) or q3) -> (e2 e5) composer := AndComposeQuery with: (Array q1 q2 q3) ❑ ❑

Queries An example: we want to be able

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.385 OrComposite holdsOn: anElement ^aCollection select: [:each | self holdsOn: each] Composite add: aQuery remove: aQuery AndComposite holdsOn: anElement

AbstractQuery runOn: aCollection holdsOn: anElement [:each| each fulfils: anElement]

A Possible Solution ^ queries all: MatchingProperty holdsOn: anElement holdsOn: anElement

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.386 child operation] children children do: [:child| Composite operation add: aComponent remove: aComponent

Component operation Leaf operation This way we avoid to have define dummy behavior for Leaf Composite not only group leaves but can also contains composites In Smalltalk add:, remove: doon Composite not need to be declared☞ into Component but only ❑ ❑

Composite Pattern Client Intent Compose objects into tree structure to represent part-whole hierarchies. Composite let clients treat individual objects and compositions of uniformly

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.387 resuslts without performing any other behavior Use a Component superclass (To define the interface and factor code there) Consider implementing abstract Composite and Leaf (in case of complex hierarchy) Only Composite delegates to children Composites can be nested Composite sets the parent back-pointer (add:/remove:) Can Composite contain any type of child? (domain issues) Is the Composite’s number of children limited? Forward – Simple forward. Send the message to all children and merge – Selective forward. Conditionally forward to some children – Extended forward. Extra behavior – Override. Instead of delegating ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Implementation Issues

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.388 do nothing or returns the default value Client NullObject operation

AbstractObject operation RealObject operation

NullObject Intent Provides a surrogate for anotherThe object NullObject that encapsulate shares the implementation the decisionsthoses details from its collaborators same of interface how but to does do nothing. nothing and hides

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.389 ifTrue: [self] ifFalse: [nil]] [ctrl isControlWanted

Without Null Object Illustration ... ^ ctrl isNil ifFalse: The View has to check that its controller is not nil before invoking the normal behavior. VisualPart>>objectWantingControl

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.390 With Null Object ... ^ ctrl isControlWanted ifTrue: [self] ifFalse: [nil] ^self viewHasCursor and:[...] self controlInitialize. self controlLoop. self controlTerminate ^self viewHasCursor ^false ^self ^false Avoid to make explicit tests VisualPart>>objectWantingControl Controller>>isControlActive Controller>>startUp Controller>>isControlWanted NoController>>isControlWanted NoController>>startUp NoController>>isControlActive

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.391 ^ false ^ self View controller NoController isControlWanted startUp

Controller startUp isControlWanted TextController isControlWanted startUp

NullObject in Controller Hierarchy

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.392 Uses polymorphic classes: NullObject and real ones share the same interface so are interchangeable Simplifies client code: Clients does not have to handle null case Encapsulates do-nothing behavior: easy to identify, coded efficiently Make do-nothing behavior reusable Forces encapsulation: the same nullunless they all delegate to a collaborator that can be null object. object cannot be added to severalMay cause class explosion: one -> superclass and null object classes Is non-mutable: a null object does not transform into real ❑ ❑ ❑ ❑ ❑ ❑ ❑

Consequences Advantages Disadvantages

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.393 When an object requires apattern. collaborator that already exists before the NullObject When some instances should do nothing When you want clients to beWhen you want the do-nothing behavior able to ignore the difference betweenWhen all the do-nothing behavior is encapsulated in collaborator class collaborators When very little code actually uses the variable directly When the code that does use variable is well encapsulated in one place When the code that uses variable handle it always same way ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

When/ When Not Apply NullObject Do not apply NullObject, Use a variable set to nil

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.394 Null Strategies Null Adapters Reusable Nulls ❑ ❑ ❑

VisualWorks Examples NoController in the (MVC) Controllernever wants control. It is the controller for views that are non-interactive. hierarchy. NoController represents a controller that DragMode implements the dragging of widgets in window painter. SelectionDragMode allows the move ofit. NullDragMode responds to the mouse’s drag motions by doing nothing. the widget, CornerDragMode lets the user resize NullInputManager in the InputManager hierarchy.object interface to platform events that affect internationalised input. Subclasses An InputManager is arepresent specific platforms. NullInputManager represents platforms that don;t support platform neutral internatialisation. A NameScope represents a name scope -- static (global / pool class pool), instance variables (of a class or hierarchy), local (argument / temporary, of method block). A StaticScope holds globaltemporary and variables. class They variables, form LocalScopes aouter holds tree scope. instance that GlobalScope and defines has all anNullScope it answers that the variable is not defined in code scope. are the outer variables. scope Every a scope NullScope.reused by simple and clean blocks. has When an the lookup reaches a

Object-Oriented Design with Smalltalk a Pure OO Language Some Selected Design Patterns Universität Bern Ducasse Stéphane 23.395 Java, C++, Smalltalk Smalltalk for the Java Programmer Smalltalk for the Ada Programmer ❑ ❑ ❑

Comparing

Object-Oriented Design with Smalltalk a Pure OO Language Universität Bern Ducasse Stéphane 397 target applications, evolution, design goals syntax, semantics, implementation technology portability, interoperability, environments & tools, development styles History: ☞ Language features: ☞ Pragmatics: ☞ ❑ ❑ ❑

24. Comparing C++, Java and Smalltalk Overview

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 398 Prolog Lisp Oberon Modula-2 Modula-3 COBOL Ada Ada 95 Pascal Eiffel Clu PL/1 FORTRAN C C++ ANSI C++ Algol 60 Algol 68 Java Objective C Self Simula 67 Smalltalk 72 Smalltalk 80

History 1960 1970 1980 1990

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 399

Target Application Domains Smalltalk Originally conceived as PL for children. Designed as language and environment for “Dynabook”. Now: Rapid prototyping. Simulation. Graphical user interfaces. “Elastic” applications. C++ Originally designed for simulation (C with Simula extensions). Now: Systems programming. Telecommunications and other high-performance domains. Java Originally designed for embedded systems. Now: Internet programming. Graphical user interfaces.

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 400 , multiple inheritance, delete and new Originally (1972) every object was anto incorporate a meta-reflective architecture. independent entity. The language evolved Now the language (Smalltalk-80) is stable, but environments and frameworks continue to evolve. Originally called C with classes, inheritance and virtual functions (Simula-like). Since 1985 added strong typing, templates, exceptions, and many, many other features. Standard libraries and interfaces are emerging. Still evolving. Originally called Oak, Java 1.0 was already a stable language. Java 1.1 and 1.2the most important). introduced modest language extensions (innerThe Abstract Windowing Toolkit was radically overhauled to support a more classes being general-purpose event model. The libraries are still expanding and evolving. ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Evolution Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 401 and strong-typing, ... “Everything is an object” Self-describing environment Tinkerability C with classes ☞ “Every C program is also a C++ program” ... almost No hidden costs C++ minus the complexity (syntactically, not semantically) Simple integration of various OO dimensions (few innovations) “Java — it’s good enough” ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Language Design Goals Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 402 The ultimate modelling tool Programmer is in complete control Applications are not “installed” in the conventional sense Meta-reflective architecture ☞ Mature framework technology “Portable assembler” with HL abstraction mechanisms ☞ Templates (computationally complete!) Dynamically loaded classes ☞ First clean integration of many OO dimensions (concurrency, exceptions ...) ❑ ❑ ❑ ❑ ❑ ❑

Unique, Defining Features Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 403 yes (well integrated) limited limited (weakly integrated) no templates no yes yes pure hybrid pure single multiple single always optional yes (it depends) dynamic static static automatic manual automatic Smalltalk C++ Java architecture namespaces no (header files) packages fully reflective yes (semaphores) no (libraries) yes (monitors) modules generics reflection exceptions inheritance concurrency object model type checking dynamic binding Overview of Features memory management

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 404

Syntax Smalltalk Minimal. Essentially there are only objects and messages. A few special operators exist for assignment, statements, blocks, returning etc. C++ Baroque. 50+ keywords, two commenting styles, 17 precedence levels, opaque type expressions, various syntactic ambiguities. Java Simplified C++. Fewer keywords. No operator overloading.

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 405 Pointers are also values; “references” really aliases No pointers “Everything is an object” Objects are the units of encapsulation Objects are passed by reference “Everything is a structure” Classes are the units of encapsulation Objects are passed by value ☞ “Almost everything is an object” Classes are the units of encapsulation (like C++) Objects are passed by reference ☞ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

Object Model Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 406 d delete Garbage collection can be efficient and non-intrusive Automatic objects are automatically destructed Dynamic objects must be explicitly Special care needed for distributed or multi-platform applications! Objects are either primitive, or made of references to other objects No longer referenced objects may be garbage collected ☞ Objects are structures, possibly containing pointers to other objects Destructors should be explicitly programmed (cf. OCF) ☞ ☞ Reference counting, garbage collection libraries and tools (Purify) can help Objects are garbage collected ☞ ❑ ❑ ❑ ❑ ❑ ❑

Memory Management Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 407 aggressive optimization performed (automatic inlining, JIT compilation etc.) explicit inling (but is only a “hint” to the compiler!) Overridden, non-virtuals will be statically bound! Message sends are always dynamic ☞ Only virtual methods are dynamically bound ☞ Overloaded methods are statically disambiguated by the type system ☞ Overloading, overriding and coercion may interfere! All methods (except “static,” and “final”) are dynamically bound Overloading, overriding and coercion can still interfere! ❑ ❑ ❑ ❑ ❑ ❑

Dynamic Binding A::f(float); B::f(float), B::f(int); A b = new A; b.f(3) calls A::f(float) Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 408 multiple instantiations may lead to “code bloat” Multiple subtyping (a class can implement multiple interfaces) Several experimental extensions implemented ... Single inheritance; single roots: Object, Dynamic typing, therefore no type parameters needed for generic classes Multiple inheritance; multi-rooted Generics supported by templates (glorified macros) ☞ Single inheritance; single root Object ☞ No support for generics; you must explicitly “downcast” (dynamic typecheck) ☞ ❑ ❑ ❑ ❑ ❑ ❑

Inheritance, Generics Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 409

categories

namespaces dynamic type-checking (safe downcasting)

and invalid sends raise exceptions some implementations support use header files to control visibility of names Classes live inside packages Dynamic type-checking ☞ No module concept — classes may be organized into ☞ Static type-checking No module concept ☞ Static ❑ ❑ ❑ ❑ ❑ ❑

Types, Modules Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 410 synchronization via Semaphores any value may be thrown exceptions are not necessarily caught in the right context! exception classes are subclasses of Exception or Error synchronization by monitors (synchronized classes/methods +exceptions are caught within the thread in which they raised wait/signal) Can signal/catch exceptions Multi-threading by instantiating Process ☞ Try/catch clauses ☞ No concurrency concept (various libraries exist) ☞ Try/catch clauses ☞ Multi-threading by instantiating Thread (or a subclass) ☞ ☞ ❑ ❑ ❑ ❑ ❑ ❑

Exceptions, Concurrency Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 411

introspection every class is a subclass of Object (including Class) every class is an instance of Class (including Object) classes can be created, inspected and modified at run-time Smalltalk’s object model itself can be modified only supports Meta-reflective architecture: ☞ ☞ ☞ ☞ Run-time reflection only possible with specialized packages Compile-time reflection possible with templates Standard package supports limited run-time “reflection” ☞ ❑ ❑ ❑ ❑

Reflection Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 412

Implementation Technology Smalltalk Virtual machine running “Smalltalk image.”then “interpreted” by the VM — now commonly compiled “just-in-time” to native code. Classes are compiled to “byte code”,Most of the Java VM techniques were pioneered in Smalltalk. which is C++ Originally translated to C. Now native compilers. Traditional compile and link phases. Can foreign libraries (if link-compatible.) Opportunities for optimization are limited due to low-level language model. Templates enable compile-time reflection techniques (i.e., to resolve polymorphism at compile-time; to select optimal versions of algorithms etc.) Java Hybrid approach. Each class is compiledvirtual machine that either interprets the byte-code, or compiles it “just in time” to to byte-code. Class filestarget machine. may be dynamically loaded intoStandard libraries are statically linked to the Java machine; others must be loaded a Java dynamically.

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 413 Portability through virtual machine Interoperability through special bytecodes,native methods and middleware Portability through language standardization (C as a “portable assembler”) Interoperability through C interfaces and middleware Portability through virtual machine Interoperability through native methods and middleware ❑ ❑ ❑ ❑ ❑ ❑

Portability, Interoperability Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 414 Incremental compilation and execution is possible Special tools exist to detect memory leaks (e.g., Purify) Tools exist to debug multi-threaded applications. ❑ ❑ ❑

Environments and Tools

Advanced development environments exist for all three languages, with class and hierarchy browsers, graphical debuggers, profilers, “make” facilities, version control, configuration management etc. In addition: Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 415 Tinkering, growing, rapid prototyping. Incremental programming, compilation and debugging. Framework-based (vs. standalone applications). Conventional programming, compilation and debugging cycles. Library-based (rich systems libraries). Conventional, but with more standard libraries & frameworks. ❑ ❑ ❑ ❑ ❑ ❑

Development Styles Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. 416 Good for rapid development; evolving applications; wrapping Requires investment in learning framework technology Not suitable for connection to evolving interfaces (need special tools) Not so great for intensive data processing, or client-side internet programming Good for systems programming; control over low-level implementation Requires rigid discipline and investment in learning language complexity Not suitable for rapid prototyping (too complex) Good for internet programming Requires investment in learning libraries, toolkits and idioms Not suitable for reflective programming (too static) ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑

The Bottom Line ...

You can implement an OO design in any of the three. Smalltalk C++ Java

Smalltalk-A Pure OO Language Comparing C++, Java and Smalltalk Universität Bern Oscar Nierstrasz 7. Syntax A bit of semantics ❑ ❑

25. Smalltalk for the Java Programmer

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.417 null/* comment */// comment a = 1“string”‘c’true, false“lulu” == “lulu”“lulu”.equals (“lulu”) “comment” nil a := 1 ‘string’ true, false ‘lulu’ == $c

Syntax (i) Reference to nowhere Comment Assignment Basic types Identity and Equality

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.418 thissuperthis.getClass()xx this.xanotherObject.x Node aNode; self class Node aNode; self super x aNode | aNode

Syntax (ii) Self reference Instance Variables Access Instance Variable Definition Local Variable

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.419 at: index addAll: col anotherObject fooB anObject.foo()this.foo() foo()anObject.foo(a,b)addAll(index, col)anObject fooA() ; fooB()anObject fooA(); anotherObject fooB() anObject foo anObject fooA . anObject fooA ; fooB anObject foo: a with: b public boolean addAll (int index, Collection aCollection) add: index all: col (not readable) at: index addAll: aCollection self foo

Syntax Methods Message Sends Method Definition

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.420 ifFalse:[b] ifTrue: [a] collection do:, collect:, detect:, ...n...} ...... } k timesRepeat: [ ] {a}{a}else {b} col isEmpty ifTrue: [a] ifTrue: [a] ifFalse: [b]

Syntax Conditional and Loops if (col.isEmpty())if (col.isEmpty()) col isEmpty while (col.isEmpty()) {a} col isEmpty do{a} while(col.isEmpty()) for (int n=1; n < k; n++){ [col isEmpty] whileTrue: [a] for (int n=1; n

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.421 No Primitive Types Only Objects “string”new String (“string”) truenew Boolean (true) 1 new Integer (1)int i,j ;i + j Integer i, j; i.add(j) ‘string’ true 1 i + j

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.422 d := #string “a” == “b”“a”.equals(“b”) ‘a’ = ‘b’ ‘a’==’b’

Literals representing the same object a = “string”;b = “string”;c = new String (“string”);a == b truea == c falsea.equals(c) truea.equals(b) true c := #string. a := ‘string’. b := ‘string’. a = b true c = d true a == b false c == d true

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk for the Java Programmer Universität Bern Ducasse Stéphane 25.423 Vocabulary – package + type -> class – subprograms -> methods – record component -> instance variable – package variable -> classVariable Class Definition Method Definition Instance Creation Method Instance Creation ❑ ❑ ❑ ❑ ❑

26. Smalltalk For the Ada Programmer

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.424 ' ' contents addressee originator ' '' '' Packet # LAN-Simulation ' Contents: Unbounded_String; Addressee: Integer; Originator: Node; type Packet is new Object with private; -- extending the data structure ... type Packet is new Object with record -- the component end record; classVariableNames: poolDictionaries: category: Class Definition instanceVariableNames: with Ada.Strings.Unbounded;with Nodes; use Ada.Strings.Unbounded; package Packets is private use Nodes; end Packets; Object subclass:

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.425 ^ addressee addressee := aSymbol ^ originator = aNode “returns true if I’m addressed to the node aNode” ^ self addressee = aNode name

Method Definition Declaration (i) type Packet is new Object with private; -- extending the data structure function Addressee(A_Packet: Packet) return Integer; procedure Addressee (A_Packet: in out Packet, An_Address: Integer); function Is_Sent_By (A_Packet: Packet, A_Node: Node) return Boolean; function Is_Addressed_To (A_Packet: Packet, A_Node: Node) return Boolean; ... package Packets is private end Packets; Packet>>addressee Packet>>addressee: aSymbol Packet>>isAddressedTo: aNode Packet>>isSentBy: aNode

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.426 ^ addressee addressee := aSymbol return A_Packet.Addressee; A_Packet.Addressee := An_Address;

Method Definition (i) function Addressee (A_Packet: Packet) return Integer is begin end Addressee; procedure Addressee (A_Packet: in out Packet, An_Address: Integer) is begin end Addressee; ... package body Packets is end Packets; Packet>>addressee Packet>>addressee: aSymbol

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.427 ^ originator = aNode A_Packet.Originator = A_Node; A_Packet.Addressee = Name(A_Node); --Name is a function on type Node “returns true if I’m addressed to the node aNode” ^ self addressee = aNode name

Method Definition(ii) ... function Is_Sent_By (A_Packet: Packet, A_Node: Node) return Boolean is begin end Is_Sent_By; function Is_Addressed_To (A_Packet: Packet, A_Node: Node) return Boolean is begin end Is_Addressed_To; package body Packets is end Packets; Packet>>isAddressedTo: aNode Packet>>isSentBy: aNode

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.428 send: aString to: anAddress >> class type Packet is new Object with private; -- extending the data structure function Send_To (Contents: String, Address: Integer) return Packet; ...... function Send_To (Contents: String, Address: Integer) return Packet; begin return (To_Unbounded(Contents), Integer, Empty_Node); end Send_To; Instance Creation Method |inst| inst := self new. inst contents: aString. inst to: anAddress. ^inst package Packets is end Packets; package body Packets is end Packets; Packet

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.429 “, 123); This packet travelled to the printer P: Packet := Send_To (“ Addressee(P); ... |p| p := Packet send: 'This packet travelled to the printer' to: 123. p addressee procedure XXX begin end XXX; XXX

Instance Creation

Object-Oriented Design with Smalltalk a Pure OO Language Smalltalk For the Ada Programmer Universität Bern Ducasse Stéphane 26.430 27. References

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.431 www.object-arts.com/Home.htm mac, pc, hp, linux, unix www.cincom.com/visualworks/ www.software.ibm.com/ad/smalltalk/ www.cincom.com/objectstudio/

A Jungle of Names Some Smalltalk Dialects: • Smalltalk-80 -> ObjectWorks -> VisualWorks by (ParcPlace -> ObjectShare->Cincom) • IBM Smalltalk (pc, unix, aix...) • Smalltalk-V (virtual) -> Parts VisualSmalltalk by (Digitalk ObjectShare) • VisualAge = IBMSmalltalk + Envy (OTI -> IBM) • Smalltalk Agents (Mac) www.quasar.com • SmallScript www.quasar.com (.Net, PC and Mac) • Smalltalk MT (PC, assembler) • (PC) • Smalltalk/X -> www.exept.de (run java byte code into Smalltalk VM) • Smalltalk/Express (free now but not maintained anymore) • Enfin Smalltalk -> Object Studio (Cincom)

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.432 Team Development Environments • Envy (OTI) most popular, available for VisualWorks • VSE (Digitalk), (not available) • TeamV, (not available) • Store (new Objectshare) • ObjectStudio v6 (similar to Envy)

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.433 www.cincom.com www.object-arts.com/Home.htm http://www.squeak.org/ • VisualWorks 3.0 and VW5i.2 on PC for free • VisualWorks 3.0 and VW5i.2 on Linux (Red-Hat) • Dolphin Smalltalk on PC (not the last version) • Squeak (Morphic Objects + Socket all Platforms) continous development • Gnu Smalltalk (not evaluated) www.software..com/ad/smalltalk/education/univagr.html contact [email protected]

Some Free Smalltalks Professional Environment New concepts Free for Universities: • VisualWorks 3.0 and VW5i.2) all platforms products (www.cincom.com/vwnc/) • VisualAge is free for University: • Envy is free for University

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.434 Main References * (Intro + VW)Trevor Hopkins and Bernard Horan, Prentice-Hall,1995, 0-13-318387-4 Smalltalk: an Introduction to application development* (Intro using + VisualWorks, VW) Smalltalk,X. Briffault and G. Sabah, Eyrolles, Paris. 2-212-08914-7 programmation orientée objet et développement d'applications, + (Intro SEx) On To Smalltalk, P. Winston, Addison-Wesley, 1998, 0-201-49827-8 ** (Hints, Design + VW) Smalltalk by Example : The Developer's Guide, Alec Sharp, McGraw Hill, ISBN: 0079130364, 1997 ** (Idioms) Smalltalk Best Practice Patterns, Kent Beck, Prentice Hall, 1997, isbn 0-13- 476904-x (Praxisnahe Gebrauchsmuster, K. Beck, Prentice-Hall, 1997, ISBN 3-8272- 9549-1). * (Idioms) Smalltalk with1996, 0-13-165549-3. Style, S. Skublics and E. Klimas and D. Thomas, Prentice-Hall, ** (User Interface Reference + VW) The Smalltalk Developer’s Guide to VisualWorks, Tim Howard, Sigs Books, 1995, 1-884842-11-9 ** (Envy) Joseph Pelrine, Alan Knight and Adrien ..., Title not know yet, SIG Press. ** (Design) The Design Patterns Smalltalk Companion, S. Alpert and K. Brown B. Woolf, Addison-Wesley, 1998,0-201-18462-1

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.435 Other References (Old or Dialects) ** Smalltalk-80: The language, Adele Goldberg and David Robson, Addison-Wesley, 1984-1989, 0-201-13688-0 (Purple bookbut still really interesting: a reference! ST-80, part of the original• An introduction to Object-Oriented Programming and Smalltalk, Lewis J. Pinson blue book). VW. old Richard S. Wiener, 1988, Addison-Wesley, ISBN 0-201-119127. (ST-80) • Object-Oriented Programming with C++ and Smalltalk, Caleb Drake, Prentice Hall, 1998, 0-13-103797-8 + Smalltalk, Objects and Design, Chamond Liu,+ Smalltalk the Language, David Smith, Benjamin/Cummings Publishing, 1995,0-8053- Manning, 0-13-268335-0 (IBM Smalltalk) 0908-X (IBM smalltalk) • Discovering Smalltalk, John Pugh, 94 (Digitalk Smalltalk) • Inside Smalltalk (I & II), Wilf Lalonde and Pugh, Prentice Hall,90, (ParcPlace ST-80) • Smalltalk-80: Bits of History and Words Advice, G. Kranser, Addison-Wesley,89, 0- 201-11669-3

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.436 Other References (ii) • The Taste of Smalltalk, Ted• Smalltalk The Language and Its Implementation (contains the original VM description Kaehler and Dave Patterson, Norton,available at users.ipa.net/~dwighth/smalltalk/bluebook/), Adele Goldberg and Dave 0-393-95505-2,1985 Robson, 0-201-11371-6, 1982 (called The Blue Book) To understand the language, its design, intention.... • Peter Deutsch, The Past, Present and the Future of Smalltalk, ECOOP’89 • Byte 81 Special Issues on Smalltalk (read paper language intent) • Alan Kay, The EarlyWesley, 1996 History of Smalltalk, History of Programming Languages, Addison-

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.437 VisualWorks /brain.cs.uiuc.edu/VisualWorks/ VisualAge /brain.cs.uiuc.edu/VisualAge/ kilana.iam.unibe.ch/SmalltalkWiki/ /www.stic.org/ /www.smalltalk.org/ /www.goodstart.com/stlinks.html /st-www.cs.uiuc.edu/ www.esug.org/ www.bsug.org/ www.gsug.org/ kilana.iam.unibe.ch/SmalltalkWiki/SwissSmalltalkUserGroup

Some Web Pages Wikis: STIC: Cool Sites: ESUG, BSUG, GSUG, SSUG

Object-Oriented Design with Smalltalk a Pure OO Language References Universität Bern Ducasse Stéphane 27.438