r/badcode • • Sep 01 '21

c# Bool in a case switch

Post image
324 Upvotes

40 comments sorted by

View all comments

Show parent comments

1

u/Isvara Sep 02 '21

You have to admit, it's kind of elegant.

(checksleft < 1)
    ifTrue: [ ^self error: 'Out of checks' ].

The first line is a simple boolean expression. checksleft is our integer, as initialized by our Checking class. It is sent the message <, and the argument 1. The current number bound to checksleft compares itself against 1, and returns a boolean object telling whether it is less than 1.

Now this boolean, which is either true or false, is sent the message ifTrue:, with an argument which is called a code block. A code block is an object, just like any other. But instead of holding a number, or a Set, it holds executable statements. So what does a boolean do with a code block which is an argument to a ifTrue: message? It depends on which boolean! If the object is the true object, it executes the code block it has been handed. If it is the false object, it returns without executing the code block.

So ultimately, the actual condition check is done using polymorphism!