SDSU CS 683 Emerging Technologies: Embracing Change
Spring Semester, 2001
Coding Patterns
Previous    Lecture Notes Index    Next    
© 2001, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 15-Feb-01

Contents of Doc 7, Coding Patterns

This document is taken from the following two references. All the good ideas here are from Beck and Johnson. Quoted text in this lecture is from Beck's book.

My contribution is just to realize that their ideas are well worth stealing. Johnson lecture on coding style alone is worth the price of his on-line course. Beck's text is a must own for a Smalltalk programmer.

CS 497 Object-Oriented Programming & Design, Lecture notes, Ralph Johnson, Department of Computer Science, UIUC,

Smalltalk Best Practice Patterns, Kent Beck, Prentice Hall, 1997

Doc 7, Coding Patterns Slide # 2

Coding Patterns

Kent Beck's Predictors of Good Style

"In a program written with good style,
everything is said once and only once"
"Good code invariable has small methods and small objects"

"When you can extend a system solely by adding new objects without modifying any existing objects, then you have a system that is flexible and cheap to maintain."
Object should be easily moved to new contexts
"Don't put two rates of change together"

Doc 7, Coding Patterns Slide # 3
Coding Standards

Consistency makes the code easier to read

A poor standard is better than mixing several good styles

Doc 7, Coding Patterns Slide # 4


Names have big impact on the readability of code

Names should mean something

at:put:, size, printString

Use standard naming conventions

Doc 7, Coding Patterns Slide # 5

Class Names

Smalltalk class names:

Names are read 100 to 1000 times more often than typed
Abbreviations waste more time (reading) than they save
SmallInteger, LimitedWriteStream, LinkedMessageSet

Doc 7, Coding Patterns Slide # 6

Simple Superclass Name

Superclass names


Doc 7, Coding Patterns Slide # 7

Qualified Subclass Name

If name is in common use
Array, Number, String
If the purpose is more important that class hierarchy
If the class hierarchy is important
Subclass is conceptually a variation on the superclass
OrderedCollection, LargeInteger, CompositeCommand

Doc 7, Coding Patterns Slide # 8

Method Names

If a standard name exists, use of over following these rules

Search the image for similar methods

Doc 7, Coding Patterns Slide # 9

Intention Revealing Selector

Don't name methods after how it works
linearSearchFor: indicates how the method works
searchFor: is better
includes: is even better

To test a name

Imagine a second very different implementation
Will the name work for both implementations?

Doc 7, Coding Patterns Slide # 10
Types of Methods

General Types

Specialized Types with special rules

Doc 7, Coding Patterns Slide # 11
Names for Methods that

Modify the Receiver

Use a verb phrase for the name


Doc 7, Coding Patterns Slide # 12
Names for Methods that

Modify an Argument

Use a verb phrase ending with preposition like:


Doc 7, Coding Patterns Slide # 13
Names for Methods that

Return a value

Use a noun phrase or adjective

Use description not a command


Doc 7, Coding Patterns Slide # 14
Accessing State

How does a method access instance variable?

   deposit: aFloat
      balance := balance + aFloat

   deposit: aFloat
      self balance: (self balance + aFloat)

Direct access
Easier to read
Better information hiding

Indirect access
Makes subclassing easier
Permits lazy evaluation

Doc 7, Coding Patterns Slide # 15

Accessing Methods

Methods setting and getting the state of an object

Use the name of the variable

x x:
balance balance:

Java prepends set and get to these methods

This is not the Smalltalk convention

Doc 7, Coding Patterns Slide # 16

Boolean Property Accessing

Don't make accessing methods with just a boolean argument

For setter use two methods starting with "make"

makeVisible, makeInvisible
makeClean, makeDirty

Add a "toggle" method if needed


For getters use methods starting with "is"


Doc 7, Coding Patterns Slide # 17

Query Methods

Query methods

Prefix the name with a form of "be"


Use common English testing words

