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.

Conditional ExpressionHow do you format conditional expressions where both branches assign or return a value?Most programming languages make a distinction between statements that work solely by side effectand expressions that return values. For example, control structures in C and Pascal work only bycontrolling how other statements execute.In <strong>Smalltalk</strong> there are no pure statements. All control structures are implemented in terms ofmessages, and all messages return values. This leads to the possibility of using the value of controlstructures.Programmers new to <strong>Smalltalk</strong> are likely to be surprised the first time they encounter loops orconditionals used as an expression. New <strong>Smalltalk</strong>ers are likely to write:self isInitializedifTrue: [cost := self calculateCost]ifFalse: [cost := 0]These expressions can be translated into the following without changing the meaning:cost := self isInitializedifTrue: [self calculateCost]ifFalse: [0]Is the simpler form worth the possibility of confusion for beginners? It more directly communicatesthe intent of the expression. You don’t mean “there are two paths of expression, one of which setsthe value of cost to the result of sending myself calculateCost and the other of which sets the valueof cost to 0,” you mean “set cost to one of two values, either the result of sending myselfcalculateCost or 0.”Format conditionals so their value is used where it clearly expresses the intent of the method.Assignment and return are often found in both branches of a conditional. Look for opportunities tofactor both to the outside of the conditional.Here is an example of a return on both branches of a conditional:costself isInitializedifTrue: [^self calculateCost]ifFalse: [^0]If I write code like this, I don’t mean “here are two alternative paths of execution,”, I mean, “hereare two alternative values to be returned.” Thus, a Conditional Expression expresses my intentmore clearly:cost^self isInitializedifTrue: [self calculateCost]ifFalse: [0]I commonly see code in which both sides of a conditional expression evaluate to a Boolean. Startwith this:<strong>Coding</strong> <strong>Patterns</strong> page 132 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!