s LearnSqueak.com

PRACTICAL SQUEAK WORKSHOP

Inheritance and composition: a shape workshop

Give rectangles, circles and groups one useful protocol, then draw and move them in Morphic.

10 construction stagesTested source & checkpointsNative screenshots & demos

Before you start

Inheritance lets related objects share behavior. Polymorphism lets a caller send the same message to different objects and receive the right behavior for each. We will separate those ideas: rectangles and circles inherit state and movement, while a composed group supports the same drawing and area messages without inheriting from our shape superclass. The result is a small native Morphic gallery with real buttons and a passing SUnit suite.

  • Comfortable with Workspace Do It and Print It
  • Can create a class and accept an instance method in a Browser
  • A standard Squeak 6.1 image, including Morphic and SUnit

Classes and objects · Using Squeak’s tools

Use Squeak 6.1 and save a learning copy of your image. Extract the bundle, open File List, select the named .st checkpoint and choose fileIn. Each checkpoint is complete and cumulative: it works on its own in a clean image, or in the numbered order shown here. File-in chunks contain ! separators and belong in File List. Short expressions labeled Workspace use Do It or Print It; Browser methods are accepted individually on the named class and side. No extra packages are needed. Moving backwards after installing a later checkpoint can leave later methods in your image, so use a fresh learning image for that experiment.

01 · Define the shared protocol before the subclasses

File in checkpoint 01. It defines LSShape, LSRectangle and LSShapeTest in LearnSqueak-Inheritance. Our classes are separate from Squeak’s own graphics classes. LSShape owns origin and color. initialize gives each instance 0@0 and blue; subclasses call super initialize before adding their own defaults. origin is the top-left of a shape’s bounding box, including a circle’s box.

area and drawOn: send subclassResponsibility. This documents a required behavior and raises an error if a concrete subclass forgets it. It does not make LSShape impossible to instantiate: Squeak enforces the missing method only when the message is sent. A protocol here is an agreement between callers and objects, not a separately declared interface type.

Browser → class definition pane → Accept this definition separately
Object subclass: #LSShape
    instanceVariableNames: 'origin color'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'LearnSqueak-Inheritance'
Browser → class definition pane → Accept this definition separately
LSShape subclass: #LSRectangle
    instanceVariableNames: 'width height'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'LearnSqueak-Inheritance'
Browser → LSShape → initialization → Accept this method
initialize
    super initialize.
    origin := 0@0.
    color := Color blue
Browser → LSShape → geometry → Accept this method
area
    self subclassResponsibility
Browser → LSShape → drawing → Accept this method
drawOn: aCanvas
    self subclassResponsibility
Where to run this

File List → fileIn source/01-rectangle.st. Then Workspace → Print It.

Construction code · follow the run instructions above
LSShape new origin.
Expected result

0@0. The first checkpoint has 3 passing tests.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
1. Define the shared protocol before the subclasses in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

02 · Let a rectangle provide its own geometry

LSRectangle is a subclass of LSShape with width and height. Its area method overrides the inherited requirement. bounds answers a Rectangle used by the canvas; that built-in Rectangle describes coordinates and is distinct from our LSRectangle model.

The setter validates both numbers before storing either one. A rejected update therefore leaves the old area intact. The inherited color: and origin: methods need no copies in this subclass. In the Browser, use the instance side: width and area describe one rectangle, not the class object.

Browser → LSRectangle → accessing → Accept this method
width: aNumber height: anotherNumber
    ((aNumber isNumber and: [anotherNumber isNumber])
        and: [aNumber > 0 and: [anotherNumber > 0]])
        ifFalse: [self error: 'Dimensions must be positive numbers'].
    width := aNumber.
    height := anotherNumber
Browser → LSRectangle → geometry → Accept this method
area
    ^ width * height
Browser → LSRectangle → geometry → Accept this method
bounds
    ^ origin extent: width@height
Where to run this

Workspace → select the entire block and Print It; methods shown below belong separately to LSRectangle.

Construction code · follow the run instructions above
| rectangle |
rectangle := LSRectangle new width: 30 height: 20.
rectangle area.
Expected result

600. No drawing is required to calculate area.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
2. Let a rectangle provide its own geometry in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

03 · Reuse movement through ordinary method lookup

When a rectangle receives translateBy:, Squeak starts looking for that selector on LSRectangle. It finds no override there, so it continues to LSShape and runs the inherited implementation with the original rectangle as self. The rectangle’s own origin changes.

Movement changes location, not size. Keeping that invariant in a test makes the shared behavior explicit. A subclass could override translation, but doing so should preserve the contract callers rely on. Inheritance is most useful when instances of a subclass can safely participate wherever this superclass’s behavior is expected.

Browser → LSShape → transforming → Accept this method
translateBy: delta
    origin := origin + delta
Where to run this

Workspace → Print It after checkpoint 01.

Construction code · follow the run instructions above
| rectangle before |
rectangle := LSRectangle new origin: 10@20; width: 30 height: 20.
before := rectangle area.
rectangle translateBy: 5@7.
{rectangle origin. rectangle area = before}.
Expected result

An Array containing 15@27 and true.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
3. Reuse movement through ordinary method lookup in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

04 · Add a circle by overriding the varying behavior

Checkpoint 02 adds LSCircle. It inherits origin, color and translateBy:, but implements different area, bounds and drawing methods. radius is positive; its bounding box has a side length of twice the radius. The canvas receives fillOval:color:, so a square bounding box produces the circular picture.

Circle area uses Float pi. Tests compare with a small tolerance rather than assuming every decimal representation is exact. Shared storage and movement stay in LSShape; the geometric formulas and canvas operations stay in the concrete classes.

Browser → class definition pane → Accept this definition separately
LSShape subclass: #LSCircle
    instanceVariableNames: 'radius'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'LearnSqueak-Inheritance'
Browser → LSCircle → initialization → Accept this method
initialize
    super initialize.
    radius := 1
Browser → LSCircle → accessing → Accept this method
radius: aNumber
    (aNumber isNumber and: [aNumber > 0])
        ifFalse: [self error: 'Radius must be a positive number'].
    radius := aNumber
Browser → LSCircle → geometry → Accept this method
area
    ^ Float pi * radius squared
Browser → LSCircle → drawing → Accept this method
drawOn: aCanvas
    aCanvas fillOval: self bounds color: color
Where to run this

File List → fileIn source/02-polymorphism.st; Workspace → Print It.

Construction code · follow the run instructions above
| circle |
circle := LSCircle new radius: 10.
{circle bounds extent. circle area}.
Expected result

The extent is 20@20 and the area is approximately 314.159265. All 6 tests pass.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
4. Add a circle by overriding the varying behavior in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

05 · Ask each shape for its area

The collection contains two different classes. inject:into: visits each element and sends area to it. Squeak chooses LSRectangle>>area for the first receiver and LSCircle>>area for the second. The loop needs no class checks or conditional formula selection.

Adding another shape means implementing the agreed messages on that shape; the summing code can stay unchanged. This is polymorphism. Inheritance helped these two classes reuse implementation, but it is not what makes the loop possible. Any object that answers area appropriately can participate.

Browser → LSShapeTest → tests → Accept this method
testPolymorphicSum
    | shapes total |
    shapes := {LSRectangle new width: 30 height: 20. LSCircle new radius: 10}.
    total := shapes inject: 0 into: [:sum :shape | sum + shape area].
    self assert: (total - (600 + (100 * Float pi))) abs < 0.000001
Where to run this

Workspace → Print It after checkpoint 02.

Construction code · follow the run instructions above
| shapes |
shapes := {LSRectangle new width: 30 height: 20. LSCircle new radius: 10}.
shapes inject: 0 into: [:sum :shape | sum + shape area].
Expected result

Approximately 914.159265 square units. The exact expected expression in the test is 600 + (100 * Float pi).

Download this checkpoint source

NATIVE SQUEAK CAPTURE
5. Ask each shape for its area in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

07 · Move the models, then refresh the view

Move all +20 sends moveShapes to its gallery. That method sends translateBy: to every member and then refreshes the label and invalidates the view with changed. Click three times, then Reset shapes. The total stays constant during movement because no dimensions change.

The model objects do not announce changes automatically. If you alter a shape from a Workspace, call gallery refresh afterward. shapes returns a copy of the collection, protecting its membership from accidental direct edits, but it still contains the same model objects. This is a shallow copy, not a deep clone.

Browser → LSShapeGallery → actions → Accept this method
moveShapes
    shapes do: [:shape | shape translateBy: 20@0].
    self refresh
Browser → LSShapeGallery → updating → Accept this method
refresh
    totalLabel contents: 'Sum of areas: ', (self totalArea roundTo: 0.01) printString,
        ' square units'.
    self changed
Where to run this

Workspace → Do It, or use Move all +20 in the panel you already opened.

Construction code · follow the run instructions above
| gallery |
gallery := LSShapeGallery new.
gallery openInWorld.
gallery moveButton doButtonAction.
Expected result

The first shape’s origin changes from 40@110 to 60@110. The displayed sum remains 25559.73.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
7. Move the models, then refresh the view in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

