The rise of functional programming & the decline of Angular 2.0

Datetime:2016-08-23 05:12:34          Topic: AngularJS  Functional Program           Share

Learn why we believe that the rise of functional programming (FP) will prevent Angular 2.0 from being as successful as its predecessor.

Angular 2.0 RC.5 was just released last week and is now really close the long-awaited 2.0 release.

After the success of Angular 1.0, it is normal to expect a huge success for Angular 2.0. However, we feel that there are reasons to believe that Angular 2.0 will not be as successful as its predecessor.

We believe this because we have been observing the front-end development trends and we have noticed a significant shift within the JavaScript community .

Let’s learn what this “shift” is about.

A little bit of history

JavaScript is a multi-paradigm programming language. On its early days, it was mostly used as a scripting programming language. As the complexity of front-end application increased, the JavaScript community shifted towards a more object-oriented (prototype-based) style .

We can take a look to the API of many of the early single-page application (SPA) frameworks like Backbone.js to observe that they were heavily based on inheritance:

var Note = Backbone.Model.extend({

  initialize: function() { ... },

  author: function() { ... },

  coordinates: function() { ... },

  allowedToEdit: function(account) {
    return true;
  }

});

At the time ES6 wasn’t around and many developers demanded a class-based object-oriented API. After some time the class-based API became a reality:

JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance. MDN

However, when the class-based API arrived it was already too late and many influential developers didn’t want it anymore:

Why? What happened between the arrival of the first SPA frameworks and the arrival of ES6?

The answer is simple: the JavaScript community is shifting towards a more functional programming style .

The rise of functional programming

Functional programming has its roots in lambda calculus, a formal system developed in the 1930s.

FP is a “scary topic” because languages (especially purely functional ones) have largely been emphasised in academia rather than in commercial software development. However this is changing. JavaScript is a very accessible programming language and, as a result, FP in JavaScript is much more accessible than learning Haskell .

Many developers with a background on FP languages have started to work on SPA frameworks and today we can enjoy libraries like React, Redux, Cycle.js, MobX, Ramda, RxJS or Immutable.js in our JavaScript applications. Some of these libraries have a more FP style API than others but they all share one thing: they try avoid OOP style on their APIs .

When we say “OOP style” we are referring to:

  • Inheritance over composition
  • Internal class state
  • Imperative state mutations

Some elements of the React API use OOP elements. For example, we can extend the React.Component class:

import React from 'react';

class Contacts extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div></div>
    );
  }
}

export default Contacts;

But the React community is aware of the benefits of FP and new elements with a strong FP influence have been introduced into its API. For example, React .14 introduced a simpler way to define components called stateless functional components which introduced many benefits over its OOP alternative .

Many developers with an OOP background have been using libraries like React and Redux and slowly have been starting to understand the core FP principles. This is leading them to be eager to learn more about FP in JavaScript.

As developers learn more about FP we can observe the emergence of many libraries with a strong FP style like Cycle.js or Ramda and we believe that the shifting of the JavaScript community towards FP has just started .

How can the rise of FP influence the success of Angular 2.0?

We believe that the Angular 2,0 API is highly influenced by OOP ideas and goes against the shifting of the JavaScript community towards FP that we have been explaining in this article.

Angular 2.0 is being advertised as a framework that gives you everything. However, some developers are using Angular 2.0 with Redux because after experiencing the benefits of FP in React they just simply don’t want to deal with an API with a strong OOP style. They like more the idea of triggering actions (pure functions) that will invoke a reducer (pure function) in Redux than invoking a method in a Service class in Angular 2.0:

// SOURCE: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';

@Injectable()
export class HeroService {
  private heroesUrl = 'app/heroes';  // URL to web api
  constructor(private http: Http) { }
  getHeroes() {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }
  getHero(id: number) {
    return this.getHeroes()
               .then(heroes => heroes.find(hero => hero.id === id));
  }
  save(hero: Hero): Promise<Hero>  {
    if (hero.id) {
      return this.put(hero);
    }
    return this.post(hero);
  }
  delete(hero: Hero) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let url = `${this.heroesUrl}/${hero.id}`;
    return this.http
               .delete(url, {headers: headers})
               .toPromise()
               .catch(this.handleError);
  }
  // Add new Hero
  private post(hero: Hero): Promise<Hero> {
    let headers = new Headers({
      'Content-Type': 'application/json'});
    return this.http
               .post(this.heroesUrl, JSON.stringify(hero), {headers: headers})
               .toPromise()
               .then(res => res.json().data)
               .catch(this.handleError);
  }
  // Update existing Hero
  private put(hero: Hero) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let url = `${this.heroesUrl}/${hero.id}`;
    return this.http
               .put(url, JSON.stringify(hero), {headers: headers})
               .toPromise()
               .then(() => hero)
               .catch(this.handleError);
  }
  private handleError(error: any) {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}

We can use the Angular 2.0 components (even though they are not stateless functional components) together with some other libraries (like Redux or RxJS) to make Angular 2.0 feel “more functional”.

Why we need such a powerful framework then? Would it not be better to simply use a very light weight component library with Redux? This is something that is even happening to React components .

We believe that the “sweet spot” is somewhere between OOP and FP, maybe somewhere a bit closer to FP than OOP.

We believe that the Angular 2,0 API is highly influenced by OOP ideas and goes against the shifting of the JavaScript community towards FP that we have been explaining in this article.

As more and more people learn about functional programming techniques and try frameworks and libraries like React, Cycle.js, Redux, MobX, RxJS or Ramda they will be more likely to try to avoid classes and inheritance as much as they can. This reason leads us to we believe that the rise of FP within the JavaScript community will prevent Angular 2.0 from being as successful as its predecessor.

If you want to learn more about functional programming in JavaScript, a good way to get started is to use React with Redux and read some books:

Then you can introduce immutable.js and RxJS into your React applications and finally give a try to Cycle.js and Ramda.

Please feel free to share thoughts about this article with us via @OweR_ReLoaDeD and @WolkSoftwareLtd .

Don’t forget to subscribe if you don’t want to miss it out future articles!

6

Kudos

6

Kudos





About List