Jun 97 - Tips
Volume Number: 13 (1997)
Issue Number: 6
Column Tag: Tips & Tidbits
Jun 97 - Tips & Tidbits
by Steve Sisak
Prettyprinting Complex Expressions
The main problem with trying to read a complex expression in a program is trying to discern its structure. When you are writing such an expression, think of it as a tree, with the operators located where the branches join, and the operands attached to them. If you arrange your code to reflect something of this tree structure in two dimensions, the result becomes much easier to understand.
Let's start with a simple example. Compare
IF (NewState > OfState^.NrStates) OR (NewState = 0) AND
(OfState^.NrStates > 1) THEN
with
IF
(NewState > OfState^.NrStates)
OR
(NewState = 0) AND (OfState^.NrStates > 1)
THEN
Note that the AND-expression and its subexpressions were not broken out onto separate lines, because they are simple enough that their clarity would not be helped by this.
See how gracefully this technique copes with increasing numbers of subexpressions:
RETURN
(ThePoint.x >= TheRect.left)
AND
(ThePoint.x < TheRect.right)
AND
(ThePoint.y >= TheRect.top)
AND
(ThePoint.y < TheRect.bottom)
Imagine what a mess this would look like all run together:
IF
NOT EqualFixedRect
(
OldEntry^.DeviceIntersect,
NewEntry.DeviceIntersect
)
OR
NOT BlockEqual
(
(*Src1 :=*) ADR(OldEntry^.DeviceMapping),
(*Src2 :=*) ADR(NewEntry.DeviceMapping),
(*Count :=*) SIZE(gxMapping)
)
OR
(
OldEntry^.DeviceBitmap.width
<>
NewEntry.DeviceBitmap.width
)
OR
(
OldEntry^.DeviceBitmap.height
<>
NewEntry.DeviceBitmap.height
)
OR
NOT EqualColorSet
(
OldEntry^.DeviceBitmap.set,
NewEntry.DeviceBitmap.set
)
OR
NOT EqualColorProfile
(
OldEntry^.DeviceBitmap.profile,
NewEntry.DeviceBitmap.profile
)
THEN
or this one:
IF
(
ThisDevice^^.gdPMap^^.pixelSize
=
OtherDevice^^.gdPMap^^.pixelSize
)
AND
(
(QuickDraw.gdDevType IN ThisDevice^^.gdFlags)
=
(QuickDraw.gdDevType IN OtherDevice^^.gdFlags)
)
AND
(
(
QuickDraw.dontMatchSeeds
IN
flags
)
OR
(
ThisDevice^^.gdPMap^^.pmTable^^.ctSeed
=
OtherDevice^^.gdPMap^^.pmTable^^.ctSeed
)
)
THEN
Such an arrangement also makes it easier to attach comments explaining what the subexpressions are for:
IF
(Windows.FrontWindow() = NIL)
(* no other windows active *)
AND
(LastPalette() <> Windows.WindowInFront)
(* I have palettes *)
THEN
By the way, these are not made-up examples, they are all from actual working code. This isn't about exercises for kiddies in classrooms. It's about real-world programming!
Lawrence D'Oliveiro
LDO@waikato.ac.nz