08 · Compose a group that speaks the same protocol

Checkpoint 04 defines LSShapeGroup as a subclass of Object. It stores members and delegates area, drawOn: and translateBy: to them. A gallery can contain a group and an ordinary shape together. That works because the gallery sends messages rather than checking ancestry.

A group is a has-members relationship. It does not need a single color, origin or radius, so inheriting LSShape would impose state that this implementation does not use. Composition lets us reuse the contained objects while keeping that relationship explicit. Group area means the sum of member areas: overlapping parts count more than once. It is not the area of a geometric union.

Browser → class definition pane → Accept this definition separately
Object subclass: #LSShapeGroup
    instanceVariableNames: 'members'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'LearnSqueak-Inheritance'
Browser → LSShapeGroup → geometry → Accept this method
area
    ^ members inject: 0 into: [:sum :shape | sum + shape area]
Browser → LSShapeGroup → drawing → Accept this method
drawOn: aCanvas
    members do: [:shape | shape drawOn: aCanvas]
Browser → LSShapeGroup → transforming → Accept this method
translateBy: delta
    members do: [:shape | shape translateBy: delta]
Where to run this

File List → fileIn source/04-composition.st; Workspace → Do It.

Construction code · follow the run instructions above
| group gallery |
group := LSShapeGroup new
    add: (LSRectangle new origin: 40@110; width: 120 height: 90; color: Color blue);
    add: (LSCircle new origin: 180@120; radius: 45; color: Color orange).
gallery := LSShapeGallery new shapes: {group}.
gallery openInWorld.
Expected result

Both members draw through the group. Move all +20 delegates movement to the members. All 11 tests pass.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
8. Compose a group that speaks the same protocol in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

09 · Test the contract at the model and view boundaries

The suite checks formulas, validation, inherited state, movement and the heterogeneous sum. It also checks that a group is not an LSShape while still working in the gallery. UI component tests send doButtonAction to real buttons, exercising their configured target and selector.

The gallery tests use ensure: to delete their views. Pixel dimensions are only a small rendering smoke test; they do not prove every visual detail or physical mouse interaction. The deliberately empty group answers zero. These examples state what clients may expect, leaving room to change the internal representation.

Browser → LSShapeTest → tests → Accept this method
testGroupDelegatesWithoutShapeInheritance
    | group rectangle |
    group := LSShapeGroup new.
    rectangle := LSRectangle new width: 30 height: 20.
    group add: rectangle; add: (LSCircle new radius: 10).
    self deny: (group isKindOf: LSShape).
    self assert: (group area - (600 + (100 * Float pi))) abs < 0.000001.
    group translateBy: 9@4.
    self assert: rectangle origin equals: 9@4
Where to run this

Workspace → Do It, then Test Runner → Run Selected.

Construction code · follow the run instructions above
TestRunner openForSuite: LSShapeTest suite.
Expected result

11 run, 11 passes, 0 failures, 0 errors at checkpoint 04.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
9. Test the contract at the model and view boundaries in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

10 · Extend the model and choose relationships deliberately

Checkpoint 05 includes the three exercise solutions below. The rectangle can answer isSquare, the circle accepts diameter: by delegating to its validated radius setter, and a group can remove a member safely. Each extension has an executable test; the complete suite has 14.

Use inheritance when the shared state and behavior describe a stable kind-of relationship and subclasses preserve the expected contract. Use composition when you want an object to work with replaceable collaborators. In this lesson a gallery contains shapes, a group contains members, and a circle is a shape. None of those choices follows merely from wanting to reuse a few lines of code.

This deliberately small group does not prevent cycles or shared members. Adding the same mutable shape to two groups means both groups refer to that one object; moving either group moves it. Keep membership acyclic and ownership intentional, or add explicit validation and copying policies in a larger application.

Where to run this

File List → fileIn source/05-exercise-solutions.st; Workspace → Print It.

Construction code · follow the run instructions above
LSShapeTest suite run.
Expected result

14 run, 14 passes, 0 failures, 0 errors.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
10. Extend the model and choose relationships deliberately in native Squeak 6.1
Native Squeak 6.1 capture from this lesson’s verified source; prepared by a reproducible script.

Watch the workflow

Every screenshot comes from the actual Squeak 6.1 image. Animations are scripted sequences of native rendered states, not a recording of a person clicking. Their playback speed is editorial and does not represent benchmark time. Source, verification results and capture provenance are included in the bundle.

