Blocks versus private methods?

What are the disadvantages of using a block to define a private method inside a method instead of using a real private method? Is there anything other than the fact that you cannot call a method from another place?

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; } 
+6
source share
3 answers

Code clarity is important.

Methods allow you to encapsulate entire sections of code separately from each other and make reading easier.

Another reason for choosing private methods over blocks is memory management. This is a much larger topic of discussion here, but suffice it to say that the blocks are strange in memory management and do not act like any other code structure in this regard.

+1
source

I think the 3 biggest disadvantages are:

  • A block cannot be reused, as you mentioned.
  • A block is not tested - you cannot write a unit test, which checks that the block does what you think it does.
  • The code is less readable. When you read this method, it is important that the series is serialized, not the details of how serialization is implemented.

Moving this block to a method will solve all these problems. If a block is used by some API that takes a block callback as an argument, you can always return the block from the method .

+6
source

It might be harder to navigate in the code - you tend to have entry points hidden quite obscurely in the middle of some function, and there is no function name that you can see in the debugger or search, which can make debugging and tracking a little more difficult.

+1
source

Source: https://habr.com/ru/post/917819/


All Articles