Java Basics

1.1   The structure of a Java class and source code file

1.1.1       Structure of a Java class

A class can define multiple components for example:

  • Package statement
  • Import statement
  • Comments
  • Class declarations and definitions
  • Variables
  • Methods
  • Constructors       Package Statement

All Java classes are part of a package; if a class is not defined in a named package it becomes part of a default package, which doesn´t have a name. If a class includes a package statement, it must be the first statement in the class definition (it cannot appear within a class declaration or after the class declaration) and if present, it must appear exactly once in a class:

package certification;
//should be the first statement in a class

class Course{
} Import Statement

Classes and interfaces from the same package can use each other without prefixing the package name. But to use a class or interface from another package, the import statement can be used:

package University;
import certification.ExamQuestion;
// import must be placed after the package

class AnnualExam{
     examQuestion eq;

The import statement follows the package but precedes the class declaration. Comments

The comments in Java code can be placed at multiple places in a class. To place multiline comments, start with /* and end with */ . End-of-line comments start with // and are placed at the end of a line of code. Comments can be placed before the package statement.

* @author JRamirez // first name initial + last name End-of-line within a multiline
* @version 0.0.2
* Class to store the details of a monument
package uni; // package uni End-of-line comment

class Monument {
     int startYear;
} Class Declaration

Components of a class declaration:

  • Access modifiers
  • Nonaccess modifiers
  • Class name
  • Name of the base class, if the class is extending another class
  • All implemented interfaces, if the class is implementing any interfaces
  • Class body (class fields, methods, constructors), included within a pair of curly

braces, {}


public final class Runner extends Person implements Athlete {} Compulsory and optional elements of a class:


  • Keyword class
  • Name of the class
  • Class body, marked by the opening and closing curly braces, {}


