Imagine, you have some object with amount and price variables.
And you want to calculate total, put this totals to collection and
calculate grand total.

Naive implementation will be something like
total := amount * price for the first task
and something like
grandTotal := totals sum for the latter one.

But what if amount or price are nil's?
You can add nil checks, of course: total := (amount ifNil:[0]) * (price
ifNil: [0]).
And then what if totals will be empty? *More checks*.
Is it really wise to have total to be zero if amount is nil? *More
ifTrue:ifFalse: code*.
And then you want to add amount := total / price calculation, and you
realize that both total and price may be nil, and price may be zero.
*More and more and more checks.*

*Protego* (http://www.smalltalkhub.com/#!/~assargadon/Protego) adds
"protected" versions of common operators and methods.

So, you just put
total := amount *@ price
and
grandTotal := totals sum_protected
into your code - and everything *just works*.

total will be nil if any of the operands are nil. grandTotal will be
calculated normally, even for empty totals collection (will return nil for
empty collection).
Collection can hold nil's and it will work anyway. If all elements of the
collection is nil, result will be nil.

Protected version of addition and subtraction will treat nil's as zeros
until both operands are nil - then it will return nil.
There are protected versions of comparisions, too.

It's quite simple idea, which is still very useful, and it makes code much
more readable, clean and self-commenting.

That's why I have extracted this part of SmallPOS framework, and have
published it as separate package to use it in other, non-SmallPOS
applications.

Reply via email to