Chapter 16: Think Different: Blocks and Functional Programming
Programming paradigms fall into three major categories: procedural programming, object-oriented programming, and functional programming. Most modern programming languages—such as Java, C#, or Objective-C—don’t fall purely into a specific paradigm. They are usually inclined to one while including some methodologies from the others. Objective-C is primarily object-oriented, yet it borrows some functional aspects using blocks. This chapter is about the functional programming aspects in Objective-C.
The functional programming (FP) paradigm is easy to explain theoretically, but its highly abstract nature makes it hard to understand and realize its power. The easiest way to really comprehend and appreciate FP is to implement a practical system. Later in this chapter, you dirty your hands with a dash of FP by writing an FP equivalent of a commonly used Cocoa method, and then go deeper by refactoring the RESTEngine you wrote in Chapter 10 to use blocks. Finally, you learn about some of the block-based methods added to the Cocoa framework from iOS 4 onward. Now let’s get started.
What Is a Block?
Simply defined, a block is an ad hoc piece of code. Just as you would with a primitive data type like an integer or double, you declare a block and start using it. You can pass blocks as parameters, “copy” them for use later, and do pretty much anything that you would normally do to a primitive data type. Veteran C programmers have ...