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.

Variable StateHow do you represent state whose presence varies from instance to instance?Warning! This is not a pattern you should use often, if ever. It is here because you will see codewritten with it, and you will have to understand what is going on.This pattern is here for all the LISP programmers who come to <strong>Smalltalk</strong>. Some LISP culturesvalue flexibility over all else. Their objects tend to have no fixed parts. A Point might have an x, itmight have a y, it might have a color, who knows?The symptom of code like this is that classes declare a single instance variable that holds aDictionary mapping Strings or Symbols (the names of variables) to Objects. Some of the values ofthe Dictionary might be Numbers, others Collections, others Strings. Moreover, if you look atseveral instances of this class, all of their Dictionaries have the same keys.The problem with code like this is that you can’t read it and understand what is going on. Theprogramming tools don’t support this style of programming well. There is no equivalent of “browseinstance variable references” for code that stores all its state in Dictionaries.It is certainly legitimate to build models where state is sometimes present and sometimes not, evenin instances of the same class. You wouldn’t want to declare a hundred variables almost all ofwhich are nil in almost all instances, just because a few instances will need them.Put variables that only some instances will have in a Dictionary stored in an instance variablecalled “properties”. Implement “propertyAt: aSymbol” and “propertyAt: aSymbol put:anObject” to access properties.Make sure that any variables all or nearly all instances share are implemented as instance variables,not as entries on the property list.You may want to hide the difference between variables stored as instance variables and variablesstored on the property list with a Getting Method and Setting Method.<strong>Coding</strong> <strong>Patterns</strong> page 62 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!