In this session, I'd like you to focus
on the use of parentheses and brackets.
Don't mix them up.
Parentheses change the priority of an execution
in expressions or in code,
while brackets define blocks.
When the expressions in a block are defined, they are not executed.
You control the execution: you must send the message value to the block
to trigger the execution of its expressions.
Let's talk again about when you must use brackets.
You use them around expressions
if you don't know whether they will be executed:
for instance, do they use if? Do they belong to the branch of a deviation?
You also use brackets
if you don't know how many times you must execute
the expressions a block contains.
For instance: n timesRepeat: [self doSomething]
self doSomething is encapsulated in a block.
Why? Because you must execute its expressions several times.
You must put them in a block to send it the message value several times.
Another example: this time, I send the message ifTrue:.
Depending on the receiver,
depending on whether this expression is true or false,
you execute or don't execute the expression self doSomething.
I can't use parentheses since if needed, it won't be executed at all.
If you put it in a block,
you can decide whether you send it the message value.
This is the same thing but with whileTrue:.
It's the same with the receiver block and the block passed as a parameter.
Depending on whether the evaluation returns the Boolean true or false,
you must execute once, several times, or even not at all
the expression self doSomething: it must be put in a block.
Let's do a small exercise.
If I give you the two following expressions,
repeat from 1 to: n self doSomething,
should I use parentheses or brackets?
If I write x ifEmpty: self doSomething,
should I use parentheses or brackets?
I'll give you the answers.
In both cases, you should use brackets.
In the first case, if you want to repeat self doSomething,
you have to send the message value to this block several times.
In the second case, x ifEmpty:,
if x isn't empty, you shouldn't execute self doSomething.
If x is empty, you have to.
To sum up, we saw in this course
that you shouldn't mix up parentheses and brackets.
Parentheses are about changing the order of computation in an expression.
Brackets are about freezing
expressions
and to control their execution or even to execute them several times.