13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Enumeration MethodYou are using Indirect Variable Access. You may have implemented a Collection AccessorMethod.How do you provide safe general access to collection elements?Sometimes clients want lots of ways of accessing a private collection. You could implement twentyor thirty Collection Accessor Methods, but you haven’t the time and you aren’t even sure even thatwould be enough. At the same time, all the argument for not just making a Getting Method for thecollection public still hold.Implement a method that executes a Block for each element of the collection. Name themethod by concatenating the name of the collection and “Do:”.The Enumeration Method for a Department’s Employees looks like this:Department>>employeesDo: aBlockemployees do: aBlockNow client code that wants to get a collection of all of the Employees in a bunch of departmentscan use a Concatenating Stream:allEmployees| writer |writer := WriteStream on: Array new.self departments do: [:eachDepartment | each employeesDo: [:eachEmployee | writernextPut: eachEmployee]]^writer contentsWhat if you want Departments to be able to contain other Departments, and not just Employees(this is an example of the modeling pattern Composite)? You can implement employeesDo: forboth:Department>>employeesDo: aBlockemployees do: [:each | each employeesDo: aBlock]Employee>>employeesDo: aBlockaBlock value: self<strong>Coding</strong> <strong>Patterns</strong> page 74 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!