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;
}
I think the 3 biggest drawbacks are:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With