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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Query MethodA Composed Method has had to execute a boolean expression.How do you write a method that tests a property of an object?There are actually two decisions here. The first is deciding what to return from a method that tests aproperty. The second is what you should name the method.Designing the protocol for a Query Method provides you with two alternatives. The first is toreturn one of two objects. For example, if you have a switch that can be either on or off, you couldreturn either #on or #off.Switch>>makeOnstatus := #onSwitch>>makeOffstatus := #offSwitch>>status^statusThat leaves clients needing to know how Switch stores its status:WallPlate>>updateself switch status = #on ifTrue: [self light makeOn].self switch status = #off ifTrue: [self light makeOff]A maintenance programmer who innocently decides to change the Symbols to #On and #Off willbreak the client.It is far easier to maintain a relationship based solely on messages. Rather than status returning aSymbol, it is better for Switch to provide a single method that returns a Boolean, true if the Switchis on and false if the Switch is off.Whether this is represented in the Switch as a variable holding a Boolean or a variable holding oneof two Symbols is irrelevant to designing the protocol.The naming question is a bit more sticky. The simplest name for a method that tests a property andreturns a Boolean is just a simple name. In example above, I’d be tempted to call the method “on”:Switch>>on“Return true if the receiver is on, otherwise return false.”However, this leads to confusion. Does “on” mean “is it on?” or “make it on”?Return a Boolean. Name the method by prefacing the property name with a form of “be”- is,was, will, etc.Here are some examples from <strong>Smalltalk</strong>:isNilisControlWantedisEmptyLooking at the code above, I’m not sure it’s the greatest design in the world. I’d probably want tointroduce the switch directly to the light.<strong>Coding</strong> <strong>Patterns</strong> page 32 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!