Category: Other

  • Cold Dive into React Native: A Beginner’s Tutorial

    When React Native was announced, the first reactions were overwhelmingly positive. Traditionally, when we think about web technologies in the mobile space, things like Apache Cordova spring to mind which allow us to package web sites or web applications as applications for mobile platforms. In this tutorial, we will take a look at React Native’s architecture, the philosophy behind React Native, and how it differs from other solutions in the same space. By the end of the article, we will have transformed a React “Hello World” application into a React Native one.

    Let us start by saying that React Native is a relatively new technology. It has been officially available since March 2015, been in private beta since the start of the year, and internally used at Facebook for a while before that. The saying “Rome wasn’t built in a day” generally applies to technology as well. Tools like “grunt” and platforms like “node” took years to mature. In the web world things are moving quickly, and with a huge number of frameworks, packages, and tools coming out every day, developers tend to get a little more sceptical and don’t want to jump on every hype bandwagon only to realize that they ended up in a vendor lock-in situation. We will get into what makes React Native special, why it is a technology worth getting into, and cover a few instances where it’s not all unicorns and rainbows.

    Under the Hood

    When talking about web technologies on mobile, available solutions usually fall in one of the following categories.

    Bundling Web Applications in a Mobile Web Browser

    The web application lives in a mobile browser, typically called a WebView. Without any major refactoring, a web site or web application works on the mobile device. We may need to consider mobile browser events such as tapping or listening to device orientation changes and the smaller screen for a complete user experience, but we have a working mobile version with minimal effort. Cordova/PhoneGap is the most popular option in this category. Unfortunately this option has a big downside: in some cases, applications developed using Cordova are significantly slower than native applications, especially for graphical-heavy applications. In other cases, the mobile operating system doesn’t actually provide all the features in the WebView that are available in the mobile browser. The user experience can also differ from native applications, this may happen due to the application or the platform itself. This problem may range from scrollbars not feeling the same to having a noticeable delay when tapping on elements.

    Compiling to Native Technologies

    A completely different solution is to create a native codebase in the end. This happens by transforming the original source code into another programming language. We trade in native performance for an abstraction layer with some uncertainties. In cases of closed-source solutions, we are not even sure what happens under the hood and with what kind of black box we are dealing with. In other cases we are not sure how much the next mobile operating system update will break our code and when fixes or updates will be available. A popular example of this category would be HaXe.

    Using a JavaScript Layer

    Here we use JavaScript engine of the mobile environment and execute our JavaScript there. Native controls are mapped to JavaScript objects and functions, so when we were to call a function called “fancyButtonRightHere()”, a button would appear on the screen. NativeScript or Appcelerator Titanium are well-known examples of this category.

    React Native could be classified as something from the third category. For the iOS version, React Native uses “JavaScriptCore” under the hood which is the default JavaScript engine on iOS. “JavaScriptCore” is also the JavaScript engine in Apple’s Safari browsers. OS X and iOS developers can actually directly interface with it if they want to.

    One big difference is that React Native runs the JavaScript code in a separate thread, so the user interface does not block and animations should be silky and smooth.

    React is the Key Feature

    It is worth noting that React in React Native is not put there by accident. For React Native, we need an understanding of what exactly React offers. The following concepts work the same in both React and React Native, although these code examples are tailored to be run in the browser.

    Single Rendering Entry Point

    When we take a look at a simple React component, the first thing we may notice is that the component has a “render” function. In fact, React throws an error if there is no render function defined inside the component.

    var MyComponent = function() {
      this.render = function() {
        // Render something here
      };
    };
    

    The special thing is that we don’t mess with DOM elements here, but we return a XML-based construct that represents what will be rendered in the DOM. This XML-based construct is called JSX.

    var MyComponent = function() {
      this.render = function() {
        return <div className="my-component">Hello there</div>;
      };
    };
    

    A special JSX transformer takes all of that XML-looking code and converts it into functions. This is what the component after the transformation will look like:

    var MyComponent = function() {
      this.render = function() {
         return React.createElement("div", {
           className: "my-component"
         }, "Hello there");
      };
    };
    

    The biggest advantage is that by taking a quick look at the component, we always know what it’s supposed to do. For example a “<FriendList />” component might render a number of “<Friend />” components. We can’t render our components anywhere else than inside of the “render” function, so there is never the concern that we don’t know where exactly our rendered component came from.

    Unidirectional Data Flow

    To build the content of a component, React provides properties or props for short. Similar to XML attributes, we pass in the props directly to a component and can then use the props inside the constructed component.

    var Hello = function(props) {
      this.render = function() {
        return <div className="my-component">Hello {props.name}</div>;
      };
    };
    var Greeter = function() {
      this.render = function() {
        return <Hello name="there" />
      }
    };
    

    This leads to our components being in a tree-like structure and we are only allowed to pass data when constructing child elements.

    Re-Render on Changes

    In addition to props, components can also have an internal state. The most prominent example of that behavior would be a click counter that updates its value when a button is pressed. The number of clicks itself would be saved in the state.
    Each of the prop and state change triggers a complete re-render of the component.

    Virtual DOM

    Now when everything is re-rendered when the props or state changes, how come React itself is performing that well? The magic ingredient is “Virtual DOM”. Whenever something is needed to be re-rendered, a virtual representation of the updated DOM is generated. The Virtual DOM consists of light representations of elements modeled after the component tree, making the process of generating them much more efficient than generating real DOM elements. Before applying the changes to the real DOM, checks are done to determine where exactly in the component tree the changes happened, a diff is created, and only those specific changes are applied.

    Getting Started with this React Native Tutorial

    There are certain prerequisites that are needed in order to develop for React Native. Since iOS is currently the only supported platform, we need Mac OS X and Xcode, at least version 6.3. io.js – a Node.js compatible platform – is needed. What helps is installing watchman through the brew package manager with brew install watchman. While this is not necessarily needed, it helps when dealing with a lot of files inside our React Native project.

    React Native: The Sanest Mobile Application Development Framework.

    To install React Native, we simply need to install the React Native command-line application with npm install -g react-native-cli. Calling the react-native command then helps us creat a new React Native application. Running react-native init HelloWorld creates a folder called “HelloWorld” in which the boilerplate code can be found.

    Transforming a React Application

    With React being the key feature and the core principles coming from the React library, let’s take a look at what we need to transform a minimal React “Hello World” application into a React Native one.

    We use some ES2015 features in this code example, specifically classes. It is completely feasible to stick with “React.createClass” or use a function form similar to the popular module pattern.

    var React = require('react');
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <div className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</div>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Step 1: Embrace CommonJS Modules

    In the first step we need to change requiring the React module to use “react-native” instead.

    var React = require('react-native');
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <div className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</div>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    What is usually a part of the tooling pipeline when developing a React web application is an integral part of React Native.

    Step 2: There is no DOM

    Not surprisingly, there is no DOM on mobile. Where we previously used “<div />” we need to use “<View />” and where we used “<span />” the component we need here is “<Text />”.

    var React = require('react-native');
    var {View} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</View>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    While it’s quite convenient to put text directly in “<div />” elements, in the native world text can’t be put directly in a “<View />”. For that we need to insert a “<Text />” component.

    var React = require('react-native');
    var {View, Text} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View className="box" onClick={this.clickMe.bind(this)}>
            <Text>Hello {this.props.name}. Please click me.</Text>
          </View>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Step 3: Inline Styles Are the Way to Go

    React Native allows us to use the Flexbox modeling instead of messing around with “float” and “inline-block” that we are so familiar with in the web world. The interesting thing is that React Native does not use CSS.

    var React = require('react-native');
    var {View, Text, StyleSheet} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View style={styles.box} onClick={this.clickMe.bind(this)}>
            <Text>Hello {this.props.name}. Please click me.</Text>
          </View>
        );
      }
    }
    var styles = StyleSheet.create({
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Using inline styles seems bewildering at first. It is similar to the transition React developers had to go through when being confronted with JSX and previously using templating engines like Handlebars or Jade.
    The idea is that we don’t have stylesheets globally in the way we use CSS. We declare the stylesheets directly at component level, and so we have all the information we need to see what our component does, the layout it creates, and the styles it applies.

    var React = require('react-native');
    var {Text} = React;
    var Headline = function(props) {
      this.render = () => <Text style={headlineStyle.text}>{props.caption}</Text>;
    };
    var headlineStyles = StyleSheet.create({
      text: {
        fontSize: 32,
        fontWeight: 'bold'
      }
    });
    module.exports = Headline;
    

    Step 4: Handling Events

    The equivalent to clicking in web pages is tapping an element on the mobile device. Let’s change our code so that the “alert” pops up when we tap the element.

    var React = require('react-native');
    var {View, Text, StyleSheet, TouchableOpacity} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <TouchableOpacity onPress={this.clickMe.bind(this)}>
            <View style={styles.box}>
              <Text>Hello {this.props.name}. Please click me.</Text>
            </View>
          </TouchableOpacity>
        );
      }
    }
    var styles = StyleSheet.create({
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Instead of events being directly available on “<View />” components, we need to explicitly use elements that trigger events, in our case a touch event when pressing the view. There are different types of touchable components available, each of them providing a different visual feedback.

    Step 5: Registering the Application

    When developing with React for the browser, we just need to define a mount point, call “React.render”, and let React do its magic. In React Native, this is a little bit different.

    var React = require('react-native');
    var {View, Text, StyleSheet, TouchableOpacity, AppRegistry} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View style={styles.container}>
            <TouchableOpacity onPress={this.clickMe.bind(this)}>
              <View style={styles.box}>
                <Text>Hello {this.props.name}. Please click me.</Text>
              </View>
            </TouchableOpacity>
          </View>
        );
      }
    }
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    var MainComponent = function() {
      this.render = function() {
        return <HelloThere name="Component" />;
      }
    };
    AppRegistry.registerComponent('MainComponent', function() {
      return MainComponent;
    });
    

    We have to register the component for the Objective-C side of things which is done using the “AppRegistry” object. The name we give has to match with the name inside the Xcode project.

    Our Hello World React Native application has significantly more lines of code than its web counterpart, but on the other side React Native takes separation of concern a bit further especially because styles are defined with the component.

    As a side note, we shouldn’t rebind the “clickMe” method to the “this” context in the “render” method, especially if our React (Native) application grows to be a bit more complex. It rebinds the method on every render call which can become quite a lot. The alternative is to bind the method inside the constructor.

    Running the Application

    To run the application, we need to replace the contents of the “index.ios.js” file with the piece of code of our transformed application from the last step. Then we just need to open the Xcode project and press the big Run button. First a terminal will open with the React Native server, and then the simulator window will appear. The React Native server creates a bundle, which the native application will then fetch. This allows for a web development-like rapid development cycle, where changes will be reflected almost instantly in the simulator. After the terminal has popped up, our application will then show up in the simulator. Pressing CMD+D will show a development menu.

    Clicking on the box will then show an alert:

    For distribution, having an application that points to a local development server would not be working out for us. For this reason, we can create the bundle for usage when the React Native server isn’t running with the command react-native bundle. In that case we need to update the “didFinishLaunchingWithOptions” method of “AppDelegate” to use the offline bundle.
    This example application is also available on Github.

    Working with React Native

    Another thing worth mentioning is that we not only use React concepts and JavaScript for our mobile applications, but some of workflows web developers are used to are also available with React Native. When coming from web development, we are used to developer tools, inspecting elements, and live reloading.
    The way React Native works is that it puts all of our JavaScript files in a bundle. This bundle is either served from a server or bundled together with the application. The first is incredibly useful for development in the Simulator, as we can enable live reloading. The developer menu React provides is by no means as mighty as the Chrome Developer Tools, but it provides a very web-like developer experience with live reloading and debugging with the Chrome (or Safari) developer tools.

    Web developers are familiar with JSFiddle or JSBin, an online playground for quick web tests. There is a similar environment, RNPlay, which allows us to try out React Native in a web browser and see the result from a simulator streamed in the web browser.

    Can I Use React Native?

    In its current state, a few things are still in fluctuation and not up to the expectation you might have from using other frameworks. These are mainly advanced gesture recognition.

    You might want to refrain from completely rewriting your mobile applications in React Native just yet. In React, one of the big advantages is that React does not impose on what workflow you want to use, as it just represents the view layer. Do you want to define your own Grunt pipeline? Or would you rather use Webpack? And will you use Backbone.js for your model needs? Or do you want go with plain JavaScript objects? Answers to all of these questions are totally up to you, because React does not put any restriction on these choices. One recommendation for React from the official website is: “since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.”

    To a certain degree, this is true for React Native as well. Mobile developers can integrate React Native as a part of their application, take advantage of the web-inspired development workflow, and choose to integrate the library on a larger scale if needs be.

    React Native is not a cross-platform development framework by any means, the philosophy behind it is “Learn once, write anywhere”. While you might end up sharing some code across platforms, but there will always be code you may need to re-implement depending on the platform you are targeting.

    However, one thing is certain: React Native isn’t going away. Facebook has a massive stake in it having multiple React Native powered applications in app stores. The community around React Native is growing, and with each new release there are more contributors, issues, and pull requests.

  • Concurrency and Fault Tolerance Made Easy: An Akka Tutorial with Examples

    The challenge

    Writing concurrent programs is hard. Having to deal with threads, locks, race conditions, and so on is highly error-prone and can lead to code that is difficult to read, test, and maintain.
    Many therefore prefer to avoid multithreading altogether. Instead, they employ single-threaded processes exclusively, relying on external services (such as databases, queues, etc.) to handle any needed concurrent or asynchronous operations. While this approach is in some cases a legitimate alternative, there are many scenarios in which it is simply not a viable option. Many real-time systems – such as trading or banking applications, or real-time games – don’t have the luxury of waiting for a single-threaded process to complete (they need the answer now!). Other systems are so compute- or resource-intensive that they would take an inordinate amount of time (hours or even days in some cases) to run without introducing parallelization into their code.
    One fairly common single-threaded approach (widely used in the Node.js world, for example) is to use an event-based, non-blocking paradigm. While this does help performance by avoiding context switches, locks, and blocking, it still does not address the issues of using multiple processors concurrently (doing so would require launching, and coordinating between, multiple independent processes).
    So does this mean you have no choice but to journey deep into the bowels of threads, locks, and race conditions in order to build a concurrent application?
    Thanks to the Akka framework, the answer is no. This tutorial introduces Akka examples and explores the ways in which it facilitates and simplifies the implementation of concurrent, distributed applications.

    What is the Akka Framework?

    This post introduces Akka and explores the ways in which it facilitates and simplifies the implementation of concurrent, distributed applications.

    Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant applications on the JVM. Akka is written in Scala, with language bindings provided for both Scala and Java.
    Akka’s approach to handling concurrency is based on the Actor Model. In an actor-based system, everything is an actor, in much the same way that everything is an object in object-oriented design. A key difference, though – particularly relevant to our discussion – is that the Actor Model was specifically designed and architected to serve as a concurrent model whereas the object-oriented model is not. More specifically, in a Scala actor system, actors interact and share information, without any presupposition of sequentiality. The mechanism by which actors share information with one another, and task one another, is message passing.

    All the complexity of creating and scheduling threads, receiving and dispatching messages, and handling race conditions and synchronization, is relegated to the framework to handle transparently.

    Akka creates a layer between the actors and the underlying system such that actors simply need to process messages. All the complexity of creating and scheduling threads, receiving and dispatching messages, and handling race conditions and synchronization, is relegated to the framework to handle transparently.
    Akka strictly adheres to the The Reactive Manifesto. Reactive applications aim at replacing traditional multithreaded applications with an architecture that satisfies one or more of the following requirements:

    • Event-driven. Using Actors, one can write code that handles requests asynchronously and employs non-blocking operations exclusively.
    • Scalable. In Akka, adding nodes without having to modify the code is possible, thanks both to message passing and location transparency.
    • Resilient. Any application will encounter errors and fail at some point in time. Akka provides “supervision” (fault tolerance) strategies to facilitate a self-healing system.
    • Responsive. Many of today’s high performance and rapid response applications need to give quick feedback to the user and therefore need to react to events in an extremely timely manner. Akka’s non-blocking, message-based strategy helps achieve this.

    What is an Actor in Akka?

    An actor is essentially nothing more than an object that receives messages and takes actions to handle them. It is decoupled from the source of the message and its only responsibility is to properly recognize the type of message it has received and take action accordingly.
    Upon receiving a message, an actor may take one or more of the following actions:

    • Execute some operations itself (such as performing calculations, persisting data, calling an external web service, and so on)
    • Forward the message, or a derived message, to another actor
    • Instantiate a new actor and forward the message to it

    Alternatively, the actor may choose to ignore the message entirely (i.e., it may choose inaction) if it deems it appropriate to do so.
    To implement an actor, it is necessary to extend the akka.actor.Actor trait and implement the receive method. An actor’s receive method is invoked (by Akka) when a message is sent to that actor. Its typical implementation consists of pattern matching, as shown in the following Akka example, to identify the message type and react accordingly:

    import akka.actor.Actor
    import akka.actor.Props
    import akka.event.Logging
    class MyActor extends Actor {
      def receive = {
        case value: String => doSomething(value)
        case _ => println("received unknown message")
      }
    }
    

    Pattern matching is a relatively elegant technique for handling messages, which tends to produce “cleaner” and easier-to-navigate code than a comparable implementation based on callbacks. Consider, for example, a simplistic HTTP request/response implementation.
    First, let’s implement this using a callback-based paradigm in JavaScript:

    route(url, function(request){
      var query = buildQuery(request);
      dbCall(query, function(dbResponse){
        var wsRequest = buildWebServiceRequest(dbResponse);
        wsCall(wsRequest, function(wsResponse) {
          sendReply(wsResponse);
        });
      });
    });
    

    Now let’s compare this to a pattern-matching-based implementation:

    msg match {
      case HttpRequest(request) => {
        val query = buildQuery(request)
        dbCall(query)
      }
      case DbResponse(dbResponse) => {
        var wsRequest = buildWebServiceRequest(dbResponse);
        wsCall(dbResponse)
      }
      case WsResponse(wsResponse) => sendReply(wsResponse)
    }
    

    While the callback-based JavaScript code is admittedly compact, it is certainly harder to read and navigate. In comparison, the pattern-matching-based code makes it more immediately apparent what cases are being considered and how each is being handled.

    The Actor System

    Taking a complex problem and recursively splitting it into smaller sub-problems is a sound problem solving technique in general. This approach can be particularly beneficial in computer science (consistent with theSingle Responsibility Principle), as it tends to yield clean, modularized code, with little or no redundancy, that is relatively easy to maintain.
    In an actor-based design, use of this technique facilitates the logical organization of actors into a hierarchical structure known as an Actor System. The actor system provides the infrastructure through which actors interact with one another.
    An example of the way the actor system works in the Akka framework.
    In Akka, the only way to communicate with an actor is through an ActorRef. An ActorRef represents a reference to an actor that precludes other objects from directly accessing or manipulating that actor’s internals and state. Messages may be sent to an actor via an ActorRef using one of the following syntax protocols:

    • ! (“tell”) – sends the message and returns immediately
    • ? (“ask”) – sends the message and returns a Future representing a possible reply

    Each actor has a mailbox to which its incoming messages are delivered. There are multiple mailbox implementations from which to choose, with the default implementation being FIFO.
    An actor contains many instance variables to maintain state while processing multiple messages. Akka ensures that each instance of an actor runs in its own lightweight thread and that messages are processed one at a time. In this way, each actor’s state can be reliably maintained without the developer needing to explicitly worry about synchronization or race conditions.
    Each actor is provided with the following useful information for performing its tasks via the Akka Actor API:

    • sender: an ActorRef to the sender of the message currently being processed
    • context: information and methods relating to the context within which the actor is running (includes, for example, an actorOf method for instantiating a new actor)
    • supervisionStrategy: defines the strategy to be used for recovering from errors
    • self: the ActorRef for the actor itself
    Akka ensures that each instance of an actor runs in its own lightweight thread and that messages are processed one at a time. In this way, each actor’s state can be reliably maintained without the developer needing to explicitly worry about synchronization or race conditions.

    To help tie these tutorials together, let’s consider a simple example of counting the number of words in a text file.
    For purposes of our Akka example, we’ll decompose the problem into two subtasks; namely, (1) a “child” task of counting the number of words on a single line and (2) a “parent” task of summing those per-line word counts to get the total number of words in the file.
    The parent actor will load each line from the file and then delegate to a child actor the task of counting the words in that line. When the child is done, it will send a message back to the parent with the result. The parent will receive the messages with the word counts (for each line) and keep a counter for the total number of words in the entire file, which it will then return to its invoker upon completion.
    (Note that the Akka tutorial code samples provided below are intended to be didactic only and therefore do not necessarily concern themselves with all edge conditions, performance optimizations, and so on. Also, a complete compilable version of the code samples shown below is available in this gist.)
    Let’s first look at a sample implementation of the child StringCounterActor class:

    case class ProcessStringMsg(string: String)
    case class StringProcessedMsg(words: Integer)
    class StringCounterActor extends Actor {
      def receive = {
        case ProcessStringMsg(string) => {
          val wordsInLine = string.split(" ").length
          sender ! StringProcessedMsg(wordsInLine)
        }
        case _ => println("Error: message not recognized")
      }
    }
    

    This actor has a very simple task: consume ProcessStringMsg messages (containing a line of text), count the number of words on the specified line, and return the result to the sender via a StringProcessedMsg message. Note that we have implemented our class to use the ! (“tell”) method to send the StringProcessedMsgmessage (i.e., to send the message and return immediately).
    OK, now let’s turn our attention to the parent WordCounterActor class:

    1.  case class StartProcessFileMsg()
    2.
    3.  class WordCounterActor(filename: String) extends Actor {
    4.
    5.    private var running = false
    6.    private var totalLines = 0
    7.    private var linesProcessed = 0
    8.    private var result = 0
    9.    private var fileSender: Option[ActorRef] = None
    10.
    11.   def receive = {
    12.     case StartProcessFileMsg() => {
    13.       if (running) {
    14.         // println just used for example purposes;
    15.         // Akka logger should be used instead
    16.         println("Warning: duplicate start message received")
    17.       } else {
    18.         running = true
    19.         fileSender = Some(sender) // save reference to process invoker
    20.         import scala.io.Source._
    21.         fromFile(filename).getLines.foreach { line =>
    22.           context.actorOf(Props[StringCounterActor]) ! ProcessStringMsg(line)
    23.           totalLines += 1
    24.         }
    25.       }
    26.     }
    27.     case StringProcessedMsg(words) => {
    28.       result += words
    29.       linesProcessed += 1
    30.       if (linesProcessed == totalLines) {
    31.         fileSender.map(_ ! result)  // provide result to process invoker
    32.       }
    33.     }
    34.     case _ => println("message not recognized!")
    35.   }
    36. }
    

    Many things are going on in here, so let’s examine each of them in more detail (note that the line numbers referenced in the discussion that follows are based on the above code sample)…
    First, notice that the name of the file to process is passed to the WordCounterActor constructor (line 3). This indicates that the actor is only to be used to process a single file. This also simplifies the coding job for the developer, by avoiding the need to reset state variables (running, totalLines, linesProcessed, and result) when the job is done, since the instance is only used once (i.e., to process a single file) and then discarded.
    Next, observe that the WordCounterActor handles two types of messages:

    • StartProcessFileMsg (line 12)
      • Received from the external actor that initially initiates the WordCounterActor.
      • When received, the WordCounterActor first checks that it is not receiving a redundant request.
      • If the request is redundant, WordCounterActor generates a warning and nothing more is done (line 16).
      • If the request is not redundant:
        • WordCounterActor stores a reference to the sender in the fileSender instance variable (note that this is an Option[ActorRef] rather than an Option[Actor] – see line 9). This ActorRef is needed in order to later access and respond to it when processing the final StringProcessedMsg (which is received from a StringCounterActor child, as described below).
        • WordCounterActor then reads the file and, as each line in the file is loaded, a StringCounterActorchild is created and a message containing the line to be processed is passed to it (lines 21-24).
    • StringProcessedMsg (line 27)
      • Received from a child StringCounterActor when it completes processing the line assigned to it.
      • When received, the WordCounterActor increments the line counter for the file and, if all lines in the file have been processed (i.e., when totalLines and linesProcessed are equal), it sends the final result to the original fileSender (lines 28-31).

    Once again, notice that in Akka, the sole mechanism for inter-actor communication is message passing. Messages are the only thing that actors share and, since actors can potentially access the same messages concurrently, it is important for them to be immutable, in order to avoid race conditions and unexpected behaviors.

    Case classes in Scala are regular classes that provide a recursive decomposition mechanism via pattern matching.

    It is therefore common to pass messages in the form of case classes since they are immutable by default and because of how seamlessly they integrate with pattern matching.
    Let’s conclude the example with the code sample to run the whole app.

    object Sample extends App {
      import akka.util.Timeout
      import scala.concurrent.duration._
      import akka.pattern.ask
      import akka.dispatch.ExecutionContexts._
      implicit val ec = global
      override def main(args: Array[String]) {
        val system = ActorSystem("System")
        val actor = system.actorOf(Props(new WordCounterActor(args(0))))
        implicit val timeout = Timeout(25 seconds)
        val future = actor ? StartProcessFileMsg()
        future.map { result =>
          println("Total number of words " + result)
          system.shutdown
        }
      }
    }
    
    In concurrent programming, a “future” is a essentially a placeholder object for a result that is not yet known.

    Notice how this time the ? method is used to send a message. In this way, the caller can use the returnedFuture to print the final result when this is available and to exit the program by shutting down the ActorSystem.

    Akka fault tolerance and supervisor strategies

    In an actor system, each actor is the supervisor of its children. If an actor fails to handle a message, it suspends itself and all of its children and sends a message, usually in the form of an exception, to its supervisor.

    In Akka, supervisor strategies are the primary and straightforward mechanism for defining the fault tolerant behavior of your system.

    In Akka, the way in which a supervisor reacts to and handles exceptions that percolate up to it from its children is referred to as a supervisor strategy. Supervisor strategies are the primary and straightforward mechanism by which you define the fault tolerant behavior of your system.
    When a message signifying a failure reaches a supervisor, it can take one of the following actions:

    • Resume the child (and its children), keeping its internal state. This strategy can be applied when the child state was not corrupted by the error and it can continue functioning correctly.
    • Restart the child (and its children), clearing its internal state. This strategy can be used in the opposite scenario of the one just described. If the child state has been corrupted by the error, it is necessary the reset its state before it can be used in the Future.
    • Stop the child (and its children) permanently. This strategy can be employed in cases where the error condition is not believed to be rectifiable, but does not jeopardize the rest of the operation being performed, which can be completed in the absence of the failed child.
    • Stop itself and escalate the error. Employed when the supervisor does not know how to handle the failure and so it escalates it to its own supervisor.

    Moreover, an Actor can decide to apply the action just to the failed children or to its siblings as well. There are two pre-defined strategies for this:

    • OneForOneStrategy: Applies the specified action to the failed child only
    • AllForOneStrategy: Applies the specified action to all of its children

    Here’s a simple example, using the OneForOneStrategy:

    import akka.actor.OneForOneStrategy
    import akka.actor.SupervisorStrategy._
    import scala.concurrent.duration._
    override val supervisorStrategy =
     OneForOneStrategy() {
       case _: ArithmeticException      => Resume
       case _: NullPointerException     => Restart
       case _: IllegalArgumentException => Stop
       case _: Exception                => Escalate
     }
    

    If no strategy is specified, the following default strategy is employed:

    • If there was an error while initializing the actor or if the actor was killed, the actor is stopped.
    • If there was any other kind of exception, the actor is simply restarted.

    The Akka-supplied implementation of this default strategy is as follows:

    final val defaultStrategy: SupervisorStrategy = {
      def defaultDecider: Decider = {
        case _: ActorInitializationException ⇒ Stop
        case _: ActorKilledException         ⇒ Stop
        case _: Exception                    ⇒ Restart
      }
      OneForOneStrategy()(defaultDecider)
    }
    

    Akka allows for the implementation of custom supervisor strategies, but as the Akka documentation warns, do so with caution as incorrect implementations may lead to problems such as blocked actor systems (i.e. permanently suspended actors).

    Location transparency

    The Akka architecture supports location transparency, enabling actors to be entirely agnostic to where the messages that they receive originated. The sender of the message may reside in the same JVM as the actor or in a separate JVM (either running on the same node or a different node). Akka enables each of these cases to be handled in a manner that is completely transparent to the actor (and therefore the developer). The only caveat is that messages sent across multiple nodes must be serializable.

    The Akka architecture supports location transparency, enabling actors to be entirely agnostic to where the messages that they receive originated.

    Actor systems are designed to run in a distributed environment without requiring any specialized code. Akka only requires the presence of a configuration file (application.conf) that specifies the nodes to send messages to. Here’s a simple example of a configuration file:

    akka {
      actor {
        provider = "akka.remote.RemoteActorRefProvider"
      }
      remote {
        transport = "akka.remote.netty.NettyRemoteTransport"
        netty {
          hostname = "127.0.0.1"
          port = 2552
        }
      }
    }
    

    A few parting tips…

    We have seen how the Akka framework helps achieve concurrency and high performance. However, as this tutorial pointed out, there are a few points to keep in mind when designing and implementing your system in order to exploit the power of Akka to its fullest:

    • To the greatest extent possible, each actor should be assigned the smallest task possible (as previously discussed, following the Single Responsibility Principle)
    • Actors should handle events (i.e., process messages) asynchronously and should not block, otherwise context switches will happen which can adversely affect performance. Specifically, it is best to perform blocking operations (IO, etc.) in a Future so as not to block the actor; i.e.:
        case evt => blockingCall() // BAD
        case evt => Future {
          blockingCall()           // GOOD
        }
      
    • Be sure your messages are all immutable, since the actors that pass them to one another will all be running concurrently in their own threads. Mutable messages are likely to result in unexpected behavior.
    • Since messages sent between nodes must be serializable, it is important to bear in mind that the larger the messages are, the longer it will take to serialize, send, and deserialize them, which can negatively impact performance.

    Conclusion

    Akka, written in Scala, simplifies and facilitates the development of highly-concurrent, distributed, and fault tolerant applications, hiding much of the complexity from the developer. Doing Akka full justice would require much more than this single tutorial, but hopefully this introduction and its examples were sufficiently captivating to get you to want to read more.
    Amazon, VMWare, and CSC are but a few examples of leading companies who are actively using Akka. Visit the official Akka website to learn more and to explore whether Akka could be the right answer for your project as well.

  • Getting Started with Your First Ember.js App

    As modern web applications do more and more on the client-side (the fact itself that we now refer to them as “web applications” as opposed to “web sites” is quite telling), there has been rising interest in client-side frameworks. There are a lot of players in this field but for applications with lots of functionality and many moving parts, two of them stand out in particular: Angular.js and Ember.js.
    We already published a comprehensive [Angular.js tutorial][https://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app], so we’re going to focus on Ember.js in this post, in which we’ll build a simple Ember application to catalog your music collection. You’ll be introduced to the framework’s main building blocks and get a glimpse into its design principles. Should you want to see the source code while reading, it’s available as rock-and-roll on Github.

    What are we going to build?

    Here’s what our Rock & Roll app is going to look like in its final version:
    Final version of app with ember.js
    On the left, you’ll see that we have a list of artists and, on the right, a list of songs by the selected artist (you can also see that I have good taste in music, but I digress). New artists and songs can be added simply by typing in the text box and pressing the adjacent button. The stars beside each song serve to rate it, à la iTunes.
    We could break down the app’s rudimentary functionality into the following steps:

    1. Clicking ‘Add’ adds a new artist to the list, with a name specified by the ‘New Artist’ field (same goes for songs for a given artist).
    2. Emptying the ‘New Artist’ field disables the ‘Add’ button (same goes for songs for a given artist).
    3. Clicking an artist’s name lists their songs on the right.
    4. Clicking the stars rates a given song.

    We have a long way to go to get this working, so let’s start.

    Routes: the key to the Ember.js app

    One of the distinguishing features of Ember is the heavy emphasis it puts on URLs. In many other frameworks, having separate URLs for separate screens is either lacking or is tacked on as an afterthought. In Ember, the router—the component that manages urls and transitions between them—is the central piece that coordinates work between building blocks. Consequently, it is also the key to understanding the innerworkings of Ember applications.
    Here are the routes for our application:

    App.Router.map(function() {
      this.resource('artists', function() {
        this.route('songs', { path: ':slug' });
      });
    });
    

    We define a resource route, artists, and a songs route nested inside it. That definition will give us the following routes:
    Routes
    I used the great Ember Inspector plugin (it exists both for Chrome and Firefox) to show you the generated routes in an easily readable way. Here are the basic rules for Ember routes, which you can verify for our particular case with the help of the above table:

    1. There is an implicit application route.This gets activated for all requests (transitions).
    2. There is an implicit index route.This gets entered when the user navigates to the root of the application.
    3. Each resource route creates a route with the same name and implicitly creates an index route below it.This index route gets activated when the user navigates to the route. In our case, artists.index gets triggered when the user navigates to /artists.
    4. A simple (non-resource), nested route will have its parent route name as its prefix.The route we defined as this.route('songs', ...) will have artists.songs as its name. It gets triggered when the user navigates to /artists/pearl-jam or /artists/radiohead.
    5. If the path is not given, it is assumed to be equal to the route name.
    6. If the path contains a :, it is considered a dynamic segment.The name assigned to it (in our case, slug) will match the value in the appropriate segment of the url. Theslug segment above will have the value pearl-jam, radiohead or any other value that was extracted from the URL.

    Display the list of artists

    As a first step, we’ll build the screen which displays the list of artists on the left. This screen should be shown to the users when they navigate to /artists/:
    Artists
    To understand how that screen is rendered, it’s time to introduce another overarching Ember design principle:convention over configuration. In the above section, we saw that /artists activates the artists route. By convention, the name of that route object is ArtistsRoute. It’s this route object’s responsibility to fetch data for the app to render. That happens in the route’s model hook:

    App.ArtistsRoute = Ember.Route.extend({
      model: function() {
        var artistObjects = [];
        Ember.$.getJSON('https://localhost:9393/artists', function(artists) {
          artists.forEach(function(data) {
            artistObjects.pushObject(App.Artist.createRecord(data));
          });
        });
        return artistObjects;
      }
    });
    

    In this snippet, the data is fetched via an XHR call from the back-end and—after conversion to a model object—pushed to an array which we can subsequently display. However, the responsbilities of the route do not extend to providing display logic, which is handled by the controller. Let’s take a look.
    Hmmm—in fact, we do not need to define the controller at this point! Ember is smart enough to generate the controller when needed and set the controller’s M.odel attribute to the return value of the model hook itself, namely, the list of artists. (Again, this is a result of the ‘convention over configuration’ paradigm.) We can step one layer down and create a template to display the list:

    <script type="text/x-handlebars" data-template-name="artists">
      <div class="col-md-4">
        <div class="list-group">
          {{#each model}}
            {{#link-to "artists.songs" this class="list-group-item artist-link"}}
              {{name}}
              <span class="pointer glyphicon glyphicon-chevron-right"></span>
            {{/link-to}}
          {{/each}}
        </div>
      </div>
      <div class="col-md-8">
        <div class="list-group">
          {{outlet}}
        </div>
      </div>
    </script>
    

    If this looks familiar, it’s because Ember.js uses Handlebars templates, which have a very simple syntax and helpers but do not allow for non-trivial logic (e.g., ORing or ANDing terms in a conditional).
    In the above template, we iterate through the model (set up earlier by the route to an array that contains all artists) and for each item in it, we render a link that takes us to the artists.songs route for that artist. The link contains the artist name. The #each helper in Handlebars changes the scope inside it to the current item, so {{name}} will always refer to the name of the artist that is currently under iteration.

    Nested routes for nested views

    Another point of interest in the above snippet: {{outlet}}, which specifies slots in the template where content can be rendered. When nesting routes, the template for the outer, resource route is rendered first, followed by the inner route, which renders its template content into the {{outlet}} defined by the outer route. This is exactly what happens here.
    By convention, all routes render their content into the template of the same name. Above, the data-template-name attribute of the above template is artists which means that it will get rendered for the outer route, artists. It specifies an outlet for the content of the right panel, into which the inner route, artists.index renders its content:

    <script type="text/x-handlebars" data-template-name="artists/index">
      <div class="list-group-item empty-list">
        <div class="empty-message">
          Select an artist.
        </div>
      </div>
    </script>
    

    In summary, one route (artists) renders its content in the left sidebar, its model being the list of artists. Another route, artists.index renders its own content into the slot provided by the artists template. It could fetch some data to serve as its model but in this case all we want to display is static text, so we don’t need to.

    Create an artist

    Part 1: Data binding

    Next, we want to be able to create artists, not just look at a boring list.
    When I showed that artists template that renders the list of artists, I cheated a bit. I cut out the top part to focus on what’s important. Now, I’ll add that back:

    <script type="text/x-handlebars" data-template-name="artists">
      <div class="col-md-4">
        <div class="list-group">
          <div class="list-group-item">
            {{input type="text" class="new-artist" placeholder="New Artist" value=newName}}
            <button class="btn btn-primary btn-sm new-artist-button" {{action "createArtist"}}
              {{bind-attr disabled=disabled}}>Add</button>
          </div>
        < this is where the list of artists is rendered >
      ...
    </script>
    

    We use an Ember helper, input, with type text to render a simple text input. In it, we bind the value of the text input to the newName property of the controller that backs up this template, ArtistsController. By consequence, when the value property of the input changes (in other words, when the user types text into it) the newName property on the controller will be kept in sync.
    We also make it known that the createArtist action should be fired when the button is clicked. Finally, we bind the disabled property of the button to the disabled property of the controller. So what does the controller look like?

    App.ArtistsController = Ember.ArrayController.extend({
      newName: '',
      disabled: function() {
        return Ember.isEmpty(this.get('newName'));
      }.property('newName')
    });
    

    newName is set to empty at the start which means that the text input is going to be blank. (Remember what I told about bindings? Try to change newName and see it get reflected as the text in the input field.)
    disabled is implemented such that when there is no text in the input box, it is going to return true and thus the button will be disabled. The .property call at the end makes this a “computed property”, another scrumptious slice of the Ember cake.
    Computed properties are properties that depend on other properties, which can themselves be “normal” or computed. Ember caches the value of these until one of the dependent properties change. It then recalculates the value of the computed property and caches it again.
    Here’s a visual representation of the above process. To summarize: when the user inputs an artist’s name, thenewName property updates, followed by the disabled property and, finally, the artist’s name is added to the list.

    Detour: A single source of truth

    Think about that for a moment. With the help of bindings and computed properties, we can establish (model) data as the single source of truth. Above, a change in the name of the new artist triggers a change in the controller property, which in turn triggers a change in the disabled property. As the user starts to type the name of the new artist, the button becomes enabled, as if by magic.
    The bigger the system, the more leverage we gain from the ‘single source of truth’ principle. It keeps our code clean and robust, and our property definitions, more declarative.
    Some other frameworks also put emphasis on having model data be the single source of truth but either do not go as far as Ember or fail to do such a thorough a job. Angular, for example, has two-way bindings—but does not have computed properties. It can “emulate” computed properties through simple functions; the problem here is that it has no way of knowing when to refresh a “computed property” and thus resorts to dirty checking and, in turn, leads to a performance loss, especially notable in bigger applications.
    Should you wish to learn more about the topic, I recommend you read eviltrout’s blog post for a shorter version or this Quora question for a lengthier discussion in which core developers from both sides weigh in.

    Part 2: Action handlers

    Let’s go back to see how the createArtist action is created after it’s fired (following the press of the button):

    App.ArtistsRoute = Ember.Route.extend({
      ...
      actions: {
        createArtist: function() {
          var name = this.get('controller').get('newName');
          Ember.$.ajax('https://localhost:9393/artists', {
            type: 'POST',
            dataType: 'json',
            data: { name: name },
            context: this,
            success: function(data) {
              var artist = App.Artist.createRecord(data);
              this.modelFor('artists').pushObject(artist);
              this.get('controller').set('newName', '');
              this.transitionTo('artists.songs', artist);
            },
            error: function() {
              alert('Failed to save artist');
            }
          });
        }
      }
    });
    

    Action handlers need to be wrapped in an actions object and can be defined on the route, controller or view. I chose to define it on the route here because the result of the action is not confined to the controller but rather, “global”.
    There is nothing fancy going on here. After the back-end informed us that the saving operation completed successfully, we do three things, in order:

    1. Add the new artist to the model of the template (all artists) so that it gets re-rendered and the new artist appears as the last item of the list.
    2. Clear the input field via the newName binding, saving us from having to manipulate the DOM directly.
    3. Transition to a new route (artists.songs), passing in the freshly created artist as the model for that route. transitionTo is the way to move between routes internally. (The link-to helper serves to do that via user action.)

    Display songs for an artist

    We can display the songs for an artist either by clicking on the artist’s name. We also pass in the artist that is going to become the model of the new route. If the model object is thusly passed in, the model hook of the route will not be called since there is no need to resolve the model.
    The active route here is artists.songs and thus the controller and template are going to be ArtistsSongsController and artists/songs, respectively. We already saw how the template gets rendered into the outlet provided by the artists template so we can focus on just the template at hand:

    <script type="text/x-handlebars" data-template-name="artists/songs">
      (...)
      {{#each songs}}
        <div class="list-group-item">
          {{title}}
          {{view App.StarRating maxRating=5}}
        </div>
      {{/each}}
    </script>
    

    Note that I stripped out the code to create a new song as it would be exactly the same as that for creating a new artist.
    The songs property is set up in all artist objects from the data returned by the server. The exact mechanism by which it is done holds little interest to the current discussion. For now, it’s sufficient for us to know that each song has a title and a rating.
    The title is displayed directly in the template and the rating gets represented by stars, via the StarRatingview. Let’s see that now.

    Star rating widget

    A song’s rating falls between 1 and 5 and gets shown to the user through a view, App.StarRating. Views have access to their context (in this case, the song) and their controller. This means they can read and modify its properties. This is in contrast to another Ember building block, components, which are isolated, reusable controls with access to only what has been passed in to them. (We could use a star rating component in this example, too.)
    Let’s see how the view displays the number of stars and sets the song’s rating when the user clicks on one of the stars:

    App.StarRating = Ember.View.extend({
      classNames: ['rating-panel'],
      templateName: 'star-rating',
      rating: Ember.computed.alias('context.rating'),
      fullStars: Ember.computed.alias('rating'),
      numStars:  Ember.computed.alias('maxRating'),
      stars: function() {
        var ratings = [];
        var fullStars = this.starRange(1, this.get('fullStars'), 'full');
        var emptyStars = this.starRange(this.get('fullStars') + 1, this.get('numStars'), 'empty');
        Array.prototype.push.apply(ratings, fullStars);
        Array.prototype.push.apply(ratings, emptyStars);
        return ratings;
      }.property('fullStars', 'numStars'),
      starRange: function(start, end, type) {
        var starsData = [];
        for (i = start; i <= end; i++) {
          starsData.push({ rating: i, full: type === 'full' });
        };
        return starsData;
      },
      (...)
    });
    

    rating, fullStars and numStars are computed properties which we discussed previously with the disabledproperty of the ArtistsController. Above, I used a so-called computed property macro, about a dozen of which are defined in Ember. They make typical computed properties more succinct and less error-prone (to write). I set rating to be the rating of the context (and thus the song), while I defined both the fullStars and numStars properties so that they read better in the context of the star rating widget.
    The stars method is the main attraction. It returns an array of data for the stars in which each item contains arating property (from 1 to 5) and a flag (full) to indicate whether the star is full. This makes it exceedingly simple to walk through them in the template:

    <script type="text/x-handlebars" data-template-name="star-rating">
      {{#each view.stars}}
        <span {{bind-attr data-rating=rating}}
          {{bind-attr class=":star-rating :glyphicon full:glyphicon-star:glyphicon-star-empty"}}
          {{action "setRating" target=view}}>
        </span>
      {{/each}}
    </script>
    

    This snippet contains several points of note:

    1. First, the each helper designates that it uses a view property (as opposed to a property on the controller) by prefixing the property name with view.
    2. Second, the class attribute of the span tag has mixed dynamic and static classes assigned. Anything prefixed by a : becomes a static class, while the full:glyphicon-star:glyphicon-star-empty notation is like a ternary operator in JavaScript: if the full property is truthy, the first class should be assigned; if not, the second.
    3. Finally, when the tag is clicked, the setRating action should be fired—but Ember will look it up on the view, not the route or controller, as in the case of creating a new artist.

    The action is thus defined on the view:

    App.StarRating = Ember.View.extend({
      (...)
      actions: {
        setRating: function() {
          var newRating = $(event.target).data('rating');
          this.set('rating', newRating);
        }
      }
    });
    

    We get the rating from the rating data attribute we assigned in the template and then set that as the ratingfor the song. Note that the new rating is not persisted on the back-end. It would not be difficult to implement this functionality based on how we created an artist and is left as an exercise for the motivated reader.

    Wrapping it all up

    We have tasted several ingredients of the aforementioned Ember cake:

    • We have seen how routes are the crux of Ember applications and how they serve as the basis of naming conventions.
    • We have seen how two-way data bindings and computed properties make our model data the single source of truth and allow us to avoid direct DOM manipulation.
    • And we have seen how to fire and handle actions in several ways and build a custom view to create a control that is not part of our HTML.

    Beautiful, isn’t it?