S.Ducasse Stéphane Ducasse 1 Smalltalk Coding Idioms.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Advertisements

Smalltalk Coding Patterns mostly from Smalltalk Best Practice Patterns Kent Beck Prentice-Hall, 1997.
Stéphane Ducasse«ChapterNr».1 Selected Design Patterns Design Patterns are recurrent solutions to design problems They are pros and cons We already saw:
Stéphane Ducasse«ChapterNr».1 Abstract Classes Should not be instantiated (abstract in Java) But can defined complete methods Defines a protocol common.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Six compound procedures and higher-order procedures.
Stéphane Ducasse«ChapterNr».1 Arthur Riel Design Heuristics from Object-Oriented Design Heuristics by Arthur Riel Read the Heuristics… –Find reasons why.
Stéphane Ducasse9.1 Inheritance Semantics and Lookup.
Stéphane Ducasse 1 The Taste of Smalltalk.
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz Summer Semester 2006.
Some Basic Points on Classes
03G-1 Everything is an Object Examining builtin classes All these are classes in Little Smalltalk:  Object  Class  Method  Block  Boolean True False.
Squeak Collections The Squeak collection hierarchy. Some collection operators. Working with collections. For-loops.
Chapter 10 Classes Continued
Stéphane Ducasse5.1 Smalltalk in a Nutshell OO Model in a Nutshell Syntax in a Nutshell.
4. Smalltalk Coding Idioms. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.2 Roadmap  Snakes and Ladders — Cascade and Yourself  Lots of Little Methods.
Stéphane Ducasse«ChapterNr».1 Basic Objects, Conditionals and Loops Booleans Basic Loops Overview of the Collection hierarchy— more than 80 classes: (Bag,
S.Ducasse Stéphane Ducasse 1 The Taste of Smalltalk.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Patterns. Design comes from Modeling (requirements, analysis, problem) Mending (patch, refactoring) Memory (patterns, recall)
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
S.Ducasse Stéphane Ducasse 1 Classes and Metaclasses - an Analysis.
Refactoring Improving the structure of existing code Refactoring1.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
S.Ducasse Stéphane Ducasse 1 Design Heuristics.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Object-oriented Programming and Design 1 Polymorphism Poly => many Morph => shape Variables take on many shapes, or many classes of objects.
Refactoring1 Improving the structure of existing code.
Stéphane Ducasse 1 Visitor.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Smalltalk (and Squeak) Aida Dungan and Rick Shreve.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Inheritance Semantics and Method Lookup.
Object-oriented programming and design 1 Object Identity = vs. == copying objects Value Object ValueWithHistory.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
CSE 341, S. Tanimoto Java brief review - 1 Java Brief Review Java’s strengths Object-oriented terminology Inheritance Interfaces An example with inheritance.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Stéphane Ducasse 1 Singleton.
M1G Introduction to Programming 2 5. Completing the program.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
S.Ducasse Stéphane Ducasse 1 Common Mistakes and Debugging in VW.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring1 Improving the structure of existing code.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Stéphane Ducasse 1 Some Points on Classes.
S.Ducasse Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Smalltalk in a Nutshell.
1 Introduction 1. Why Data Structures? 2. What AreData Structure? 3. Phases of Software Development 4. Precondition and Postcondition 5. Examples.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
FIT Objectives By the end of this lecture, students should: understand the role of constructors understand how non-default constructors are.
Stéphane Ducasse 1 Elements of Design - Unit of Reuse.
OOP Basics Classes & Methods (c) IDMS/SQL News
Stéphane Ducasse 1 Abstract Classes.
S.Ducasse 1 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface.
UNIT-IV Designing Classes – Access Layer ‐ Object Storage ‐ Object Interoperability.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Improving the structure of existing code
Smalltalk on a Dime.
Presentation transcript:

S.Ducasse Stéphane Ducasse 1 Smalltalk Coding Idioms

S.Ducasse License: CC-Attribution-ShareAlike

S.Ducasse 3 Idioms Inspired by Smalltalk Best Practice Patterns by K. Beck

S.Ducasse 4 Conversion Method

S.Ducasse 5 Conversion Methods ‘ asURLhttp:// Handy But not all the strings are urls makes only sense when network package is loaded bloat your interface with conversion methods for anything

S.Ducasse 6 Conversion Methods Use conversion methods only when the return typed is polymorphic to the receiver aCol asSet aCol asOrderedCollection For the rest use readFrom: URL readFrom: ‘

S.Ducasse 7 Constructor

S.Ducasse 8 How do you represent instance creation? Most simple way: Packet new addressee: # mac ; contents: ‘hello mac’ Good if there are different combinations of parameters. But you have to read the code to understand how to create an instance. Alternative: make sure that there is a method to represent each valid way to create an instance. Constructor Method

S.Ducasse 9 Provide methods in class “instance creation” protocol that create well-formed instances. Pass all required parameters to them Packet class>>send: aString to: anAddress ^ self basicNew contents: aString ; addressee: anAdress ; yourself Constructor Method (solution)

S.Ducasse 10 Examples Point class>>x:y: Point class>> r: radiusNumber theta: thetaNumber ^ self x: radiusNumber * thetaNumber cos y: radiusNumber * thetaNumber sin SortedCollection class>>sortBlock: aBlock

S.Ducasse 11 Complete Creation Method Class methods that create instances are in category "instance creation" methods. Creation followed by initialization is the most flexible. Point new x: 0; y: 0 Important to preserve invariants and avoid ill-formed objects.

S.Ducasse 12 Once you define a constructor with parameters, how do you pass them to the newly created instance? Packet class>>send: aString to: anAddress ^ self basicNew contents: aString ; addressee: anAdress ; yourself But this violates the “say things once and only once” rule (initialize) Constructor Parameter Method

S.Ducasse 13 Code a single method in the “private” procotol that sets all the variables. Preface its name with “set”, then the names of the variables. Packet class>>send: aString to: anAddr ^ self basicNew setContents: aString addressee: anAddr Packet>>setContents: aString addressee: anAddress contents:= aString. addressee := anAddress. ^self Constructor Parameter Method

S.Ducasse 14 Interesting Result Packet>>setContents: aString addressee: anAddress contents:= aString. addressee := anAddress. ^self Note self (Interesting Result) in setContents: addressee, because the return value of the method will be used as the return of the caller

S.Ducasse 15 Complete Creation Method Instance creation methods should create well- formed instances. Pass all required parameters to them. Point x: 0 y: 0 SortedCollection sortBlock: aBlock Set new

S.Ducasse 16 Creation Parameter Method How should a Complete Creation Method initialize new object? Separate setters are more flexible x: aNumber y: anotherNumber ^self new x: aNumber; y: anotherNumber But difficult to identify where checks can be defined

S.Ducasse 17 Creation Parameter Method Provide a single method that sets all the variables. Preface its name with "set", then the names of the variables. Forces the client to specify all arguments Place to check semantics constraints XX class>>x: aNumber y: anotherNumber ^self new setX: aNumber y: anotherNumber XX>>setX: aNumber y: anotherNumber ^self x: aNumber; y: anotherNumber

S.Ducasse 18 Composed Methods

S.Ducasse 19 Composed Method How big should a method be? Write methods that perform one identifiable task. Few lines per method. Consistent level of abstraction. Minimizes number of methods you have to change in subclass. Minimizes code copying in subclass.

S.Ducasse 20 Composed Method Usage Top down self input; process; output Bottom up common expressions long loop bodies comments

S.Ducasse 21 Methods from Comments Comments indicate "identifiable task" If you need to comment a block of code, it probably should be a separate method. Turn method comment into method name.

S.Ducasse 22 Querying methods Do know want to reveal implementation Still communicate well

S.Ducasse 23 Query Method by Example Instead of: Switch>>makeOn status := #on Switch>>makeOff status := #off Switch>>status ^status Client>>update self switch status = #on ifTrue: [self light makeOn] self switch status = #off ifTrue: [self light makeOff] It is better to define Switch>>isOn, Switch>>isOff Switch>>on is not a good name... #on: or #isOn ?

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

S.Ducasse 25 Boolean Property Setting Don't write accessing methods with only argument is a boolean Create two methods beginning with "make” “be”. Add "toggle" if necessary. makeVisible / makeInvisible / toggleVisible makeDirty / makeClean beOn, beOff

S.Ducasse 26 Comparison Methods

S.Ducasse 27 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... Sometimes there is no absolute way of comparing If you redefine =, you should redefine hash Comparing Method

S.Ducasse 28 Comparing Methods We can also use sortBlock: of SortedCollection class...sortBlock: [:a :b | a income > b income] Here you can have multiple ways to compare

S.Ducasse 29

S.Ducasse 30 Execute Around Method How do we 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, he should invoke them on the right order. Execute Around

S.Ducasse 31 Code a method that takes a Block as an argument. Name the method by appending “During: aBlock” to the name of the first method that have to be invoked. In the body of the Execute Around Method, invoke the first method, evaluate the block, then invoke the second method. File>>openDuring: aBlock self open. [aBlock value] valueNowOrUnwindDo: [self close] Execute Around (solution)

S.Ducasse 32 Cursor>>showWhile: aBlock | oldcursor | oldcursor := self class currentCursor. self show. ^aBlock valueNowOrOnUnwindDo: [oldcursor show] Execute Around Example

S.Ducasse 33 Collection Idioms do: collect: includes:

S.Ducasse 34 Instead of writing: |index| index := 1. [index <= aCollection size] whileTrue: [... aCollection at: index... index := index + 1] Write: aCollection do: [:each |...each...] do:

S.Ducasse 35 Instead of writing: |result| result := aCollection species new: aCollection size. 1 to: aCollection size do: [ :each | result at: each put: (aCollection at: each) abs]. Write: aCollection collect: [:each| each abs] Note that this solution works well for indexable collection and also for sets. The previous doesn’t. collect:

S.Ducasse 36 Instead of writing:...aCollection size = 0 ifTrue: [...]...aCollection size > 0 ifTrue: [...] Write:... aCollection isEmpty isEmpty

S.Ducasse 37 Instead of writing: | found | found := false. aCollection do: [:each| each = anObject ifTrue: [found : = true]]. | found | found := (aCollection detect: [:each| each | anObject] ifNone:[ nil]) notNil. Write: aCollection includes: anObject includes:

S.Ducasse 38 Reversing Method

S.Ducasse 39 How to code a smooth flow of messages? Point>>printOn: aStream x printOn: aStream aStream nextPutAll: y printOn: aStream Here three objects receive different messages. Reversing Method

S.Ducasse 40 Code a method on the parameter. Derive its name form the original message. Take the original receiver as a parameter to the new method. Implement the method by sending the original message to the original receiver. Reversing Methods (II)

S.Ducasse 41 Reversing... But creating new selectors just for fun is not a good idea. Each selector must justify its existence. Stream>>print: anObject anObject printOn: self Point>>printOn: aStream aStream print: x; nextPutAll: print: y Note that the receiver can now change without affecting the other parameters

S.Ducasse 42 Printing and comments

S.Ducasse 43 How do you code the default printing method? There are two audiences: you (a lot of information) your clients (should not be aware of the internal) Override printOn: to provide information about object’s structure to the programmer In VisualWorks, two needs are supported displayString for clients printString for you (call printOn:) Debug Printing Method

S.Ducasse 44 How do you comment methods? Templates are not a good idea. Can be obsolete Intention Revealing Selector says what the method does. Type Suggesting Parameter Name says what the arguments are expected to be..... Method Comment

S.Ducasse 45 Communicate important information that is not obvious from the code in a comment at the beginning of the method Example of important information: Method dependencies, preconditions To do Reasons for changes (in a base class) Method Comment

S.Ducasse 46 Example (self flags bitAnd: 2r1000) = 1 “Am I visible?” ifTrue:[...] is becoming... isVisible ^(self flags bitAnd: 2r1000) = 1 self isVisible ifTrue:[...]

S.Ducasse 47 Delegation

S.Ducasse 48 How does an object share implementation without inheritance? With inheritance code in written in 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

S.Ducasse 49 Pass part of its work on to another object Many objects need to display, all objects delegate to a brush-like object (Pen in VisualSmalltalk, GraphicsContext in VisualAge and VisualWorks) All the detailed code is concentrated in a single class and the rest of the system has a simplified view of the displaying. Delegation

S.Ducasse 50 How do you invoke a disinterested delegate? is the identity of the delegating object important? The delegating object can pass itself to be notified by the delegate.The delegate could not want to have an explicit reference to the delegating but still need access to it. is the state of the delegating object important to the delegate? If the delegate has no reason to need the identity of the delegating object and it is self-contained to accomplish its task without additional state: Simple Delegation Simple Delegation

S.Ducasse 51 Delegate messages unchanged Suppose an object that acts a bit as a collection but has lots of other protocols, instead of inheriting from a collection, delegates to a collection. Collection doesn’t care who invoked it. No state from the delegating is required. Simple Delegation (solution)

S.Ducasse 52 How do you implement delegation to an object that needs reference to the delegating object? Have a reference in the delegate to the delegating. Drawbacks: extra complexity, each time the delegate changes, one should destroy the old reference and set a new each delegate can only be used by one delegating, If creating multiple copies of the delegate is expensive or impossible, this does not work Pass along the delegating object (i.e., self ) in an additional parameter called “for:” Self Delegation

S.Ducasse 53 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 by different collections. Dictionaries compute hash by sending “hash” and IdentityDictionaries by sending “basicHash” Example of Self Delegation

S.Ducasse 54 Example Dictionary>>at: key put: value self hashTable at: key put: value for: self HashTable>>at: key put: value for: aCollection |hash| hash := aCollection hashOf: key... Dictionary>>hashOf: anObject ^anObject hash IdentityDictionary>>hashOf: anObject ^anObject basicHash The hierarchy of hashed Collections is then independent of the hierarchy of the HashTable

S.Ducasse 55 Conclusion Digest slowly Think about your code