Monday, February 21, 2005

ComplexConditions

Are you sometimes irritated when you have to write conditional logic using and:/or:? I was there too, and I have two things to say.

  1. For the most part, classes and subclassing will eliminate the need for such methods,
  2. But if you cannot do that, then you should consider using ComplexConditions.

The basic idea is that when you say and:/or:, what you are really doing is connecting some pieces of code to, finally, ask something about the aggregated conditions as a whole. In other words:

    [conditionA], [conditionB], [conditionC]
      ifAllTrue: [such]
      ifAnyTrue: [such]
      otherwise: [such]

Also,

    anObject>>hasInterestingProperty

      ^[self hasKillerProperty] orAllOf:
        [self hasIrrelevantProperty],
        [self hasDisreputableProperty]

... and so on. The implementation of BlockClosure>>, is left to the reader. It can be done with an aggregate collection, or with a block.

Complicated boolean code shrinks with this arrangement. I have run into some cases where code goes from >20 lines and multiple statements down to 5 lines in one statement. The message ifAllDefined:ifAnyDefined:otherwise: is also very good at summarizing verbose nil checks.

So nice --- and the code reads so much better!

Update: look at what I found... somebody wrote something called ComplexConditions in C#! Unfortunately, it does not seem to be a port of ComplexConditions for Smalltalk.

0 comments: