|
Revision 2335, 0.9 KB
(checked in by Chuck.Esterbrook, 2 years ago)
|
|
Improvements to the How-To's.
|
-
Property svn:eol-style set to
native
|
| Line | |
|---|
| 1 | """ |
|---|
| 2 | MakeAnIfElseLadder.cobra |
|---|
| 3 | |
|---|
| 4 | Consider possible alternatives to an if-else ladder: |
|---|
| 5 | |
|---|
| 6 | * Make a class hierarchy and send a message to the object. |
|---|
| 7 | |
|---|
| 8 | * Use the `branch` statement (see MakeABranchStatement.cobra) |
|---|
| 9 | |
|---|
| 10 | When using an if-else ladder, consider throwing a FallThroughException() at the |
|---|
| 11 | bottom if you expect that it should never happen. |
|---|
| 12 | |
|---|
| 13 | |
|---|
| 14 | See also: MakeABranchStatement.cobra, CheckInheritanceAndImplementation.cobra. |
|---|
| 15 | """ |
|---|
| 16 | |
|---|
| 17 | |
|---|
| 18 | class Program |
|---|
| 19 | |
|---|
| 20 | def main |
|---|
| 21 | t = Thing() |
|---|
| 22 | if t.isSmall |
|---|
| 23 | print 'small' |
|---|
| 24 | else if t.isMedium |
|---|
| 25 | print 'medium' |
|---|
| 26 | else if t.isLarge |
|---|
| 27 | print 'large' |
|---|
| 28 | else |
|---|
| 29 | throw FallThroughException(t) |
|---|
| 30 | # ^ As seen here, you can (optionally) include a value with the |
|---|
| 31 | # fall-through exception which is the value that was being examined. |
|---|
| 32 | |
|---|
| 33 | |
|---|
| 34 | class Thing |
|---|
| 35 | """ |
|---|
| 36 | A thing is always small, medium or large, and never more than one. |
|---|
| 37 | """ |
|---|
| 38 | |
|---|
| 39 | get isSmall as bool |
|---|
| 40 | return false |
|---|
| 41 | |
|---|
| 42 | get isMedium as bool |
|---|
| 43 | return true |
|---|
| 44 | |
|---|
| 45 | get isLarge as bool |
|---|
| 46 | return false |
|---|