Methods & Protocols
Parts: message pattern, optional comment, optional temporaries, optional pragmas (<primitive: 60>, <script>, <example>), statements.
14.1 Anatomy of a method
Parts: message pattern, optional comment, optional temporaries, optional pragmas (<primitive: 60>, <script>, <example>), statements.
BankAccount >> transfer: anAmount to: anotherAccount
"Move anAmount from me to anotherAccount. Answer the receiver."
| fee | "temporaries"
fee := self feeFor: anAmount.
self withdraw: anAmount + fee.
anotherAccount deposit: anAmount.
^ self "explicit return (optional here)"14.2 Protocols (method categories)
Methods are grouped into protocols — purely organizational, but conventions matter:
initialize, setters used during construction getters and setters
isEmpty, isValid, hasChildren — answer booleans =, hash, < printOn:, displayStringOn: asString, asArray, asDictionary do:, collect: implementation details (not enforced!) instance creation (class side)
extension methods belonging to another package Pharo automatically categorizes many methods (e.g., accessors) when you accept them.
14.3 Extension methods
You can add methods to any class, including Object, String, or Integer. Put them in a protocol named *YourPackage so they are saved with your package:
Extensions are powerful; use them sparingly and avoid overriding existing methods of other packages.
"protocol: *Bank-Core"
Number >> euros
^ Money amount: self currency: #EUR25 euros. "→ a Money"14.4 Script and example methods
Class-side methods tagged with the <example> or <script> pragma (e.g., BankAccount class >> exampleTransfer) get a clickable icon in the browser to run them — executable documentation.
14.5 Accessors and code generation
Right-click a class → *Generate accessors* (or *Refactorings → Generate accessors*) creates getter/setter pairs for selected slots. Many Smalltalkers expose only what is needed — "tell, don't ask".
14.6 Method-related reflection
Methods are objects: BankAccount >> #deposit: answers the CompiledMethod (with sourceCode, protocol, selector); BankAccount includesSelector: #withdraw: and BankAccount canUnderstand: #printString (inherited) answer booleans. More in Chapter 30.