Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Using functional concepts within OOP

An introduction to FP worthy of the topic is way beyond the scope of this book, but we will make numerous references to the concepts described above throughout the rest of the book, and we'll look at the advantages of those concepts as we progress. That said, here is a quick summary of what FP can offer us, even though programming for macOS is primarily an object-oriented endeavor.

FP's behavior, in passing and returning values rather than accessing properties, leads to much safer code. We don't have a lot of functions accessing the same data, and this avoids many of the nasty surprises thrown up by complex state-dependent structures.

When functions are only working with their own unique copies of values, and can only change the state of a program through their returned values, they are completely thread-safe. There is no need for flags and locks, and the whole rest of the concurrent programming machinery, which leads to simpler, faster, and safer code.

For the same reasons, FP is an appropriate strategy to adopt around parallel processing. Given that we've pretty much reached many of the physical limits of shunting bits around integrated chips, it is a safe bet that parallel cores are going to continue to become an increasingly important part of development.

Functional programming tends to lead to fewer lines of code. Less code means fewer mistakes and better maintainability.

Pure functions are predictable. We can reason about the code much more easily, and because they always return the same value for a given input, we can drastically reduce the extent to which our code needs to be tested as an application increases in size and complexity. From the point of view of a pure function, the world always looks the same; it is entirely ignorant of its context.

However, we will not attempt to fit square pegs into round holes and make unnecessary work for ourselves by trying to write functionally as much as we can (see the Web for where that goes; functional evangelists write some seriously esoteric code at times). But we will help ourselves to FP concepts wherever they prove to be advantageous in an otherwise object-oriented environment.