If the negation of a query method is common provide an inverse method


Place query methods in testing category (or protocol)

Doc 7, Coding Patterns Slide # 18

Converter Methods

Converter methods convert the receiver to another object with the same protocol

Converting float to an integer
Converting a string to a bag

Prepend "as" to the name of the class of the object returned


Doc 7, Coding Patterns Slide # 19
Converter Constructor Method

Converting an object to another with different protocol

Converting a string to a date object

Provide a class method that

Name the method by prepending "from" to the class of the original object

Example - in the Date class have:

fromString: aString
"Returns a date object represented by aString"

Doc 7, Coding Patterns Slide # 20

Composed Method

Methods should perform one identifiable task

This minimizes

Doc 7, Coding Patterns Slide # 21
How to Use Composed MethodTop-Down

While writing a method


Factor common code in a single method

Put long loop bodies into separate method

If lines of code need a comment, place the code in a method with Intention Revealing Selector

If you send two or more messages to an object in a method, add a method in that object with Intention Revealing Selector

Doc 7, Coding Patterns Slide # 22

Variable Names

Key pieces of information about a variable

Roles or purpose

Doc 7, Coding Patterns Slide # 23
Role Suggesting Instance Variable Name

Name instance variables for the role they play

Use a plural name if the variable is a collection

Comment the type in the class comment

Doc 7, Coding Patterns Slide # 24
Type Suggesting Parameter Name

Keywords indicate the parameter's role

Name parameters after the most general expected type

   at: anInteger put: anObject
   add: aCharacter

If multiple parameters have same type, precede the class with descriptive name

Doc 7, Coding Patterns Slide # 25
Temporary Variable Names

Name temporaries after the role they play

Methods are simpler when they don't use temporaries

Don't avoid using temporaries, try to write methods that don't need them

Doc 7, Coding Patterns Slide # 26

Behavior & State

Explicit Initialization

How to initialize an instance variable to a default value?

Implement an "initialize" method

Object subclass: #Timer
   instanceVariableNames: 'count period '
Instance Methods
Category: initialize

   count := 0.
   period := self defaultMillisecondPeriod
Category: private

Class Methods

Category: instance creation

   ^self basicNew initialize

Doc 7, Coding Patterns Slide # 27

Lazy Initialization

How to initialize an instance variable to a default value?

Lazy initialization uses

Explicit initialization favors readability

Lazy initialization favors
Subclasses can easily change defaults
Initialization is done only when needed

In timer class remove initialize method and add:

   period isNil ifTrue: [period := self defaultMillisecondPeriod].
   count isNil ifTrue: [count := self defaultCount].

Doc 7, Coding Patterns Slide # 28
Choosing Message

"The long term health of a system is all about managing themes and variations"

Avoid using conditional logic (if statement)

Replace if statement with message sends


   responsibility := (entry isKindOf: Film)
      ifTrue: [anEntry producer]
      ifFalse: [anEntry author]


   Responsibility := anEntry responsibility
Where in the Film class we have

      self producer

And in the Entry class we have

      self author

Doc 7, Coding Patterns Slide # 29
Method Comment

"Communicate important information that is not obvious from the code in a comment at the beginning of the method"

Types of information difficult to convey in code

Sometimes another method must be called before this one

If you need to change a method written by someone else comment why

Doc 7, Coding Patterns Slide # 30
Formatting Methods

Consistency of code layout improves readability

Squeak's system browser formats code, use it

To improve your code layout and understanding of the issues involved read Kent Beck's book: Smalltalk Best Practice Patterns

Doc 7, Coding Patterns Slide # 31

1. Find examples of code in the Squeak image that follow the guidelines given here.

2. Find examples of code in the Squeak image that violate the guidelines given here.

3. Contrast the readability and flexibility of the examples found in 1 & 2.

Copyright ©, All rights reserved.
2001 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
OpenContent license defines the copyright on this document.

Previous    visitors since 15-Feb-01    Next