If you remember the last time you had to fetch remote data, handle user input, or interact with local storage, you probably recall writing entire sections of business logic into nested sequences of callback functions. This callback pattern breaks the linear
Listing 1.5 Programming with function chains
Calling _.value() kicks off the execution of all operations in the chain.
flow of your code and becomes hard to read, because it’s cluttered with nested forms of success- and error-handling logic. This is all about to change.
As I said earlier, learning functional programming, especially for JavaScript devel-opers, is extremely important today. When building large applications, a lot of the focus has shifted from object-oriented frameworks like Backbone.js to frameworks that favor a reactive programming paradigm. Web frameworks like Angular.js are still widely used today; but new players in the field, such as RxJS, embrace the power of FP to tackle very challenging tasks.
Reactive programming is probably one of the most exciting and interesting appli-cations of functional programming. You can use it to dramatically reduce the com-plexity in asynchronous and event-driven code that you, as JavaScript developers, deal with on a daily basis on the client as well as the server.
The main benefit of adopting a reactive paradigm is that it raises the level of abstraction of your code, allowing you to focus on specific business logic while forget-ting about the arduous boilerplate code associated with setforget-ting up asynchronous and event-based programs. Also, this emerging paradigm takes full advantage of FP’s abil-ity to chain or compose functions together.
Events come in many flavors: mouse clicks, text field changes, focus changes, han-dling new HTTP requests, database queries, file writes, and so on. Suppose you need to read and validate a student’s SSN. A typical imperative approach might look like the next listing. val = val.replace(/^\s*|\s*$|\-s/g, '');
if(val.length === 9) { desired level of modularity with all business logic in a single place. Also, this function isn’t reusable due to its dependency on external state. Because reactive programming is based on functional programming, it benefits from the use of pure functions to pro-cess data with the same familiar operations like map and reduce and the terseness of lambda expressions. So learning functional is half the battle when learning reactive!
Listing 1.6 Imperative program that reads and validates a student’s SSN
Side effects
This paradigm is enabled through a very important artifact called an observable. Observ-ables let you subscribe to a stream of data that you can process by composing and chaining operations together elegantly. Let’s see it in action and subscribe to a simple input field for a student’s SSN.
Rx.Observable.fromEvent(document.querySelector('#student-ssn'), 'keyup') .map(input => input.srcElement.value)
.filter(ssn => ssn !== null && ssn.length !== 0) .map(ssn => ssn.replace(/^\s*|\s*$|\-/g, '')) .skipWhile(ssn => ssn.length !== 9)
.subscribe(
validSsn => console.log(`Valid SSN ${validSsn}`) );
Can you see the similarity between listing 1.7 and programming with chains in list-ing 1.5? This shows that whether you’re processlist-ing a collection of elements or user input, it’s all abstracted out and treated in the exact same manner. I have much more to say about this in chapter 8.
One of the most important takeaways is that all the operations performed in list-ing 1.7 are completely immutable, and all the business logic is segregated into individ-ual functions. You don’t have to use functional with reactive, but thinking functionally forces you to do so—and when you do, you unlock a truly amazing architecture based on functional reactive programming (FRP).
Functional programming is a paradigm shift that can dramatically transform the way you tackle solutions to any programming challenges. So is FP a replacement for the more popular object-oriented design? Fortunately, applying functional program-ming to your code isn’t an all-or-nothing approach, as noted in the Michael Feathers quote at the beginning of this chapter. In fact, lots of applications can benefit from using FP alongside an object-oriented architecture. Due to rigid control for immuta-bility and shared state, FP is also known for making multithreaded programming more straightforward. Because JavaScript is a single-threaded platform, this isn’t something we need to worry about or cover in this book. In the next chapter, I spend some time highlighting some of the key differences between functional and object-oriented design, which I believe will help you grok the functional way of thinking more easily.
In this chapter, I briefly touched on topics that will be covered in depth through-out the book as you sink deeper into a functional frame of mind. If you’ve been fol-lowing all the concepts so far, that’s great, but don’t worry if you missed a few things—
that just means you’ve picked up the right book. In traditional OOP, you’re accus-tomed to programming in the imperative/procedural style; changing this will require you to make a drastic shift in your thought processes as you begin to tackle problems the “functional way.”
Listing 1.7 Functional program that reads and validates a student’s SSN
1.4 Summary
■ Code that uses pure functions has zero chance of changing or breaking global state, which helps make your code more testable and maintainable.
■ Functional programming is done in a declarative style that’s easy to reason about. This improves the overall readability of the application and makes your code leaner through a combination of functions and lambda expressions.
■ Data processing in a collection of elements is done fluently via function chains that link operations such as map and reduce.
■ Functional programming treats functions as building blocks by relying on first-class, higher-order functions to improve the modularity and reusability of your code.
■ You can reduce the complexity of event-based programs by combining func-tional with reactive programming.
23