When to Use Blocks

When to use blocks

The whole thing would be more readable as:


if something.do_stuff
#successful code
else
#unsuccessful code
end

or to use a common rails idiom:


if @user.save
render :action=>:show
else
@user.errors.each{|attr,msg| logger.info "#{attr} - #{msg}" }
render :action=>:edit
end

IMHO, avoiding the return of a boolean value is overuse of code blocks.

A block makes sense if . . .

It allows code to use a resource without having to close that resource


open("fname") do |f|
# do stuff with the file
end #don't have to worry about closing the file

The calling code would have to do non-trivial computation with the result

In this case, you avoid adding the return value to calling scope. This also often makes sense with multiple return values.


something.do_stuff do |res1, res2|
if res1.foo? and res2.bar?
foo(res1)
elsif res2.bar?
bar(res2)
end
end #didn't add res1/res2 to the calling scope

Code must be called both before and after the yield

You see this in some of the rails helpers:


<% content_tag :div do %>
<%= content_tag :span "span content" %>
<% end -%>

And of course iterators are a great use case, as they're (considered by ruby-ists to be) prettier than for loops or list comprehensions.

Certainly not an exhaustive list, but I recommend that you don't just use blocks because you can.

When should I use using blocks in C#?

When the SomeType class implements IDisposable.

What is the C# Using block and why should I use it?

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}

using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}

The second is easier to read and maintain.


Since C# 8 there is a new syntax for using that may make for more readable code:

using var x = new SomeDisposableType();

It doesn't have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:

string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}

And have this:

using var someReader = ...;
string x = someReader.Read();

What is the purpose of using blocks

Blocks are closures (or lambda functions, however you like to call them). Their purpose is that using blocks, the programmer doesn't have to create named functions in the global scope or provide a target-action callback, instead he/she can create an unnamed, local "function" which can access the variables in its enclosing scope and easily perform actions.

For example, when you want to e. g. dispatch an asynchronous operation, such an animation for views, without blocks, and you wanted to be notified of the competion, you had to write:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
.... set up animation ....
[UIView commitAnimations];

This is a lot of code, furthermore it implies the presence of a valid self pointer - that might not always be available (I experience such a thing when I was developing MobileSubstrate-tweaks). So, instead of this, you can use blocks from iOS 4.0 and onwards:

[UIView animateWithDuration:1.0 animations:^{
// set up animation
} completion:^{
// this will be executed on completion
}];

Or, for example, loading online resources with NSURLConnection... B. b. (Before Blocks):

urlConnection.delegate = self;

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)rsp
{
// ...
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// ...
}

// and so on, there are 4 or 5 delegate methods...

A. B. (Anno Blocks):

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *d, NSError *e) {
// process request here
}];

Much easier, cleaner and shorter.

Why we use blocks in objective C instead of functions?

Blocks, sometimes called anonymous functions, are really nothing more than functions with state. Sometimes that state is what makes them particularly useful, and sometimes we use them solely for convenience of syntax and conciseness of code.

When a block captures state, it's called a closure. This means that variables defined outside of the block's scope, but used within the block, are captured at the point the block is defined. That is, when the code which defines the block is executed at runtime. This means that each execution of the block can (and often will) capture different values for the same variables.

When to use __block keyword on object references with ARC

__block is needed for scalar variables if you want to change their value with code inside the block. Captured scalars appear as const inside the block and therefore cannot be changed. If you have a pointer to an object, the same distinction applies--the captured pointer itself will be a const pointer and therefore cannot be modified, but the object pointed to can be modified by code inside the block. If you want to change the object pointed to, then the pointer itself must change, and so the pointer must be declared with the __block type. It is never necessary to declare the object itself as __block, but only the pointer to the object, and only if the pointer must be changed.

If you have the right mental model, blocks aren't that confusing. It is important to know that blocks are initially allocated on the stack, and so vanish when the lexical scope is destroyed as the stack frame is popped. If you want the block to hang around past the lifetime of the lexical scope in which the block was created, move it to the heap using Block_copy() or sending it a -copy message. When a block is copied to the heap, all the captured const variables go along, and any objects these const variables point to are retained. When the block is removed from the heap, all objects pointed to by the const variables are released.

__block variables "under the hood" have an extra layer of indirection the compiler uses (and that you don't see) included in the block, so when the block is copied to the heap, so are the captured __block variables, and the invisible pointers are adjusted to point to the new heap location of these __block variables. This means the address of a __block variable can change, so be careful if you use that address. You can also see that a __block variable lives 'outside' the block in some sense, so these variables can be read and modified from code external to the block.

I've been brief, but you can find better explanations here, listed in increasing complexity:

http://ios-blog.co.uk/tutorials/programming-with-blocks-an-overview/

http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html

http://www.mikeash.com/pyblog/friday-qa-2011-06-03-objective-c-blocks-vs-c0x-lambdas-fight.html

When should I use code blocks or brackets in Javascript?

This code does indeed work:

function printFarmInventory(cows, chickens) {
var cowString = String(cows);
while (cowString.length < 3) {
cowString = "0" + cowString;
}
console.log(cowString + " Cows")
var chickensString = String(chickens);
while (chickensString.length < 3) {
chickensString = "0" + chickensString
}
console.log(chickensString + " Chickens")
}


Related Topics



Leave a reply



Submit