Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocks vs private methods?

What are the disadvantages of using a block to define a private method within a method, instead of using a real private method? Is there any apart from not being able to call the method from somewhere else?

Example:

-(NSDictionary*)serialize
{   
    NSMutableDictionary* serialization = [NSMutableDictionary dictionary];

    TwoArgumentsBlockType serializeItemBlock = ^void(MyItemClass* item, NSString* identifier)
    {       
        if (item)
        {
            // serialization code
        }
    };

    serializeItemBlock(self.someItem1, kSomeIdentifier1);
    serializeItemBlock(self.someItem2, kSomeIdentifier2);
    serializeItemBlock(self.someItem3, kSomeIdentifier3);
    serializeItemBlock(self.someItem4, kSomeIdentifier4);
    serializeItemBlock(self.someItem5, kSomeIdentifier5);
    serializeItemBlock(self.someItem6, kSomeIdentifier6);
    serializeItemBlock(self.someItem7, kSomeIdentifier7);
    serializeItemBlock(self.someItem8, kSomeIdentifier8);
    serializeItemBlock(self.someItem9, kSomeIdentifier9);
    serializeItemBlock(self.someItem10, kSomeIdentifier10);
    serializeItemBlock(self.someItem11, kSomeIdentifier11);

    return serialization;
}
like image 681
diegoreymendez Avatar asked Jun 11 '12 18:06

diegoreymendez


3 Answers

I think the 3 biggest drawbacks are:

  1. The block isn't reusable, as you mention.
  2. The block isn't testable--you can't write a unit test that verifies the block does what you think it does.
  3. The code is less readable. When you're reading this method, what's important is that a series of things are serialized, not the details of how the serialization is implemented.

Moving this block into a method would resolve all of these issues. If the block is used by some API that takes a block callback as an argument, you can always return the block from a method.

like image 168
Christopher Pickslay Avatar answered Nov 10 '22 11:11

Christopher Pickslay


Clarity of the code is important.

Methods allow you to encapsulate entire sections of code apart from each other, and can make it easier to read..

Another reason to choose private methods over blocks is memory management. This is far to big of a topic to discuss here, but sufficed to say that blocks are weird in the memory management, and don't act like any other code structure in that regard.

like image 29
Richard J. Ross III Avatar answered Nov 10 '22 12:11

Richard J. Ross III


Arguably it's harder to navigate the code - you tend to have entry points buried rather obscurely in the middle of some function, and there's no function name you can see in the debugger or search for, which can make debugging and tracing a little harder.

like image 1
terriblememory Avatar answered Nov 10 '22 11:11

terriblememory