  • Keyword class Access modifier, such as public
  • Nonaccess modifier, such as final
  • Keyword extends together with the name of the base class
  • Keyword implements together with the name of the interfaces being implemented Class Definition

The use of a class is to specify the behavior and properties of an object using methods and variables. It is a design from which an object can be created.

1.1.2       Structure and components of a Java source code file

A  Java  source code  file  is  used  to  define  classes  and  interfaces.  All your Java code should be defined in Java source code files (text files whose names end with .java)   Definition of interfaces in a Java source code file

An interface is a grouping of related methods and constants, but the methods in an

interface cannot define any implementation.

interface Controls {
     void changeChannel(int channelNumber);
     void increaseVolume();
     void decreaseVolume();
} Definition of single and multiple classes in a single java source code file

A single class or interface can be defined in a single Java source code or multiple classes and interfaces can be within the same source code. The classes and interfaces can be defined in any order of occurrence in a Java source code file. If a public class or interface is defined, its name should match the name of the Java source code file.  Application of package and import statements in Java source code files

When an import or package statement is used within a java source code file, it applies to all classes and interfaces defined in that code.

1.2 Executable Java applications

1.2.1    Executable Java classes versus nonexecutable Java clases

An executable Java class is a class which, when handed over to the Java Virtual Machine, starts its execution at a particular point in the class in the main method. A nonexecutable class doesn’t have it. The programmer designates an executable class from all of the files of an application.

1.2.2  Main method

The first requirement in creating an executable Java application is to create a class with  a  method  whose  signature  (name  and  method  arguments)  match  the main method.

public class HelloExam {
         public static void main(String args[]) {
         System.out.println("Hello exam");

This main method should comply with the following rules:

  • The method must be marked as a public method.
  • The method must be marked as a static method.
  • The name of the method must be main.
  • The return type of this method must be void.
  • The method must accept a method argument of a String array or a variable argument of type String

The keywords public and static can be interchanged:

public static void main(String[] args)

static public void main(String[] args)

1.3       Java Packages

1.3.1       The need for packages

Packages are used to group classes and interfaces, they also provide protection and namespace management. Subpackages can also be created within the packages.

1.3.2       Defining classes in a package using the package statement

//The first statement in a class or interface must be the package statement:

package certification;

class ExamQuestion {



Rules about packages:

  • Per Java naming conventions, package names should all be in lowercase.
  • The package and subpackage names are separated using a dot (.).
  • Package names follow the rules defined for valid identifiers in Java.
  • For packaged classes and interfaces, the package statement is the first statement in a Java source file (a .java file). The exception is that comments can appear before or after a package statement.
  • There can be a maximum of one package statement per Java source code file (.java file).
  • All the classes and interfaces defined in a Java source code file will be defined in the same package. There is no way to package classes and interfaces defined within the same Java source code file in different packages.       Directory Structure and Package Hierarchy

The hierarchy of the packaged classes and interfaces should match the hierarchy of the directories in which those classes are defined.

1.3.3       Using simple names with import statements

For using classes and interfaces in other classes of your code, there are two options, using the fully qualified name or using the import statement with a simple name of the class or package.


package office;

 class Cubicle {

     home.LivingRoom livingRoom;


package office;

import home.LivingRoom;

class Cubicle {

     LivingRoom livingRoom;


1.3.4       Using packaged classes without using the import statement

By using its fully qualified name, a class or interface can be used without an import statement.

class AnnualExam {

     certification.ExamQuestion eq;


This is often used when there are multiple classes and interfaces with the same name, because the import statement cannot be used in that case.

class AnnualExam {

     java.util.Date date1;

     java.sql.Date date2;


1.3.5       Importing a single or all members of a package

By using an asterisk, all the public classes, members and interfaces of a package can be imported at once.

import certification.*;

 class AnnualExam {

     ExamQuestion eq;

     MultipleChoice mc;


Importing a class in Java doesn’t add to the size of the file.

1.3.6       Importing Recursively

By using an asterisk, classes from a subpackage are not imported, only classes from the main package.

1.3.7       Default Package Import

If no explicit package is defined for classes or interfaces, they are imported in the default package automatically in all the classes and interfaces in the same directory.

class Person {

     // code


class Office {

     Person p;


A class from a default package can’t be used in any named packaged class.

1.3.8 Static Imports

To import an individual static member of a class or all its static members, the import static statement must be used.

package certification;

public class ExamQuestion {

     static public int marks;

     public static void print() {



package university;

import static certification.ExamQuestion.marks;

class AnnualExam {

     AnnualExam() {

           marks = 20;



//Importing all of the static members:

package university;

import static certification.ExamQuestion.*;

class AnnualExam {

     AnnualExam() {

          marks = 20;




1.4       Java Access Modifiers

1.4.1       Access Modifiers

Access modifiers control the accessibility of a class or interface and its members, by other classes and interfaces.

They can be applied to classes, interfaces, and their members (instance and class variables and methods). Local variables and method parameters can’t be defined using access modifiers.

Java defines four access modifiers:

  • public(least restrictive)
  • protected
  • default
  • private(most restrictive)

1.4.3       Public Access Modifier

Classes and interfaces defined using the public access  modifier  are  accessible  across  all  packages,  from  derived  to  unrelated classes.

1.4.4       Protected Access Modifier

Classes and interfaces defined using the protected access modifier are accessible to classes and interfaces in the same package and all derived classes even in separate packages. They cannot be accessed by unrelated classes in other packages.

1.4.5       Default Access (package access)

Classes and interfaces defined without any explicit access modifier are defined with package accessibility (default accessibility). They can only be accessed by classes and interfaces defined in the same package.

1.4.6       Private Access Modifier

The members of a class defined using the private access modifier are accessible only to themselves. Private members are not accessible outside the class they are defined.

1.5       Nonaccess Modifiers

1.5.1       Abstract Modifier

When added to the definition of a class, interface, or method, the abstract modifier changes  its  default  behavior.       Abstract Class

When  the abstract keyword  is  prefixed  to  the  definition  of  a  concrete  class,  it changes it to an abstract class. An abstract class can’t be instantiated. An abstract class can be defined without any abstract methods but a concrete class cannot define an abstract method.       Abstract Interface

An interface is an abstract entity by default. The Java compiler automatically adds the keyword abstract to the definition of an interface.       Abstract Method

An abstract method doesn’t have  a  body.  Usually, an abstract method is implemented by a derived class.       Abstract Variables

No type of variable can be defined as abstract.

1.5.2       Final Modifier

The keyword final changes the default behavior of a class, variable, or method.       Final Class

A class defined final cannot be extended by other classes.       Final Interface

No interface can be marked as final.       Final Variable

A final variable can only be assigned a value once.       Final Method

A final method defined in a base class cannot be overridden in a derived class.

1.5.3       Static Modifier

Can be applied to the definitions of variables, methods,  classes,  and  interfaces.       Static Variables

They are common to all instances of a class and are not unique. They are shared by all the objects of the class. Static variables may be accessed even when no instances of a class have been created.       Static Methods

Static methods aren’t associated with objects and can’t use any of the instance variables of a class. They can be used to use or manipulate static variables of a class.

Nonprivate static variables and methods can be inherited by derived classes and can be redefined within the derived class.       What can a static method access?

Non-static variables and methods can access static variables and methods. Static methods and variables cannot access the instance methods of a class.

Java 8 Streams and JPA

Since the definition of the JPA Standard predates the release of Java 8 it is not surprising that the JPA API is only based on collections. There is no way to obtain a Java 8 Stream out of a query object.

For those out there using Hibernate as their JPA provider there is an interesting way to create a stream for your JPQL queries.

Hibernate Scrollable Results

Hibernate supports many more features than those offered by the JPA Standard only. Hibernate’s Query class allows us to obtain an iterator-like object for a JQPL query. This iterator-like class is named ScrollableResults.

You can see a great example of this feature in this blog post about Reading Large Result Sets with Hibernate and MySQL. I have taken the liberty of copying one of their examples:

Query query = session.createQuery(query);
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
while ( {
   Object row = results.get();
   // process the entity here

Creating an Iterator Wrapper around Scrollable Results

Let’s take this a bit further now by implementing a Java Iterator wrapper around the Hibernate’s scrollable results object as shown below:

class ScrollableResultIterator<T> implements Iterator<T> {
   private final ScrollableResults results;
   private final Class<T> type;

   ScrollableResultIterator(ScrollableResults results, Class<T> type) {
      this.results = results;
      this.type = type;

   public boolean hasNext() {

   public T next() {
      return type.cast(results.get(0));

Gaining Access to Hibernate Session through JPA Entity Manager

As you can see the examples above use a Hibernate session object to obtain an instance of a Hibernate query object. Supposing we are using JPA, we typically have access to an EntityManager, but not to any particular implementation objects of the underlaying provider.

To gain access to the Hibernate’s Session object we can use a special method in the entity manger.

Session session = entityManager.unwrap(Session.class);

Be warned that at this point we are escaping from the safety of vendor agnostic code. In other words, if we ever wanted to use another provider like OpenJPA or EclipseLink, we would be forced to find a different alternative to implement our code here since those other providers won’t offer anything like Hibernate’s Session and ScrollableResults.

From Iterators to Spliterators to Streams

Our next step consists in obtaining a Java 8 stream out of this iterator. Lukas Eder recently wrote an interesting article about the difficulties to obtain a stream out of an iterable object which will be pretty handy here.

To achieve our goal we now need to use two utility classes in Java 8 named StreamSupport and Spliterators.

For instance, we could take an iterator, like the one we defined above and transform it into a Spliterator by doing:

private Spliterator<T> toSplitIterator(ScrollableResults scroll, Class<T> type){
   return Spliterators.spliteratorUnknownSize(
      new ScrollableResultIterator<>(scroll, type),
         Spliterator.DISTINCT | Spliterator.NONNULL | 
         Spliterator.CONCURRENT | Spliterator.IMMUTABLE

This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it:, false);

At this point we have built enough to create our first stream out of a JPQL query. We can do it as follows:

public Stream<T> getResultStream(
      String sql, 
      Integer fetchSize, 
      Map<String,Object> parameters) 
   Query query = session.createQuery(sql);
   if (fetchSize != null) {
   for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
      query.setParameter(parameter.getKey(), parameter.getValue());
   ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
   return, type), false)

A JPA Stream API

We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API:

public interface StreamQuery<T> {
   Stream<T> getResultStream();
   StreamQuery<T> setParameter(String name, Object value);
   StreamQuery<T> setFetchSize(int fetchSize);

And putting together all we have learned so far we could create this implementation of our new StreamQuery interface:

public class HibernateQueryStream<T> implements StreamQuery<T> {

   private final Session session;
   private final String sql;
   private final Class<T> type;
   private final Map<String, Object> parameters = new HashMap<>();
   private Integer fetchSize;

   public HibernateQueryStream(
      EntityManager entityManager, 
      String sql, 
      Class<T> type) 
     this.session = entityManager.unwrap(Session.class);
      this.sql = sql;
      this.type = type;

   public StreamQuery<T> setParameter(String name, Object value) {
      parameters.put(name, value);
      return this;
   public StreamQuery<T> setFetchSize(int fetchSize) {
      this.fetchSize = fetchSize;
      return this;

   public Stream<T> getResultStream() {
      Query query = session.createQuery(sql);
      if (fetchSize != null) {
      for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
         query.setParameter(parameter.getKey(), parameter.getValue());
      ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
      return, type), false)
   private Spliterator<T> toSplitIterator(ScrollableResults scroll, Class<T> type){
      return Spliterators.spliteratorUnknownSize(
         new ScrollableResultIterator<>(scroll, type),
            Spliterator.DISTINCT | Spliterator.NONNULL | 
            Spliterator.CONCURRENT | Spliterator.IMMUTABLE

   private static class ScrollableResultIterator<T> implements Iterator<T> {

      private final ScrollableResults results;
      private final Class<T> type;
      ScrollableResultIterator(ScrollableResults results, Class<T> type) {
         this.results = results;
         this.type = type;
      public boolean hasNext() {
      public T next() {
         return type.cast(results.get(0));

The Repository Layer

On top of this component we can now build our repository layer.

public class StreamRepository {

   private EntityManager entityManager;

   public Stream<Order> getOrderHistory(String email) {
      String jpql = "SELECT o FROM Order o WHERE";
      StreamQuery<Order> query = new HibernateQueryStream<>(
      return query.getResultStream();

And from here the rest is a piece of cake:

   .filter(order -> > 100)
   .reduce(0, (x,y) -> x + y);

It is important to highlight that the Hibernate session must be alive by the time we actually consume the stream, because it is at that point that the entities will be mapped. So, make sure that wherever you consume the stream the Hibernate session or you entity manager context is still alive.

Further Reading

Functional Programming with Java 8 Functions

Edwin Dalorzo I have finally had the opportunity to work in a couple of projects being entirely developed with Java 8 and during the past months I’ve experienced, first hand, many of the new functional programming features in the language. So I decided to write a series of articles about some of these things I’ve being learning and how some of the well known functional programming constructs can be translated into Java 8.


Ok, let’s start with something simple. The following is a lambda expression (i.e. an anonymous function) that takes an argument x and increments it by one. In other words a function that receives, apparently an integer, and returns a new incremented integer:

x -> x + 1

And what is the type of this function in Java?

Well, the answer is that it depends. In Java the same lambda expression could be bound to variables of different types. For instance, the following two are valid declarations in Java:

Function<Integer,Integer> add1 = x -> x + 1;
Function<String,String> concat1 = x -> x + 1;

The first one increments an integer x by one, whereas the second one concatenates the integer 1 to any string x.

And how can we invoke these functions?

Well, now that they are bound to a reference we can treat them pretty much like we treat any object:

Integer two = add1.apply(1); //yields 2
String answer = concat1.apply("0 + 1 = "); //yields "0 + 1 = 1"

So, as you can see every function has a method apply that we use to invoke it and pass it an argument.

And what if I already have a method that does that, can I use it as a function?

Yes, since an alternative way to create functions is by using methods we had already defined and that are compatible with our function definition.

Suppose that we have the following class definition with methods as defined below:

public class Utils {
   public static Integer add1(Integer x) { return x + 1; }
   public static String concat1(String x) { return x + 1; }

As you can see the methods in this class are compatible with our original function definitions, so we could use them as “method references” to create the same functions we did before with lambda expressions.

Function<Integer,Integer> add1 = Utils::add1;
Function<String,String> concat1 = Utils::concat1;

These two are just the same thing as the ones we did before.

High Order Programming

The cool thing about functions is that they encapsulate behavior, and now we can take a piece of code, put it into a function and pass it around to other functions or methods for them to use it. This type of functions that operate on (or produce new) functions are typically called high order functions and the programming style based on exploiting this powerful feature is called, unsurprisingly, high order programming.

About Functions that Create Functions

Let’s see a couple of examples of how we can do this using function objects. Let’s consider the following example:

Function<Integer, Function<Integer,Integer>> makeAdder = x -> y -> x + y;

Above we have a function called makeAdder that takes an integer x and creates a new function that takes an integer y and when invoked adds x to y. We can tell this is a high order function because it produces a new function.

Now, we use this to create our original add1 function:

Function<Integer,Integer> add1 = makeAdder.apply(1);
Function<Integer,Integer> add2 = makeAdder.apply(2);
Function<Integer,Integer> add3 = makeAdder.apply(3);

With our new high order function, however, we could also create add2, add3, ..., addn, right?

Can’t we define this in a simpler way as we did before with the Utils class methods?

Yes, we can. Consider the following addition to the Utils class:

public class Utils {
    public static Function<Intger, Integer> adder(Integer x) {
       return y -> x + y;

This signature is a bit simpler to read than that in our lambda expression, but as you can see it is pretty much the same thing. The function continues to receive the same number and type of arguments and continues to return the same type of result.

We can now use this simpler function factory to create our makeAdder and add1 functions again:

Function<Integer, Function<Integer,Integer>> makeAdder = Utils::adder;
Function<Integer,Integer> add1 = makeAdder.apply(1);

And there you have it, this is exactly the same thing as before.

About Functions that Receive Functions as Arguments

Let’s suppose we had the following two functions defined:

Function<Integer,Integer> add1 = x -> x + 1;
Function<Integer,Integer> mul3 = x -> x * 3;

Now, naively, we could invoke this two functions together to increment and multiply a number by 3, right?. Like this:

Integer x = 10;
Integer res = mul3.apply(add1.apply(x)); //yields 33

But what if we created a function that did both things instead?

Consider the following pseudocode:

(f,g) -> x -> g( f(x) )

This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order. This is a classical example of what is called function composition.

In some languages there is even an operator to compose two functions in this way:

h = f o g

Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h.

How can we do function composition in Java?

I can think of two ways to do this in Java, one more difficult than the other. Let’s start with the more difficult first, because that will let us appreciate the value of the simpler solution later on.

Function Composition Strategy 1

First, we must start by realizing that the function in pseudocode above is a binary function (i.e. a function that receives two arguments). But all our examples so far have dealt only with unary functions.

It would seem this is not important, but in Java it is, since functions of different arities have different target functional interfaces. In Java, a function that receives two arguments is called BinaryOperator.

For instance, using a BinaryOperator we could implement a sum operator:

BinaryOperator<Integer> sum = (a,b) -> a + b;
Integer res = sum.apply(1,2); // yields 3

Well, just as easily we could implement the compose operator, right? Only that in this case, instead of two simple integers, we receive two unary functions:

BinaryOperator<Function<Integer,Integer>> compose;
compose = (f,g) -> x -> g.apply(f.apply(x));

Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3, one after the other.

Function<Integer,Integer> h = compose.apply(add1,mul3);
Integer res = h.apply(10); //yields 33	

And now we can beautifully, and in really simple way, combine two unary integer functions.

Function Composition Strategy 2

Now, function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design, and so, to make our lives simpler, all Function objects have a method called compose that allows us to very easily compose two functions together.

The following code produces the exact same result as above:

Function<Integer,Integer> h = mul3.compose(add1);
Integer res = h.apply(10);	

Partial Function Application or Currying

In most functional programming languages it is possible to create partially applied functions. That is, if a function is receiving multiple arguments, we can partially invoke the function providing just a few arguments and receive a partially applied function out of it. This is typically called currying.

Although you have not noticed it, we have already covered that in this article, but now we are going to make it much more evident :-)

So, consider the following pseudo code

sum = x -> y -> x + y

Then we say that sum is a function that accepts one parameter x and fabricates another anonymous function that in turn accepts one parameter y that, when invoked, sums x and y.

In many functional programming languages a construct like this can be invoked as if this was just one simple function by doing:

sum 10 5 //yields 15

But the truth is that this is just syntactic sugar to do:

sum(10)(5) //yields 15

Since sum is a function that returns a function.

The beauty of this idiom is that now we could partially apply sum:

plus10 = sum 10

And now plus10 is a partially applied function of sum. Can you see now where we had already talked about this?

plus10(5) //yields 15

Can we do this with Java?

The truth is that we have already done it above, we just probably did not notice. Unfortunately, in Java we do not have the syntactic sugar that some other language have, and therefore this is a bit more verbose:

Function<Integer,Function<Integer,Integer>> sum = x -> y -> x + y;

Well, you can see sum is declared in a “currified” way. And now we can partially apply it:

Function<Integer, Integer> plus10 = sum.apply(10);
Integer res = plus10.apply(5); //yields 15

Unary, Binary, Ternary and n-ary Functions

So, as mentioned above, Java uses different functional interfaces for different function arities. And so Function<T,R> is a functional interface for any unary function where the domain and the codomain of the function may be of different types.

For instance, we could define a function that receives a string value and parses it as an integer:

Function<String,Integer> atoi = s -> Integer.valueOf(s);

But most of our examples above are for integer functions whose argument and return value are of this same type. For those cases we could alternatively use the UnaryOperator<T> instead. This is just a Function<T,T>.

Thus, some our declarations above could be slightly simplified with this functional interface:

UnaryOperator<Integer> add1 = n -> n + 1;
UnaryOperator<String> concat1 = s -> s + 1;
Function<Integer, UnaryOperator<Integer>> sum = x -> y -> x + y;
UnaryOperator<Integer> sum10 = sum.apply(10);

I have already written another article that explains Why Java 8 has Interface Pollution like this in case you are interested in an explanation.

Value Types and Primitive Type Functions?

Evidently using a type like Integer incurs into the costs of boxing and unboxing when our functions have to deal with a primitive type like int.

As you know, Java does not support value types as type arguments in generic declarations, so to deal with this problem we can use alternative functional interfaces like ToIntFunction, IntFunction or IntUnaryOperator.

Or we can define our own primitive function.

interface IntFx {
	public int apply(int value);

Then we can do:

IntFx add1 = n -> n + 1;
IntFunction<IntFx> sum = x -> y -> x + y;
IntFx sum10 = sum.apply(10);
sum10.apply(4); //yields 14

Similar functional interfaces can be found in the Java API for types double and long as well. This topic is also covered in the alternative article mentioned above about interface pollution.

And that’s it for the time being. I hope that in a future article I can take this a bit further and show some practical applications derived from my experience in actual projects.

Further Reading

JSApps 101: AngularJS In A Nutshell


Moving on with the topic, in the previous part of this series, we discussed about that interesting new tendency to let the browser do all the user interface heavy-lifting on the client-side, since it is such a good guy. Of course, this involves a LOT of JavaScript going on, since it is the only language the browser understands besides HTML.

We all know how complex and crazy things can get when you involve JavaScript in the picture. The language is usually seen as over-complicated, it used to be hard to debug, learning curve is steep as hell and it can get confusing quickly; also, there used to be a lack of tools and IDEs with strong support for its development just sums up for bad reputation.

However, fear not! After this article, you will have a solid base on how you can turn the fiendish JavaScript you have known for years from a simple DOM traversal helper to a whole reliable application development framework with the aid of AngularJS; man, now THAT’S a catchy name.

What In The World Is AngularJS?

AngularJS is a JavaScript library that allows you to implement the Model-view-controller pattern (in some sort of way) at a client-side level (dude, the browser). Why is this? Because you have two options in life:

  • Option A    You implement a +1000 lines JavaScript source file with a bunch of code that not only is in charge of handling manipulation of the HTML structure and creation of UI components, but also handles all of the data validation and display logic of it, all of this while your fellow teammates start hating the guts out of you.
  • Option B    You be a good developer, who cares about separation of concerns, and split all those tasks in several components where each is in charge of a single thing; those written in separate files for your code maintainability’s sake, while making a lot of friends in the process.

In the good old days, option A was “kind” of affordable (heavy quotations), since JavaScript was used for simple things like adding and removing elements from the HTML structure, changing colors and such. But when we talk about implementing a client application only using JavaScript, option A starts struggling. Mainly because we are not only moving HTML elements around, animating stuff and other user interface tasks; but also performing data validation, error handling and server communications in the client-side.

Of course, option B is the way to go. Since there is a ton of things going on in the browser, we need a way to create components that handle each task separately. This is known as the Separation of Concerns principle, or SOC; which states that your code has to be split in several parts, handling a single task each, orchestrated in order to achieve a common good. And this is where AngularJS shines. It allows you to:

  • Organize your client-side code in a Model-view-controller fashion, so you have separate components where each handles a different task in the logic stack: from user input to server data posting (Don’t worry, we’ll get on this later on.)
  • Live template processing and data-binding; more specifically: munch a template, bind it to specific data coming from the server or anywhere else and then produce a valid HTML piece that can be displayed in the browser.
  • Creation of re-usable user interface components.
  • Implementation of advanced patterns, like dependency injection; which is tied to…
  • Ability to implement unit tests for the JavaScript code.

Client-side Model-View-Whatever

We all know Model-View-Controller (MVC from now on) was conceived for a good reason: Roles and responsibilities matters. It was designed as a practical way to separate all of the front-end logic into three interconnected parts, so code having to do with how data is displayed is clearly separated from the code that validates, stores and retrieves that data. Also, it was thought with unit testing in mind. MVC Flow Now, MVC is commonly used server-side; think of ASP.NET MVC or Spring MVC, where you have a class representing the “controller”, which fetches data into “models” and then binds them to a template producing a “view” in the form of an HTML document, which is returned to the browser for display on the user screen. Remember, each time we talk about MVC, we are generally referring to the Presentation Layer of an application.

Now, why go crazy and MVC-fy my JavaScript code? Well, because what’s trendy right now are dynamic web interfaces where pretty much everything is asynchronous, little post-backs are done to the server unless really necessary and you have complex UI components like pop-ups, multi-level grids and others living on the screen (think of Facebook, for example). The only way to do this is delegate the browser (through JavaScript) with the user-interface composition, interaction between all of the components and lastly fetching and posting data back and forth from the server. You really, really NEED a way to achieve law and order so the client-side code does not become an uncontrollable mess.

OK, enough talk already. Let’s dive into how to implement a simple application using AngularJS.

Hello, Angular

Consider the classic “To-do List” example. We want a screen that displays a list of items to be completed; also we need to show a mini-form that allows us to enter and add new items to the list. Here is how it should look: To-do List UI So, in order to get this done, we need to complete some steps:

  • Create the HTML document which will be representing our view.
  • Include the AngularJS library in the HTML document so we can start creating controllers that will handle behavior of the user interface.
  • Create and include a JavaScript file where we are going to create our application object (wait for it) and define some controllers.
  • Add scope (almost there…) variables and functions that will be bound to the view through special AngularJS HTML attributes.

Basic View Markup

Let’s start this in a natural way: let’s create the user interface first. We will create a file called todolist.html and we will add the following HTML to it:
Now, nothing fancy right there; we just included the AngularJS library at line 8 and another file at line 9, which we will create in a moment. However, just notice the structure of the document: We have an UL element which will represent our list of to-do items and then a couple input controls so we can add new items to the list. It does not have any information on it for now, but eventually it will… And it will be awesome.

Let’s leave this code as it is for now, let’s move to the app.js file which has all the fun going on.

Adding Logic: The Controller

Just by looking at the previous HTML document, you will realize that there are two things we need regarding to view state data:

  • An array to store the to-do items to be displayed in the UL element at line 13.
  • A function to add new items when I click the Add button at line 15.

Simple, right? Well, let’s create a new file called app.js and add the following code; I’ll explain it later:


First things first: let’s take a look at line 1. Before we start building controllers that handle UI logic, we need to create what is known as an AngularJS application module; this is done by calling the angular.module() function and passing it the module name, which returns the created module. This object will later be used as a container where you will store all of the controllers belonging to this particular JS App.

The variable angular is available after we included the AngularJS library in our HTML document at line 8.

After we create the application object, we can start creating controllers; being done in line 3 through the controller() function, which is now callable from the application module we created in line 1. This function takes two arguments: the name of the controller and a callback function that will be responsible of initializing the controller and which will be called each time a controller is instantiated by AngularJS. AngularJS also passes a special variable to that function called $scope; everything that is added to the $scope variable during controller initialization, will be accessible to the view for data binding; better said: it represents what the view can see.

The rest of the lines are quite self-explanatory:

  • Lines 7 to 11 adds a pre-initialized array of to-do items to the scope, that will be used as storage for new items. It represents the items that will be displayed in the empty UL element we have right now.
  • Line 13 declares a variable that will hold the description of new items to be added after the Add button is clicked.
  • Lines 17 to 21 define a function that will add new items to the to-do items array; this should be called each time the Add button is clicked.

Binding The View

Now that we have AngularJS, the application module and the to-do list controller, we are ready to start binding HTML elements in the view to the scope. But before that, we need to change our <html> tag a little and add some special AngularJS attributes:


Notice the ng-app attribute we added to the <html> tag; this is your first contact with one of the several directives that are part of the AngularJS data binding framework.

Directives are simply HTML element markers that are to be processed by the data binding engine. What does ng-app do? Well, it tells AngularJS which application module it should use for this HTML document; you might notice we specified ToDoListApp, which is the one we created in out app.js file at line 1.

After we associate our HTML document with the ToDoListApp, second step is to specify a controller for our view; this is done through the ng-controller directive. The ng-controller directive assigns a controller to a section of the HTML document; in other words, this is how we tell Angular where a view starts and when it ends.

Anyways, modify the <body> tag so it looks like this:


Same with the ng-app directive, the previous code tells AngularJS that everything inside the <body> tag will be governed by the ToDoListController, which we created in our app.js file at line 3.

Now we are ready to start binding elements to members added to the $scope variable during the ToDoListController controller initialization.

The ng-repeat Directive

Let’s start with the empty UL list element. In this case we want to create a new child LI element per item that is contained in the to-do items array. Let’s use the ng-repeat directive for this matter; add the following code inside the UL tags:


OK, hold on tight. The ng-repeat directive will repeat an element per item in an array used as data source; the quoted value represents the iterator expression, which defines the array to be iterated and an alias used to refer the current item being iterated.

In this case, we specified that it should repeat the LI element for all of the items in the items array defined in the $scope variable from line 7 through 11 in the app.js file.

Lastly, inside the LI tags we define an Angular template, which is an expression enclosed in double curly braces that will be compiled dynamically during run-time. In this case, the template is extracting a member named desc from each item and is going to display its value inside the LI tags being repeated.

Go ahead, save your files and open todolist.html in your preferred browser; you will see how the list gets filled. Awesome stuff, huh?

The ng-model Directive

Next in our list is the ng-model directive, which is used to bind the value of an input element, a text box, text area, option list, etc.; to a variable of the $scope. But before I give you more talk, change the input element at line 15:


Binding the value of an element means that each time the value of the input element changes, the variable specified in the ng-model directive will change with that value.

AngularJS enables two-way binding by default, meaning that if the value of the variable the input element is bound to changes, the change will be reflected in the input element on screen. This is the true magic of AngularJS: You can change the value of elements displayed on screen just by modifying values of the $scope variable; no need of selectors, no need to access the DOM from JavaScript, no need of extra code.

In this case, the input element has been bound to the newItemDescription variable of the $scope, defined at line 13 of the app.js file. Each time the value of the input element changes, the variable at the scope will be updated and viceversa.

The ng-click Directive

What if I want to do something when I click that? For that, AngularJS provides a bunch of event handler directives. These directives can be used to invoke functions defined on the $scope each time the user performs an action over an element.

The only one we are going to use for this example is the ng-click, which handles the user click on a button or input element; the expression it takes is basically the code to be executed on each click. In our case, we will modify the button element at line 15 and add the following directive:


If you look closely, we are telling AngularJS to call the addItem function defined in the $scope. If you see the code of that function from line 17 to 21, you will see that it adds a new item to the to-do list array, based on the value of the newItemDescription variable.

If you save your files and open todolist.html, you will see how the list is automatically updated each time you enter a new description in the text box and click on Add.

Your HTML document is dynamic and alive. How cool is that?

What Kind Of Sorcery Is This!?

OK, I must tell you that all of this does not happen through magic. AngularJS is what’s called an unobtrusive library; which means that everything happens automatically as soon as the library finishes loading.

At the very beginning, when the HTML document finished loading, AngularJS crawls through HTML document structure looking for ng-app directives which tells it that something has to be done there. After all of the directives have been found, the marked elements are processed separately: elements are bound to controllers and templates are compiled.

The $scope variable lifetime is automatically handled by AngularJS, each time something happens on-screen, it is notified and performs anything that has to be done to ensure the controller and view are synced; from updating values in the $scope bound to a particular element to refreshing an element or template. This is done through the implementation of some sort of the observable pattern that allows AngularJS to react to changes on elements and the $scope itself.


Woah! That was a bunch of stuff to digest. Hopefully, you will make sense out of it with some practice. Of course those three directives are not everything that there is on AngularJS; for a complete list on all of the possible directives you can use out-of-the-box, take a look here.

Have in mind that you can also extend the library with custom directives, but that is an advanced topic we might cover in a future article.

AngularJS is not everything there is about JS Apps, this was a very basic introduction and I want you to have knowledge you can use in real life, so we will be learning how to build more complex JS Apps in my next article. Topics to be covered will be:

  • Creating custom Angular directives.
  • Complex user interfaces (windows, redirection and data validation.)
  • RequireJS for on-demand asynchronous JavaScript files loading.

Hope that sounds exciting enough for you. Stay tuned! :D

Source Code

Further Reading

JSApps 101: Introduction To JavaScript Applications


So, JavaScript… Again! After some months away from this blog, I am back with a new series of articles related to the incredible, magical and mysterious world of JavaScript. More specifically, JavaScript applications. Have you ever heard of AngularJS, Backbone, Knockout JS, LESS and such things? Read on, this might interest you.

We have used, at some point of our Internet life, some awesome websites, such as Facebook, Github, Spotify, and others; where everything is asynchronous, the user interface is super-responsive and couldn’t be closer to a desktop application in matters of functionality, all of this right in our browser. Less that some people imagine is that these sites owe their slickness mainly to our good old friend in battle: JavaScript; oh so many developers underestimate JavaScript. This article series will dive you into the basis of how these kind of powerful JavaScript applications are built and over what technologies and frameworks, so let’s move forward into some basic concepts.

Server-side v.s. Client-side

So, what in the world is a JavaScript application anyways? Well, as you might know, the traditional way a web application works is that you have a set of specialized frameworks and tools (name it ASP.NET, PHP, Spring Framework) running server-side; when someone requests a page from the server, it responds with an HTML document, usually resulting of the parsing of a server-side template (a PHP, ASPX or the alike) and then bound to data coming from the database. Those templates being processed by the server usually contain special syntax and directives that instructs the server’s templating engine how to bind data to it and produce a valid HTML document; some might recall these as the dreaded “server tags.”

Standard Server Request/Response


Some server-side technologies like ASP.NET use “controls” or helpers that assist in the rendering of complex user interface components into HTML like grids, forms and charts bound to dynamic data coming from the database. Each time these components need to be refreshed, they do it through asynchronous AJAX requests or a full-page refresh (known as a server post-back, which all users love, or not). While these are handy for speed-building of web solutions, is not as efficient as pure-JavaScript graphical components.

ASP.NET WebControls

Often, JavaScript is used to manipulate the structure of the resulting HTML document, get the value of a field, and other simple tasks dynamically on the browser (better known as “the client side”) without the need of refreshing the page. But as popularity of JavaScript arise (let’s thank jQuery for that), it is being delegated with more and more complex stuff like rendering templates into HTML, so it is done client-side and not server-side; binding of server data, validation of user input and controlling page flow. This being said, a JavaScript application is basically a “client” that runs on the browser, thanks to the leverage of technologies such as JavaScript, HTML5 and CSS3. All of the UI logic is controlled client-side, right there in the browser.

Structure of a JavaScript App

Before moving on, it is true that this requires a paradigm shift if you have been working on traditional web applications for a while, specially if you have never used a Model-View-Controller approach. If you have never heard of, or used Model-View-Controller, I’m afraid there is some reading to be done before continuing. But hey! You can start here, or else you can continue reading this incredibly sexy article.

As mentioned before, a JavaScript application, or JS App (patent pending), usually follows an MVC approach. It is composed of several “views”, which are usually HTML documents or templates; “controllers” that handles validation, logic flow and communications with the server; and “models” that contains the data to be displayed and bind on the views. As you might notice, is a pretty similar model to server-side technologies like ASP.NET MVC and Spring MVC, just that the entire presentation layer is being moved to the browser, specifically into JavaScript components. We’ll analyze advantages of this later on.

With all the presentation logic being handled by the browser, where does the data we see on the UI coming from? It comes from the server; that is the real use we have for it. The controller at the browser is the one responsible for this channel of communication; it retrieves data from the server each time the user pages through a data grid and sends data to it whenever the user needs to create or edit information. JS Apps work in a similar way to smartphone apps, in which a client runs on the phone locally and it uses data coming from a remote server. In fact, there are specialized build tools, like PhoneGap, that creates applications to be installed on a smartphone from HTML/JS/CSS3 sources.

JS App Structure

Pros & Cons

While JS Apps goes far off any conventional use of a browser, it offers several advantages:

  • Rendering of pages and templates is done by the browser in the client computer, taking advantage of the client computer’s processing power and leaving less workload on the server.
  • Better user interface responsiveness, since all calls to the server are asynchronously and JavaScript UI components are usually lightweight.
  • Completely decoupled from the server logic.
  • Less calls to the server, since it is only accessed to get data and not pages in every possible display state it might have.
  • High separation of concerns, since the server ONLY handles business logic and not UI-related validation and such.
  • Easy unit testing of the user interface and UI logic.

Also, it might represent some disadvantages:

  • Lots, lots and LOTS of JavaScript to be written; we all know it can be a pain to maintain if not properly done.
  • The learning curve is quite step, since most people is used to jQuery and DOM manipulation but not to JavaScript controllers, models and pseudo-classes; let alone advanced concepts like JavaScript dependency injection.
  • Data incoming to the server needs to be double-checked in order to prevent bad information sent by tampered JavaScript components.

Sounds Kind of Interesting, Now What?

OK, now that you might get the picture of what a JS App might look like and its advantages, so the next step would be to analyze the technologies and frameworks you could use, getting your hands dirty along the way so you can start developing this kind of applications.

In the following articles we will move into learning JavaScript libraries like AngularJS, for client-side Model-View-Controller; RequireJS, a library that allows asynchronous loading of JavaScript files on-demand; usage of Twitter Bootstrap, to build nice HTML5-compliant user interfaces; and ultimately how to structure your server application as a solid data provider for your JavaScript application.

So, stay tuned for more articles! :D


Why There Is Interface Pollution in Java 8

Edwin DalorzoI was reading this interesting post about The Dark Side of Java 8. In it, Lukas Eder, the author, mentions how bad it is that in the JDK 8 the types are not simply called functions. For instance, in a language like C#, there is a set of predefined function types accepting any number of arguments with an optional return type (Func and Action each one going up to 16 parameters of different types T1, T2, T3, …, T16), but in the JDK 8 what we have is a set of different functional interfaces, with different names and different method names, and whose abstract methods represent a subset of well know function signatures/function arities (i.e. nullary, unary, binary, ternary, etc).

The Type Erasure Issue

So, in a way, both languages suffer from some form of interface pollution (or delegate pollution in C#). The only difference is that in C# they all have the same name. In Java, unfortunately, due to type erasure, there is no difference between Function<T1,T2> and Function<T1,T2,T3> or Function<T1,T2,T3,...Tn>, so evidently, we couldn’t simply name them all the same way and we had to come up with creative names for all possible types of function combinations.

Don’t think the expert group did not struggle with this problem. In the words of Brian Goetz in the lambda mailing list:

[…] As a single example, let’s take function types. The lambda strawman offered at devoxx had function types. I insisted we remove them, and this made me unpopular. But my objection to function types was not that I don’t like function types — I love function types — but that function types fought badly with an existing aspect of the Java type system, erasure. Erased function types are the worst of both worlds. So we removed this from the design.

But I am unwilling to say “Java never will have function types” (though I recognize that Java may never have function types.) I believe that in order to get to function types, we have to first deal with erasure. That may, or may not be possible. But in a world of reified structural types, function types start to make a lot more sense […]

So, how does this affect us as developers? The following is a categorization of some of the most important new functional interfaces (and some old ones) in the JDK 8 organized by function return type and the number of expected arguments in the interface method.

Functions with Void Return Type

In the realm of functions with a void return type, we have the following:

Type of Function Lambda Expression Known Functional Interfaces
				() -> doSomething()
				foo  -> System.out.println(foo)
				(console,text) -> console.print(text)
				(sender,host,text) -> sender.send(host, text)
Define your own

Functions with Some Return Type T

In the realm of functions with a return type T, we have the following:

Type of Function Lambda Expression Known Functional Interfaces
				() -> "Hello World"
				n -> n + 1
				n -> n >= 0
				(a,b) -> a > b ? 1 : 0
				(x,y) -> x + y
				(x,y) -> x % y == 0
				(x,y,z) -> 2 * x + Math.sqrt(y) - z
Define your own

An advantage of this approach is that we can define our own interface types with methods accepting as many arguments as we would like, and we could use them to create lambda expressions and method references as we see fit. In other words, we have the power to pollute the world with yet even more new functional interfaces. Also we can create lambda expressions even for interfaces in earlier versions of the JDK or for earlier versions of our own APIs that defined SAM types like these. And so now we have the power to use Runnable and Callable as functional interfaces.

However, these interfaces become more difficult to memorize since they all have different names and methods.

Still, I am one of those wondering why they didn’t solve the problem as in Scala, defining interfaces like Function0, Function1, Function2, …, FunctionN. Perhaps, the only argument I can come up with against that is that they wanted to maximize the possibilities of defining lambda expressions for interfaces in earlier versions of the APIs as mentioned before.

Lack of Value Types

So, evidently type erasure is one driving force here. But if you are one of those wondering why we also need all these additional functional interfaces with similar names and method signatures and whose only difference is the use of a primitive type, then let me remind you that in Java we also lack of value types like those in a language like C#. This means that the generic types used in our generic classes can only be reference types, and not primitive types.

In other words, we can’t do this:

List<int> numbers = asList(1,2,3,4,5);

But we can indeed do this:

List<Integer> numbers = asList(1,2,3,4,5);

The second example, though, incurs in the cost of boxing and unboxing of the wrapped objects back and forth from/to primitive types. This can become really expensive in operations dealing with collections of primitive values. So, the expert group decided to create this explosion of interfaces to deal with the different scenarios. To make things “less worse” they decided to only deal with three basic types: int, long and double.

Quoting the words of Brian Goetz in the lambda mailing list:

More generally: the philosophy behind having specialized primitive streams (e.g., IntStream) is fraught with nasty tradeoffs. On the one hand, it’s lots of ugly code duplication, interface pollution, etc. On the other hand, any kind of arithmetic on boxed ops sucks, and having no story for reducing over ints would be terrible. So we’re in a tough corner, and we’re trying to not make it worse.

Trick #1 for not making it worse is: we’re not doing all eight primitive types. We’re doing int, long, and double; all the others could be simulated by these. Arguably we could get rid of int too, but we don’t think most Java developers are ready for that. Yes, there will be calls for Character, and the answer is “stick it in an int.” (Each specialization is projected to ~100K to the JRE footprint.)

Trick #2 is: we’re using primitive streams to expose things that are best done in the primitive domain (sorting, reduction) but not trying to duplicate everything you can do in the boxed domain. For example, there’s no IntStream.into(), as Aleksey points out. (If there were, the next question(s) would be “Where is IntCollection? IntArrayList? IntConcurrentSkipListMap?) The intention is many streams may start as reference streams and end up as primitive streams, but not vice versa. That’s OK, and that reduces the number of conversions needed (e.g., no overload of map for int -> T, no specialization of Function for int -> T, etc.)

We can see that this was a difficult decision for the expert group. I think few would agree that this is cool, and most of us would most likely agree it was necessary.

The Checked Exceptions Issue

There was a third driving force that could have made things even worse, and it is the fact that Java supports two type of exceptions: checked and unchecked. The compiler requires that we handle or explicitly declare checked exceptions, but it requires nothing for unchecked ones. So, this creates an interesting problem, because the method signatures of most of the functional interfaces do not declare to throw any exceptions. So, for instance, this is not possible:

Writer out = new StringWriter();
Consumer<String> printer = s -> out.write(s); //oops! compiler error

It cannot be done because the write operation throws a checked exception (i.e. IOException) but the signature of the Consumer method does not declare it throws any exception at all. So, the only solution to this problem would have been to create even more interfaces, some declaring exceptions and some not (or come up with yet another mechanism at the language level for exception transparency). Again, to make things “less worse” the expert group decided to do nothing in this case.

In the words of Brian Goetz in the lambda mailing list:

Yes, you’d have to provide your own exceptional SAMs. But then lambda conversion would work fine with them.

The EG discussed additional language and library support for this problem, and in the end felt that this was a bad cost/benefit tradeoff.

Library-based solutions cause a 2x explosion in SAM types (exceptional vs not), which interact badly with existing combinatorial explosions for primitive specialization.

The available language-based solutions were losers from a complexity/value tradeoff. Though there are some alternative solutions we are going to continue to explore — though clearly not for 8 and probably not for 9 either.

In the meantime, you have the tools to do what you want. I get that you prefer we provide that last mile for you (and, secondarily, your request is really a thinly-veiled request for “why don’t you just give up on checked exceptions already”), but I think the current state lets you get your job done.

So, it’s up to us, the developers, to craft yet even more interface explosions to deal with these in a case-by-case basis:

interface IOConsumer<T> {
   void accept(T t) throws IOException;

static<T> Consumer<T> exceptionWrappingBlock(IOConsumer<T> b) {
   return e -> {
	try { b.accept(e); }
	catch (Exception ex) { throw new RuntimeException(ex); }

In order to do:

Writer out = new StringWriter();
Consumer<String> printer = exceptionWrappingBlock(s -> out.write(s));

Probably, in the future (maybe JDK 9) when we get Support for Value Types in Java and Reification, we will be able to get rid of (or at least no longer need to use anymore) these multiple interfaces.

In summary, we can see that the expert group struggled with several design issues. The need, requirement or constraint to keep backwards compatibility made things difficult, then we have other important conditions like the lack of value types, type erasure and checked exceptions. If Java had the first and lacked of the other two the design of JDK 8 would probably have been different. So, we all must understand that these were difficult problems with lots of tradeoffs and the EG had to draw a line somewhere and make a decisions.

So, when we find ourselves in the dark side of Java 8, probably we need to remind ourselves that there is a reason why things are dark in that side of the JDK :-)

Further Reading

  • Related Answer in Stackoverflow
  • Lambda Straw-Man Proposal
  • Neal Gafter on The Future of Java
  • 6 Days with Windows Phone

    Disclaimer: What follows is my personal opinion, it does not reflect Informatech’s position necessarily. Though I’ve tried to be as unbiased as possible, it will undoubtedly reflect my views.

    A friend upgrades to a Lumia 920 and a Lumia 900 is left orphaned.

    With a Galaxy Nexus experiment going on since Oct 2012, and waiting for Apple’s comeback iOS 7 (plus whatever they introduce later this year), I dive in for a week to see how the Windows Phone 7.8 experience stacks up.


    I hail from a background of Apple devices, at least for a couple of years now (I had Nokia smartphones before). I’ve been exploring Android, if anything because as a developer it’s unforgivable not to have any experience in it, but customizability is not something that drives my purchases.

    Beyond specific OS choices, I believe in finished, polished products. I dislike having to hack or otherwise mod my devices. Yep, that includes spending hours tweaking and configuring.

    I like my stuff to just work, with minimal fuss. Things can be technologically interesting, but in a device I want a product. That said, let’s delve in.

    The Experience

    2013-06-10 10.54.522013-06-10 10.55.03

    What do I usually do in a smartphone (that will thus dictate the experience on Windows Phone)? Pretty much WhatsApp, Facebook, push Gmail, push Google Contacts, camera, and Dropbox auto photo uploads. Yes, other things matter, but that’s what realistically I use most of the time, and will be the scope of this review.

    So let’s not waste too much time discussing setup (which is generally polished), suffice it to say that of the above:

    • WhatsApp and Facebook were installed from the Marketplace.
    • Camera is good, but there is no official Dropbox support. I routed around this by enabling SkyDrive auto uploads, so no biggie.
    • When setting up the Google account, we hit our first snag. Because Google discontinued ActiveSync, the only straightforward choice is IMAP setup just for email, no calendar or contacts. Fortunately you can add Gmail as an Exchange server manually through the end of July. This worked OK, but the contact import was kinda crappy (ie. contacts with multiple numbers, just had the first imported).

    Once everything was working, it took me about a day to get used to the concept of Live Tiles. That is the driver of the Windows Phone UI, where you’ll launch apps, get notifications, and see periodic content changes of relevant content. The idea is novel and elegantly implemented, and after months on Android, it made me feel that special care had been taken in the consistency and polish of the interface. Both were very much welcome.

    In full day-to-day usage, the UI shines, though where I felt the most joy was in the touch keyboard. It is absolutely a pleasure to use (no gestures or swipes, straight taps), and by far it’s the best of any smartphone that I’ve used.

    The camera was another pleasant surprise. The capture and photo browser were excellent, behold:


    The multitasking also requires a bit of getting used to, as a long press of the back key will allow you to get an open app list, however it will not let you kill any. You have to jump in, and continually press back until you exit.

    To finish off the “stock” functionality, the People hub was generally useful (even though the Google contacts were indeed not wholly sync’d). It gave quick access to recent contacts, and integrated well with social networks.

    Even though Facebook is integrated in, the way to properly see your Newsfeed is through the standalone app. Which sadly is not developed by FB, and is quite honestly sub par to similar offerings on iOS and Android.

    WhatsApp was a similar story, the implementation is not up to par with the other platforms, and more annoyingly it activated the music controls and gobbled battery. As a workaround, you have to download a separate app that kills the music controls, and run it periodically. The app also seemed to implode under heavily used group chats.

    Even with the mediocrity of third-party apps, I can honestly say the OS is pleasant to use, and the tiles are colorful and attractive. So rounding out:


    • Superb interface, extremely polished.
    • Quite simply the best touch keyboard I’ve ever used, on any smartphone.
    • Integration between social networks and contacts is almost seamless.
    • Excellent camera.
    • Lumia hardware is very capable and attractive.
    • Integration with Microsoft services is predictably good.


    • Synchronization with Google services is poor (especially now that ActiveSync was retired).
    • App selection and most importantly, quality, is low, low, low. Years behind iOS and Android.
    • WhatsApp drains the battery, and requires “Stop the Music” to kill it every once in a while.
    • Multitasking does not allow you close the application from the app list (WP 7.8?)
    • Lack of a centralized notification area is confusing.


    If you’re a Hotmail user, and you live your life in Exchange and Microsoft Office, Windows Phone is a natural fit. The Lumia hardware is capable and attractive, the UI is very polished, and if you can live with the poor app selection and quality, you’ll enjoy it.

    However if you use Google services, and have gotten used to the abundance of other app stores, the UI may not compensate the tradeoffs for functionality you would have to give up. In the future this may change, but at present it’s too much to take.