Showing posts with label blocks. Show all posts
Showing posts with label blocks. Show all posts

Monday, 2 November 2015

Blocks and how to apply them to composition of a variety of GUI buttons

To define a single button class and have several buttons
Each button has its own text, and it must also alert the owner for a change of state
Done by inheritance, it would get complicated

So:
Button new text: 'some text'; action: [ do something ]

The button may act as a switch or single action.  If it's a switch it will have to alert the owner to disable the other options

For those are just instance-specific actions, you don't need several button classes.

Instead:
switchButton := Button new action: [ self owner switch ].
anotherButton := Button new action: [ self owner whatever ].

[ 1 + 1 ] 
results in the block
[ 1 + 1 ]

To execute a block we pass it the getter message value  When evaluated, a block will by default return the value of the last expression it evaluates.

[ 1 + 1 ] value 
results in 2

To pass a block parameters, we use the setter message value:value:value:
[ :a :b | a + b ] value: 1 value: 2
results in 3

Friday, 30 October 2015

Blocks - OO Computing with Smalltalk Ch 23.4

A Block object is created by enclosing any expression, or expression series, in square brackets.

The block can be thought of being just like a method, but without a name.

Blocks can be assigned to variables.

A block can have arguments, just like a method, and they get called block arguments.

They are declared inside the block, at the start, with a preceding colon, and a | at the end of the list of block arguments.

e.g.

    aBlock := [ :blockArgument1 :blockArgument2 | "and the meat of the block goes here." ]  

To evaluate a block with a single block argument, you send it the message value:
To evaluate a block with two block arguments, you send it the message value:value:
To evaluate a block with three block arguments, you send it the message value:value:value:

To evaluate a block with more than three arguments, you send it the message valueWithArguments: with the arguments in an array as the message argument.

Blocks can have temporary variables, declared between | | immediately after the block arguments are declared.

Methods return either self or the explicit ^ return,

Blocks return either the result of evaluating the last expression in the block, or the first explicit ^ return they encounter.



 

e.g. t