NATIVE SQUEAK CAPTURE
Inheritance and composition: a shape workshop demonstration
Scripted native Morphic sequence: the actual Move all +20 button runs three times, then Reset shapes. Both concrete classes inherit the same translation behavior.
NATIVE SQUEAK CAPTURE
Inheritance and composition: a shape workshop demonstration
Scripted native Morphic sequence: two group members move together, while the separate green rectangle stays put; the orange member is then removed using the tested exercise method. The displayed area follows the model.

Practice with tested solutions

1. Ask whether a rectangle is square

Add isSquare to LSRectangle. A 12 by 12 rectangle should answer true; a 12 by 20 rectangle should answer false. Reuse the existing dimensions.

Browser → LSShapeTest → tests-exercises → Accept the test, then run it before implementing the method.

Write the test first
testRectangleIsSquare
    self assert: (LSRectangle new width: 12 height: 12) isSquare.
    self deny: (LSRectangle new width: 12 height: 20) isSquare
Show a tested solution

Browser → LSRectangle → instance side → geometry → Accept isSquare. Or file in checkpoint 05.

Exercise solution
isSquare
    ^ width = height
Expected

The two assertions pass. No extra state or subclass is required.

Download complete exercise solution

2. Set a circle by diameter

Add diameter: on LSCircle. Route the update through radius: so the existing positive-number validation still applies. Test a rejected update as well as the ordinary case.

Browser → LSShapeTest → tests-exercises → Accept the test and run it.

Write the test first
testDiameterReusesRadiusValidation
    | circle |
    circle := LSCircle new diameter: 20.
    self assert: circle bounds extent equals: 20@20.
    self should: [circle diameter: 0] raise: Error.
    self assert: circle bounds extent equals: 20@20
Show a tested solution

Browser → LSCircle → instance side → accessing → Accept diameter:. Or file in checkpoint 05.

Exercise solution
diameter: aNumber
    self radius: aNumber / 2
Expected

Diameter 20 yields a 20@20 bounding box. Diameter 0 raises Error and leaves the valid size unchanged.

Download complete exercise solution

3. Remove a composed member safely

Add remove: to LSShapeGroup. Answer the removed object, or nil if it was absent. The group’s summed area must change because the remaining collection changed.

Browser → LSShapeTest → tests-exercises → Accept and run the test.

Write the test first
testGroupRemoval
    | group rectangle |
    group := LSShapeGroup new.
    rectangle := LSRectangle new width: 12 height: 12.
    group add: rectangle.
    self assert: (group remove: rectangle) identical: rectangle.
    self assert: group area equals: 0.
    self assert: (group remove: rectangle) isNil
Show a tested solution

Browser → LSShapeGroup → instance side → changing → Accept remove:. Or file in checkpoint 05.

Exercise solution
remove: aShape
    ^ members remove: aShape ifAbsent: [nil]
Expected

Removing the only rectangle returns that rectangle and leaves area 0. Removing it again answers nil. All 14 tests pass.

Download complete exercise solution

When something looks wrong

A subclassResponsibility error appears

Read the receiver class and selector in the debugger. The receiver lacks the concrete implementation of area or drawOn:. File in the intended checkpoint or accept that method on the correct instance side.

The shape moved in the model but the picture stayed still

Call gallery refresh after changing a model from outside the gallery. The button actions already do this.

A group is not found or remove: is missing

LSShapeGroup first appears in checkpoint 04; its remove: exercise appears in checkpoint 05. File in the appropriate complete checkpoint.

Verification, cleanup and next steps

Verified in an isolated copy of official Squeak 6.1 build 23976, 64-bit Linux. Checkpoints pass 3, 6, 8, 11 and 14 tests respectively.

  • Native gallery and button actions executed; mixed shape dispatch, inherited movement and composed group rendering verified
  • Exercise tests check square detection, diameter validation and safe member removal
  • Each source checkpoint also tested independently from the clean baseline image
  • The animations are native render sequences; they do not simulate physical input

Close the galleries and Test Runner when finished. The source uses only the LearnSqueak-Inheritance category and does not alter core classes. Keep the .st source files if you want to recreate the lesson in a fresh image.

  • Shipped Squeak 6.1 source — Object>>subclassResponsibility, Morph>>drawOn:, Canvas>>translateBy:during:, Canvas>>fillRectangle:color:, Canvas>>fillOval:color: and TestCase are inspectable in the image

Explore more working examples · Return to the learning path

Scope of this example

  • Dimensions are positive numeric values; the example is not a geometry library with units, transforms, hit-testing or overflow policies
  • Area sums include overlaps; group cycles and shared mutable ownership are outside this small model
  • An external model mutation needs an explicit gallery refresh