Tuesday, November 26, 2013

The Habits Of Successful New Web Professionals

Starting a position in an organization, especially if it is your first in the industry, can be as nerve-wracking as it is exciting. Practices that seem like common sense to those of us who have been in the Web industry for some time might not be as obvious to designers and developers without the benefit of our experience.
Part of our responsibility as veterans in this industry is to mentor new team members and share with them the knowledge that we know they will need to succeed.
The expert in anything was once a beginner.
As President Rutherford B. Hayes once said, “The expert in anything was once a beginner.” (Image source: opensourceway)
 As a follow-up to that piece, this one looks at the other side of the team leader-new employee dynamic. We’ll cover the practices that I have found are consistently followed by employees who excel in their new role and grow in this industry.

Embrace The Company’s Culture

Every company is different — with policies, procedures and a culture unique to it. While much attention is given to ensuring that new employees understand these policies and procedures, understanding and embracing the company’s culture is just as important to long-term success. One way to embrace a company’s culture is to get involved — both in and outside the office.
If your company is holding an event or activity for employees, make it a point to attend. It could be a full-blown company party or a small after-hours get-together of only a few employees. Either way, it provides an opportunity to socialize with your new colleagues and begin to build relationships with the people you work alongside.
In the office, look for projects that interest you and that you feel you can contribute positively to. These could be normal client engagements or even side projects driven by small teams in the organization. By asking to be included in these projects, you’ll get time to work hands on with your colleagues and show them the value you bring to the team.
Now, the challenge to participating in these activities is that new employees often feel like outsiders, and many are reluctant to join in on the company’s planned events. The irony, though, is that participating in these company events is one of the best ways to feel like part of the team and to break down that outsider status.

Respect The Client

Complaining about clients is a practice that has been around as long as clients themselves, but it has no place in the Web industry, whether you are a new professional or a seasoned veteran.
Clients can be challenging, but remember that when they stop calling you with questions or with work to be done, that is the day you no longer have a job. We are here because of our clients, not in spite of them.
Does this mean that the client is always right and that you should take whatever they dish out at you with a smile and a nod? Of course not. No one should ever suffer a client who disrespects them professionally or personally, but an abusive client who must be fired is very different from one who simply asks a lot of questions because they recognize that you are the expert. Yes, clients make poor decisions at times, and some of their questions will seem obvious or silly to you, but your answers and advice are why they hired you in the first place.
Respect clients — they keep you employed — and refrain from the bouts of unnecessary complaining that others in the organization might engage in. If others are complaining and trying to rope you in, politely excuse yourself. Nothing good will come of those negative conversations.

Ask Questions

As a new employee, you will undoubtedly have questions — a lot, in fact. That is OK. In fact, it is expected. You might feel like you are bothering others, but asking questions is how you learn and how “tribal knowledge” is passed from veterans in an organization to newcomers.
When you join, a company will likely give you some kind of orientation and show you the ropes, but only so much information can be conveyed in an orientation or in training. So much of what you will need to know is picked up on the job, by actually doing the work itself. When you hit a roadblock, look to others on the team for help. They will often have encountered the issue before and have set a precedent for dealing with it — the aforementioned tribal knowledge. Gaining that knowledge through experience and by asking questions is how you will grow in the organization.
It is OK to ask questions but be sure to try to solve the issue first
Asking questions enables you to learn and acquire team knowledge, but try to solve problems for yourself first. (Image source: Tim O’Brien)
Now, there is a balance to be struck. Throwing your hands in the air and yelling “Mayday!” every time you hit a bump in the road is too much. Try to solve a problem for yourself first, so that when you ask for help, you can show the person what you’ve tried so far. Over time, you will find the balance between exploring solutions on your own and asking for a hand.

Teach Me Something

I am constantly reading articles with new tips, techniques and best practices in our industry, and I spend many nights and weekends outside of normal office hours working to master these new techniques. When I discover an article or idea that I think is valuable, I always share it with the rest of my team. And I love it when others on the team return the favor.
When a new employee shares a worthwhile article or an approach that I had not considered, they demonstrate their passion and their dedication to growing in the industry. It also shows that they are willing not only to learn, but also to teach others.

Check Your Work

I appreciate when a team member completes a task quickly, but speed doesn’t trump accuracy. Too often, in an attempt to impress their manager, new team members will race through a task to show how efficient they are. They submit work before really going over it to make sure that all of the tasks have been completed correctly.
Checking your work before submitting it to a manager for review probably sounds like common sense, but it’s one of the biggest problems I hear about from other team leaders and managers. Work that is missing key elements or that has little errors (spelling mistakes are common) or whose functionality hasn’t been fully tested (broken links, forms that do not submit properly, etc.) are major headaches for many team leaders. A manager would rather the person finish the task a bit more slowly if the bulk of the errors could have been caught by a more thorough review.
Before you submit work as being complete, give it a once over to make sure that everything works as intended.

Mind The Clock

Web design is not a 9:00 to 5:00 job. Sometimes, inspiration or a breakthrough strikes at the end of the day. If you punch the clock exactly at 5:00, you could lose any momentum or spark of creativity you may have had, when instead you should nurture the moment. Other times, a deadline is looming that requires extra hours in the office. You need to accept that the day doesn’t always end at 5:00.
It goes both ways, though. An employee who is willing to stay late and put in extra effort when needed will be recognized and appreciated, but don’t stay at your desk 12 hours a day, only to go home and do more work there.
Working late every night will not allow you to properly balance work and life
Minding the clock means not working late every night. (Image source: abdallahh)
Minding the clock means balancing your professional and personal time. Don’t burn yourself out by trying to be a superhero who does nothing but work. The most successful colleagues I have worked with over the years have found and maintained a work-life balance.

Work On Your Communication Skills

Responding to questions and requests from clients can be a full-time job. In fact, on some days I feel like all I’ve done is answer emails. Managers want to be able to offload some communication responsibilities to others on the team — but they need to know that the communication will not suffer from a lack of skill.
Whether you are answering questions from clients, presenting design concepts in a meeting or brainstorming with colleagues, communicating your ideas in a way that meets your company’s expectations is important. This skill will increase your value to the team and set you up to take on more responsibility.

Join The Community

The Web community is amazing, and you can participate in it in a number of ways. Depending on where you live, you might have access to meetups, networking events, conferences and other gatherings. We all have opportunities to share our experience, knowledge and passion for this industry.
Participating in these events will make you feel like a part of the Web community, help you make connections with peers and reflect well on your company. With limited time to attend such events, leaders appreciate when other team members take the initiative to get out in the community and represent the company.

Stay Positive

This tip might sound easy to follow, but keeping a positive attitude and demeanor is more challenging than it seems.
As a new team member, you will undoubtedly have times when you are unsure of what to work on next or of how you are performing. This uncertainly can be stressful, and stress can eventually lead to a negative attitude. Fight the urge to give into that negativity — stay positive.
Saying that everything is easier with a positive attitude might sound like an oversimplification, but it’s not. A positive attitude makes challenges easier to face, and it encourages others to come to your aid. After all, no one is excited to work with someone with a negative attitude.

Have Fun

Many years ago, I had an employer who, whenever my job got stressful or challenging, would say, “Well, that’s why we pay you to be here. If it was fun, it wouldn’t be work!”
I don’t agree with this sentiment. Yes, most of us wouldn’t show up for work every day if a pay check wasn’t waiting for us at the end of the week. However, just because we have to work doesn’t mean we can’t enjoy where we work.
The most successful employees I have had the pleasure of working alongside over the years have enjoyed their job and where they work. Life is too short for anything else. So, have fun at your job — and if you can’t, consider getting another.
Staying positive and having fun at your job are two overlooked yet incredibly important elements of success.
Staying positive and having fun at your job are two overlooked yet incredibly important elements of success. (Image source: opensourceway)

In Summary

Joining an organization can be stressful. Hopefully, the tips presented here will help you make the most of the opportunity and relieve a bit of the stress. Here are the do’s and don’ts we’ve covered:
  • Do embrace the culture, and participate in company events.
  • Do not let the feeling of being a newbie keep you from participating in events.
  • Do not engage in pointless complaining about clients.
  • Do respect your clients and recognize that they are the reason you have a job.
  • Do not be afraid to ask questions; that’s how you learn.
  • Do try to solve problems on your own before asking for help.
  • Do share helpful or interesting articles that you come across.
  • Do not submit work before having checked it for accuracy.
  • Do strike a balance between your professional and personal time.
  • Do work on your communication skills, and understand what the company expects from your communication with clients.
  • Do look for opportunities to participate in your local Web community.
  • Do stay positive, even when you feel uncertain or stressed out.
  • Do have fun at your job and enjoy where you work.

Monday, November 25, 2013

An Introduction To Full-Stack JavaScript

Nowadays, with any Web app you build, you have dozens of architectural decisions to make. And you want to make the right ones: You want to use technologies that allow for rapid development, constant iteration, maximal efficiency, speed, robustness and more. You want to be lean and you want to be agile. You want to use technologies that will help you succeed in the short and long term. And those technologies are not always easy to pick out.
In my experience, full-stack JavaScript hits all the marks. You’ve probably seen it around; perhaps you’ve considered its usefulness and even debated it with friends. But have you tried it yourself? In this post, I’ll give you an overview of why full-stack JavaScript might be right for you and how it works its magic.
To give you a quick preview:
toptal-blog-500-opt
(Large view)
I’ll introduce these components piece by piece. But first, a short note on how we got to where we are today.

Why I Use JavaScript

I’ve been a Web developer since 1998. Back then, we used Perl for most of our server-side development; but even since then, we’ve had JavaScript on the client side. Web server technologies have changed immensely since then: We went through wave after wave of languages and technologies, such as PHP, ASP, JSP, .NET, Ruby, Python, just to name a few. Developers began to realize that using two different languages for the client and server environments complicates things.
In the early era of PHP and ASP, when template engines were just an idea, developers embedded application code in their HTML. Seeing embedded scripts like this was not uncommon:
<script>
    <?php
        if ($login == true){
    ?>
    alert("Welcome");
    <?php
        }
    ?>
</script>
Or, even worse:
<script>
    var users_deleted = [];
    <?php
        $arr_ids = array(1,2,3,4);
        foreach($arr_ids as $value){
    ?>
    users_deleted.push("<php>");
    <?php
        }
    ?>
</script>
For starters, there were the typical errors and confusing statements between languages, such as for and foreach. Furthermore, writing code like this on the server and on the client to handle the same data structure is uncomfortable even today (unless, of course, you have a development team with engineers dedicated to the front end and engineers for the back end — but even if they can share information, they wouldn’t be able to collaborate on each other’s code):
<?php
    $arr = array("apples", "bananas", "oranges", "strawberries"),
    $obj = array();
    $i = 10;
    foreach($arr as $fruit){
        $obj[$fruit] = $i;
        $i += 10;
    }
    echo json_encode(obj);
?>
<script>
    $.ajax({
        url:"/json.php",
        success: function(data){
            var x;
            for(x in data){
                alert("fruit:" + x + " points:" + data[x]);
            }
        }
    });
</script>
The initial attempts to unify under a single language were to create client components on the server and compile them to JavaScript. This didn’t work as expected, and most of those projects failed (for example, ASP MVC replacing ASP.NET Web forms, and GWT arguably being replaced in the near future by Polymer). But the idea was great, in essence: a single language on the client and the server, enabling us to reuse components and resources (and this is the keyword: resources).
The answer was simple: Put JavaScript on the server.
JavaScript was actually born server-side in Netscape Enterprise Server, but the language simply wasn’t ready at the time. After years of trial and error, Node.js finally emerged, which not only put JavaScript on the server, but also promoted the idea of non-blocking programming, bringing it from the world of nginx, thanks to the Node creator’s nginx background, and (wisely) keeping it simple, thanks to JavaScript’s event-loop nature.
(In a sentence, non-blocking programming aims to put time-consuming tasks off to the side, usually by specifying what should be done when these tasks are completed, and allowing the processor to handle other requests in the meantime.)
Node.js changed the way we handle I/O access forever. As Web developers, we were used to the following lines when accessing databases (I/O):
var resultset = db.query("SELECT * FROM 'table'");
drawTable(resultset);
This line essentially blocks your code, because your program stops running until your database driver has a resultset to return. In the meantime, your platform’s infrastructure provides the means for concurrency, usually using threads and forks.
With Node.js and non-blocking programming, we’re given more control over program flow. Now (even if you still have parallel execution hidden by your database (I/O) driver), you can define what the program should do in the meantime and what it will do when you receive the resultset:
db.query("SELECT * FROM 'table'", function(resultset){
   drawTable(resultset);
});
doSomeThingElse();
With this snippet, we’ve defined two program flows: The first handles our actions just after sending the database query, while the second handles our actions just after we receive our resultSet using a simple callback. This is an elegant and powerful way to manage concurrency. As they say, “Everything runs in parallel — except your code.” Thus, your code will be easy to write, read, understand and maintain, all without your losing control over program flow.
These ideas weren’t new at the time — so, why did they become so popular with Node.js? Simple: Non-blocking programming can be achieved in several ways. Perhaps the easiest is to use callbacks and an event loop. In most languages, that’s not an easy task: While callbacks are a common feature in some other languages, an event loop is not, and you’ll often find yourself grappling with external libraries (for example, Python with Tornado).
But in JavaScript, callbacks are built into the language, as is the event loop, and almost every programmer who has even dabbled in JavaScript is familiar with them (or at least has used them, even if they don’t quite understand what the event loop is). Suddenly, every startup on Earth could reuse developers (i.e. resources) on both the client and server side, solving the “Python Guru Needed” job posting problem.
So, now we have an incredibly fast platform (thanks to non-blocking programming), with a programming language that’s incredibly easy to use (thanks to JavaScript). But is it enough? Will it last? I’m sure JavaScript will have an important place in the future. Let me tell you why.

Functional Programming

JavaScript was the first programming language to bring the functional paradigm to the masses (of course, Lisp came first, but most programmers have never built a production-ready application using it). Lisp and Self, Javascript’s main influences, are full of innovative ideas that can free our minds to explore new techniques, patterns and paradigms. And they all carry over to JavaScript. Take a look at monads, Church numbers or even (for a more practical example) Underscore’s collections functions, which can save you lines and lines of code.

Dynamic Objects and Prototypal Inheritance

Object-oriented programming without classes (and without endless hierarchies of classes) allows for fast development — just create objects, add methods and use them. More importantly, it reduces refactoring time during maintenance tasks by enabling the programmer to modify instances of objects, instead of classes. This speed and flexibility pave the way for rapid development.

JavaScript Is the Internet

JavaScript was designed for the Internet. It’s been here since the beginning, and it’s not going away. All attempts to destroy it have failed; recall, for instance, the downfall of Java Applets, VBScript’s replacement by Microsoft’s TypeScript (which compiles to JavaScript), and Flash’s demise at the hands of the mobile market and HTML5. Replacing JavaScript without breaking millions of Web pages is impossible, so our goal going forward should be to improve it. And no one is better suited for the job than Technical Committee 39 of ECMA.
Sure, alternatives to JavaScript are born every day, like CoffeeScript, TypeScript and the millions of languages that compile to JavaScript. These alternatives might be useful for development stages (via source maps), but they will fail to supplant JavaScript in the long run for two reasons: Their communities will never be bigger, and their best features will be adopted by ECMAScript (i.e. JavaScript). JavaScript is not an assembly language: It’s a high-level programming language with source code that you can understand — so, you should understand it.

End-to-End JavaScript: Node.js And MongoDB

We’ve covered the reasons to use JavaScript. Next, we’ll look at JavaScript as a reason to use Node.js and MongoDB.

Node.js

Node.js is a platform for building fast and scalable network applications — that’s pretty much what the Node.js website says. But Node.js is more than that: It’s the hottest JavaScript runtime environment around right now, used by a ton of applications and libraries — even browser libraries are now running on Node.js. More importantly, this fast server-side execution allows developers to focus on more complex problems, such as Natural for natural language processing. Even if you don’t plan to write your main server application with Node.js, you can use tools built on top of Node.js to improve your development process; for example, Bower for front-end package management, Mocha for unit testing, Grunt for automated build tasks and even Brackets for full-text code editing.
So, if you’re going to write JavaScript applications for the server or the client, you should become familiar with Node.js, because you will need it daily. Some interesting alternatives exist, but none have even 10% of Node.js’ community.

MongoDB

MongoDB is a NoSQL document-based database that uses JavaScript as its query language (but is not written in JavaScript), thus completing our end-to-end JavaScript platform. But that’s not even the main reason to choose this database.
MongoDB is schema-less, enabling you to persist objects in a flexible way and, thus, adapt quickly to changes in requirements. Plus, it’s highly scalable and based on map-reduce, making it suitable for big data applications. MongoDB is so flexible that it can be used as a schema-less document database, a relational data store (although it lacks transactions, which can only be emulated) and even as a key-value store for caching responses, like Memcached and Redis.

Server Componentization With Express

Server-side componentization is never easy. But with Express (and Connect) came the idea of “middleware.” In my opinion, middleware is the best way to define components on the server. If you want to compare it to a known pattern, it’s pretty close to pipes and filters.
The basic idea is that your component is part of a pipeline. The pipeline processes a request (i.e. the input) and generates a response (i.e. the output), but your component isn’t responsible for the entire response. Instead, it modifies only what it needs to and then delegates to the next piece in the pipeline. When the last piece of the pipeline finishes processing, the response is sent back to the client.
We refer to these pieces of the pipeline as middleware. Clearly, we can create two kinds of middleware:
  • Intermediates
    An intermediate processes the request and the response but is not fully responsible for the response itself and so delegates to the next middleware.
  • Finals
    A final has full responsibility over the final response. It processes and modifies the request and the response but doesn’t need to delegate to the next middleware. In practice, delegating to the next middleware anyway will allow for architectural flexibility (i.e. for adding more middleware later), even if that middleware doesn’t exist (in which case, the response would go straight to the client).
user-manager-500-opt
(Large view)
As a concrete example, consider a “user manager” component on the server. In terms of middleware, we’d have both finals and intermediates. For our finals, we’d have such features as creating a user and listing users. But before we can perform those actions, we need our intermediates for authentication (because we don’t want unauthenticated requests coming in and creating users). Once we’ve created these authentication intermediates, we can just plug them in anywhere that we want to turn a previously unauthenticated feature into an authenticated feature.

Single-Page Applications

When working with full-stack JavaScript, you’ll often focus on creating single-page applications (SPAs). Most Web developers are tempted more than once to try their hand at SPAs. I’ve built several (mostly proprietary), and I believe that they are simply the future of Web applications. Have you ever compared an SPA to a regular Web app on a mobile connection? The difference in responsiveness is in the order of tens of seconds.
(Note: Others might disagree with me. Twitter, for example, rolled back its SPA approach. Meanwhile, large websites such as Zendesk are moving towards it. I’ve seen enough evidence of the benefits of SPAs to believe in them, but experiences vary.)
If SPAs are so great, why build your product in a legacy form? A common argument I hear is that people are worried about SEO. But if you handle things correctly, this shouldn’t be an issue: You can take different approaches, from using a headless browser (such as PhantomJS) to render the HTML when a Web crawler is detected to performing server-side rendering with the help of existing frameworks.

Client Side MV* With Backbone.js, Marionette And Twitter Bootstrap

Much has been said about MV* frameworks for SPAs. It’s a tough choice, but I’d say that the top three are Backbone.js, Ember and AngularJS.
All three are very well regarded. But which is best for you?
Unfortunately, I must admit that I have limited experience with AngularJS, so I’ll leave it out of the discussion. Now, Ember and Backbone.js represent two different ways of attacking the same problem.
Backbone.js is minimal and offers just enough for you to create a simple SPA. Ember, on the other hand, is a complete and professional framework for creating SPAs. It has more bells and whistles, but also a steeper learning curve. (You can read more about Ember.js here.)
Depending on the size of your application, the decision could be as easy as looking at the “features used” to “features available” ratio, which will give you a big hint.
Styling is a challenge as well, but again, we can count on frameworks to bail us out. For CSS, Twitter Bootstrap is a good choice because it offers a complete set of styles that are both ready to use out of the box and easy to customize.
Bootstrap was created in the LESS language, and it’s open source, so we can modify it if need be. It comes with a ton of UX controls that are well documented. Plus, a customization model enables you to create your own. It is definitely the right tool for the job.

Best Practices: Grunt, Mocha, Chai, RequireJS and CoverJS

Finally, we should define some best practices, as well as mention how to implement and maintain them. Typically, my solution centers on several tools, which themselves are based on Node.js.

Mocha and Chai

These tools enable you to improve your development process by applying test-driven development (TDD) or behavior-driven development (BDD), creating the infrastructure to organize your unit tests and a runner to automatically run them.
Plenty of unit test frameworks exist for JavaScript. Why use Mocha? The short answer is that it’s flexible and complete.
The long answer is that it has two important features (interfaces and reporters) and one significant absence (assertions). Allow me to explain:
  • Interfaces
    Maybe you’re used to TDD concepts of suites and unit tests, or perhaps you prefer BDD ideas of behavior specifications with describe and should. Mocha lets you use both approaches.
  • Reporters
    Running your test will generate reports of the results, and you can format these results using various reporters. For example, if you need to feed a continuous integration server, you’ll find a reporter to do just that.
  • Lack of an assertion library
    Far from being a problem, Mocha was designed to let you use the assertion library of your choice, giving you even more flexibility. You have plenty of options, and this is where Chai comes into play.
Chai is a flexible assertion library that lets you use any of the three major assertion styles:
  • assert
    This is the classic assertion style from old-school TDD. For example:
    assert.equal(variable, "value");
    
  • expect
    This chainable assertion style is most commonly used in BDD. For example:
    expect(variable).to.equal("value");
    
  • should
    This is also used in BDD, but I prefer expect because should often sounds repetitive (i.e. with the behavior specification of “it (should do something…)”). For example:
    variable.should.equal("value");
    
Chai combines perfectly with Mocha. Using just these two libraries, you can write your tests in TDD, BDD or any style imaginable.

Grunt

Grunt enables you to automate build tasks, anything including simple copying-and-pasting and concatenation of files, template precompilation, style language (i.e. SASS and LESS) compilation, unit testing (with Mocha), linting and code minification (for example, with UglifyJS or Closure Compiler). You can add your own automated task to Grunt or search the registry, where hundreds of plugins are available (once again, using a tool with a great community behind it pays off). Grunt can also monitor your files and trigger actions when any are modified.

RequireJS

RequireJS might sound like just another way to load modules with the AMD API, but I assure you that it is much more than that. With RequireJS, you can define dependencies and hierarchies on your modules and let the RequireJS library load them for you. It also provides an easy way to avoid global variable space pollution by defining all of your modules inside functions. This makes the modules reusable, unlike namespaced modules. Think about it: If you define a module like Demoapp.helloWordModule and you want to port it to Firstapp.helloWorldModule, then you would need to change every reference to the Demoapp namespace in order to make it portable.
RequireJS will also help you embrace the dependency injection pattern. Suppose you have a component that needs an instance of the main application object (a singleton). From using RequireJS, you realize that you shouldn’t use a global variable to store it, and you can’t have an instance as a RequireJS dependency. So, instead, you need to require this dependency in your module constructor. Let’s see an example.
In main.js:
  define(
      ["App","module"],
      function(App, Module){
          var app = new App();

          var module = new Module({
              app: app
          })

          return app;
      }
  );
In module.js:
  define([],
      function(){
          var module = function(options){
              this.app = options.app;
          };
          module.prototype.useApp = function(){
              this.app.performAction();
          };
          return module
      }
  );
Note that we cannot define the module with a dependency to main.js without creating a circular reference.

CoverJS

Code coverage is a metric for evaluating your tests. As the name implies, it tells you how much of your code is covered by your current test suite. CoverJS measures your tests’ code coverage by instrumenting statements (instead of lines of code, like JSCoverage) in your code and generating an instrumented version of the code. It can also generate reports to feed your continuous integration server.

Conclusion

Full-stack JavaScript isn’t the answer to every problem. But its community and technology will carry you a long way. With JavaScript, you can create scalable, maintainable applications, unified under a single language. There’s no doubt, it’s a force to be reckoned with.

Four Ways To Build A Mobile Application

The mobile application development landscape is filled with many ways to build a mobile app. Among the most popular are:
  • native iOS,
  • native Android,
  • PhoneGap,
  • Appcelerator Titanium.
This article marks the start of a series of four articles covering the technologies above. The series will provide an overview of how to build a simple mobile application using each of these four approaches. Because few developers have had the opportunity to develop for mobile using a variety of tools, this series is intended to broaden your scope.
Hopefully, armed with this knowledge, you will be in a better position to choose the right development tools for your mobile application’s needs. In this first article in the series, we’ll start with some background and then dig into iOS.
I’ve built the same simple application with each technology to demonstrate the basic concepts of development and the differences between the platforms and development tools. The purpose of this series is not to convert you to a particular technology, but rather to provide some insight into how applications are created with these various tools, highlighting some of the common terms and concepts in each environment.
FasTip is a simple application to calculate tips. Because this is a simple example, it uses the standard UI controls of each platform:
fastip-app-screens-500
The screenshots above show the application running as native iOS, PhoneGap and native Android applications. Appcelerator Titanium uses native controls, so it looks the same as the native iOS and Android applications. Our application has two screens: a main screen where the tips are calculated, and a settings screen that enables the user to set a tip percentage. To keep things simple and straightforward, we’ll use the default styles of each environment.
The source code for each app is available on GitHub.

Native iOS Development

Most applications in Apple’s App Store are written in the Objective-C programming language, and developers typically use Xcode to develop their applications.
xcode-screen-500

Obtaining the Tools

To build an iOS app, you must use Mac OS X; other operating systems are not supported. The development tools that you’ll need, iOS 7 SDK and Xcode 5, are free of charge, and you can run the app that you build in the iOS simulator, which is part of the iOS SDK. To run your app on a real device and make it available in Apple’s App Store, you must pay $99 per year.

Creating a New Project

Once you have installed Xcode, you’ll want to create a new project. Choose “Create a new Xcode project” from the welcome screen or via File → New Project in the menu.
xcode-new-project-500
For a simple application such as this one, “Single View” is appropriate. Upon clicking “Next,” you will be presented with a dialog to enter some basic information about your application:
new-project-options-500
The value that you enter in the “Class Prefix” option tells Xcode to attach that unique prefix to every class that you generate with Xcode. Because Objective-C does not support “namespacing,” as found in Java, attaching a unique prefix to your classes will avoid naming conflicts. The “Devices” setting lets you restrict your application to run only on an iPhone or an iPad; the “universal” option will enable the application to run on both.

Navigation Controllers and View Controllers

The screen functionality of iOS applications is grouped into what are known as view controllers. Our application will have two view controllers: one for the main screen and one for the settings screen. A view controller contains the logic needed to interact with the controls on a screen. It also interacts with another component called the navigation controller, which in turn provides the mechanism for moving between view controllers. A navigation controller provides the navigation bar, which appears at the top of each screen. The view controllers are pushed onto a stack of views that are managed by the navigation controller as the user moves from screen to screen.

Storyboards: Building the User Experience Visually

Starting with iOS 5, Xcode has had storyboards, which enable developers to quickly lay out a series of view controllers and define the content for each. Here’s our sample application in a storyboard:
storyboard-overview-500
The container on the left represents the navigation controller, which enables the user to move from screen to screen. The two objects on the right represent the two screens, or view controllers, that make up our app. The arrow leading from the main screen to the settings screen is referred to as a segue, and it indicates the transition from screen to screen. A new segue is created by selecting the button in the originating view and then, while the Control key is pressed, dragging the mouse to the destination view controller. Apple’s documentation provides more detail about this process.
storyboard-properties-500
In the example above, we can see that a text field has been selected, and the property panel is used to adjust the various attributes of the controls. When this application was created, the “universal” app option was selected, enabling the app to run on both an iPhone and iPad. As a result, two versions of the storyboard file have been created. When the app is running on an iPhone or iPod Touch, the _iPhone version of the file will be used, and the _iPad version will be used for iPads. This allows a different layout to be used for the iPad’s larger display. The view controller will automatically load the appropriate layout. Keep in mind that if your storyboards expose different sets of controls for the iPad and the iPhone, then you must account for this in the code for your view controller.
In addition to directly positioning items at particular coordinates on the screen, you can also use the Auto Layout system that was introduced in iOS 6. This enables you to define constraints in the relationships between controls in the view. The storyboard editor enables you to create and edit these constraints.
storyboard-constraints-500
The constraints can also be manipulated programmatically. The Auto Layout mechanism is quite sophisticated and a bit daunting to use at first. Apple has an extensive guide on Auto Layout in its documentation.

Associating Storyboards With Your Code

To access the storyboard objects from the code, you must define the relationships between them. Connecting items from the storyboard to your code via Xcode is not obvious if you’re used to other development environments. Before you can do this, you must first create a view controller to hold these associations. This can be done with the following steps:
  1. Choose File → New File.
  2. In the dialog that appears, choose “Objective-C class”:
  3. In the next dialog, give your class a name and ensure that it inherits from UIViewController:
    file-new-options-500
  4. Upon clicking “Next,” you’ll be asked to confirm where in the project the file should be saved. For a simple project, picking the main directory of the app is fine.
  5. Upon clicking “Next,” you’ll see that a new set of files has been created for your view controller. Now, associate that newly created view controller with the view controller in your storyboard.
  6. With the storyboard open, click on the view controller. In the “Identity Inspector” panel, pick the “Class” that this view controller is to be associated with:
    class-picker
  7. Once this process is completed, the code for your view controller will be properly referenced by the storyboard entry.
To reference the controls that you’ve dragged onto a storyboard from your Objective-C code, you’ll need to define these relationships. The storyboard editor has an “assistant editor” view to help with this. Basically, it’s a split-pane view that shows both the storyboard and your code. In this example, we’ll reference a button that’s already been placed on the storyboard:
  1. First, ensure that you’ve completed the steps above to associate the view controller class with the corresponding view controller in the storyboard.
  2. Choose the assistant editor by clicking the icon that looks like this:
    assistant-editor-icon
  3. A split-pane view will open, with the storyboard on the left and your view controller class on the right.
  4. Select the button in your storyboard and, while holding down the Control key, drag from the button to the interface area of your code.
    create-outlet-500
  5. The resulting dialog will enable you to create an “outlet” for the button in your code. Simply give the button a name, and click the “Connect” button in the dialog. You may now reference the button in the view controller from your code.
  6. Let’s hook up a method to be invoked when a person taps on the button. Select the button again, and use the same Control-and-drag maneuver to drop a reference into the interface section of your view controller.
  7. This time, in the dialog box that appears, we’ll associate an “action,” rather than an outlet. Choose “Action” from the “Connection” drop-down menu, and enter a name like this:
    create-action-500
    For the “Event,” use the default of “Touch Up Inside,” and press the “Connect” button.
  8. Note that your class now has an interface with two entries in it:
@interface FTSettingsViewController ()
@property (weak, nonatomic) IBOutlet UIButton *myButton;
- (IBAction)tappedMyButton:(id)sender;
@end
The IBOutlet item is used to identify anything that you’re referencing from the storyboard, and the IBAction is used to identify actions that come from the storyboard. Notice also that Xcode has an empty method where you can place the code to be run when the user taps on the control:
- (IBAction)tappedMyButton:(id)sender {
}
The process above does take some getting used to and could certainly be made more intuitive. After some practice, it will get less awkward. You might find it useful to bookmark the section of the Xcode documentation that describes how to “Connect User Interface Objects to Your Code.”
As we’ll see later, you can also add objects to the view and manipulate their properties programmatically. In fact, applications of even moderate complexity typically perform a lot of manipulation in code. For complex apps, some developers eschew the storyboard and use the code-based alternative almost entirely.

Getting Into the Code

For even the most basic of applications to function, some code must be written. So far in the storyboard, we’ve laid out our user interface and the interactions between the view controllers. But no code has been written to perform the calculations, to persist the settings of the tip percentage and so on. That is all done by you, the developer, in Objective-C.
When an application is running, its overall lifecycle is handled by something called an “application delegate.” Various methods in this delegate are called when key events in the application’s lifecycle occur. These events could be any of the following:
  • the application is started,
  • the application is moved to the background,
  • the application is brought to the foreground,
  • the application is about to be terminated,
  • a push notification arrives.
The events above are handled in a file called AppDelegate. For our sample application, the default handling of these events is just fine; we don’t need to take any special action. The documentation has an overview of the application’s lifecycle and of responding to changes in an app’s state.
The next area of attention is the view controller. Just as with the application delegate, the view controller has its own lifecycle. The view controller’s lifecycle includes methods that are invoked when the following happens:
  • the view controller has been loaded;
  • the view controller is about to appear or has appeared on the screen;
  • the view controller is about to disappear or has disappeared from the screen;
  • the bounds of the view have changed (for example, because the device has been rotated) and the view will be laid out again.
The main code for our application is in the FTViewController.m file. Here is the first bit of code that initializes our screen:
- (void)viewWillAppear:(BOOL)animated
{
    // Restore any default tip percentage if available
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    float tipPercentage = [defaults floatForKey:@"tipPercentage"];
    if (tipPercentage > 0) {
        _tipPercentage = tipPercentage;
    } else {
        _tipPercentage = 15.0;
    }
    self.tipAmountLabel.text = [NSString stringWithFormat:@"%0.2f%%", _tipPercentage];
}
In this application, we want to use whatever tip percentage value was stored in the past. To do this, we can use NSUserDefaults, which is a persistent data store to hold settings and preferences for an application. Keep in mind that these values are not encrypted in any way, so this is not the best place to store sensitive data, such as passwords. A KeyChain API is provided in the iOS SDK to store such data. In the code above, we’re attempting to retrieve the tipPercentage setting. If that’s not found, we’ll just default to 15%.
When the user taps the “Calculate Tip” button, the following code is run:
- (IBAction)didTapCalculate:(id)sender {
    float checkAmount, tipAmount, totalAmount;

    if (self.checkAmountTextField.text.length > 0) {

        checkAmount = [self.checkAmountTextField.text floatValue];
        tipAmount = checkAmount * (_tipPercentage / 100);
        totalAmount = checkAmount + tipAmount;

        self.tipAmountLabel.text = [NSString stringWithFormat:@"$%0.2f", tipAmount];
        self.totalAmountLabel.text = [NSString stringWithFormat:@"$%0.2f", totalAmount];

    }

    [self.checkAmountTextField resignFirstResponder];

}
We’re simply reading the value that the user has inputted in the “Amount” field and then calculating the tip’s value. Note how the stringWithFormat method is used to display the tipAmount value as a currency value.
When the user taps the “Settings” button in the navigation controller, the segue that we established in the storyboard will push the settings’ view controller onto the stack. A separate view controller file, FTSettingsViewController, will now handle the interactions on this screen. Pressing the “Done” button on this screen will run the following code:
- (IBAction)didTapDone:(id)sender {

    float tipPercentage;
    tipPercentage = [self.tipPercentageTextField.text floatValue];

    if (tipPercentage > 0) {

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setFloat:tipPercentage forKey:@"tipPercentage"];
        [defaults synchronize];

        [[self navigationController] popViewControllerAnimated:YES];

    } else {

        [[[UIAlertView alloc] initWithTitle:@"Invalid input"
                                    message:@"Percentage must be a decimal value"
                                   delegate:nil
                          cancelButtonTitle:@"ok"
                          otherButtonTitles:nil] show];

    }

}
Here we’re retrieving the value from the text field and making sure that the inputted value is greater than 0. If it is, then we use NSUserDefaults to persist the setting. Calling the synchronize method is what will actually save the values to storage. After we’ve saved the value, we use the popViewControllerAnimated method on the navigation controller to remove the settings view and return to the prior screen. Note that if the user does not fill in the percentage correctly, then they will be shown the standard iOS UIAlertView dialog and will remain on the settings screen.
In the section above on view controllers and storyboards, I mentioned that the controls in a view can be manipulated programmatically. While that was not necessary for our application, the following is a snippet of code that creates a button and adds it to a particular location on the screen:
CGRect buttonRect = CGRectMake(100, 75, 150, 80);
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = buttonRect;
[myButton setTitle:@"Click me!" forState:UIControlStateNormal];
[self.view addSubview:myButton];
Generally speaking, all of the controls that you place in a view extend from an ancestor class named UIView. As such, buttons, labels, text-input fields and so on are all UIViews. One instance of a UIView is in the view controller. This can be referenced in your view controller’s code as self.view. The iOS SDK positions items in a view based on a frame, also referred to as CGRect, which is a structure that contains the x and y coordinates of the item, as well as the width and height of the object. Note in the code above that the button is instantiated and assigned a frame (location and size) and then added to the view controller’s view.

Running and Debugging an iOS Application

When Xcode and the iOS SDK are installed, so is the iOS simulator, which simulates an iOS device directly on your machine. Xcode has a drop-down menu that allows you to select different device configurations. Pressing the “Run” button in the upper-left corner will build the app and then run it in the chosen simulator.
device-chooser-500
Using the menu above, you can switch between iPhones and iPads of different sizes, as well as between Retina and non-Retina versions of each device.
Debugging is done simply by clicking in the left margin of the code editor, where the line numbers appear. When the execution of your app reaches the breakpoint, the app will stop and the variable values in effect at that moment in time will appear below the code editor:
breakpoint-variables-500-opt
Some things, such as push notifications, cannot readily be tested in the simulator. For these things, you will need to test on a device, which requires you to register as an Apple developer for $99 a year. Once you have joined, you can plug in your device with a USB cable. Xcode will prompt you for your credentials and will offer to “provision” the device for you. Once the device is recognized, it will be shown in the same menu that allows you to switch between device simulators.
In Xcode, by going to Window → Organizer in the menu, you can display a tool that enables you to manage all of the devices visible in Xcode and to examine crash logs and more. The Organizer window also lets you take and export screenshots of your application.

Summary

Thus far, we’ve seen the basics of developing a simple native iOS application. Most applications are more complex than this, but these are the basic building blocks:
  • Xcode
    The development environment
  • Storyboards
    For laying out and configuring the user interface
  • View controllers
    Provide the basic logic for interacting with each of the views defined in the storyboards
  • Navigation controllers
    Enable the user to navigate between the different views

Learning Resources

To get started with iOS development, you might want to consult these useful resources:
This concludes the first segment of our tour of app development. I hope it has given you some insight into the basic concepts behind native app development on iOS. The next article in this series will cover how to build the same application using native Android development tools.

Tuesday, November 19, 2013

How Should I Contact You?

What’s the right way to contact clients, colleagues and friends, and for them to contact you? Is offering a multitude of options really the best way forward and will certain tools begin to become acceptable for certain types of communication?
This post is a little like crystal ball gazing because this change is continuing to wind its way along. But for now, here are my predictions:

Email is not dead, long live email

For certain scenarios, traditional email is still entirely suitable. This includes most client B2B contact, a lot of inter-corporate communications, and some B2C contact, particularly opt-in newsletters and special offers (though many of these are migrating to Facebook). If you need to make a lengthy and involved communication, where structure is important, then email is still your very best option.

Facebook will become the dominant player in social emailing/messaging/’chatmail’ (Watch out Gmail!)

Although Facebook messaging isn’t true email as it lacks some of the features of email, it is very well suited to social, informal contact. Now friends don’t have to worry whether they have your up- to-date email address, because they know you’re active on Facebook. If someone wants to reach you on the weekend, Facebook is probably a better option, because you may check Facebook more often than email (depending on how much of an addict you are). Regardless, Facebook will send the recipient an email with the contents (depending on setup options). Facebook is also quite unique in that it collates SMS, IM and emails within a message string. Facebook says this is ideal for a typical family scenario – where a grandparent is a strict email user, a teen prefers SMS via their mobile and a parent prefers to use Facebook – Facebook messaging allows converged contact with all of these whatever the medium used. What’s evolving is that the means of communication is now less important than the conversation itself. Of course, this is particularly relevant for social, informal messaging, but not so for business communication.

Skype is super for instant messaging

Instant messaging is a beautiful thing, in my opinion. I rarely use it to contact clients but for colleagues and friends it can be time saving, easy and effective. By its very nature it’s instant, so long as the other person is online (which you can normally see), but it’s also short. It’s difficult to see how anyone could object to it. After all, if you don’t want to be IM’d, you can set your profile to view ‘Away’ or ‘Do not disturb’ and then you won’t be bothered. I hope and expect that it will soon become more acceptable for business use. Facebook does of course have IM (or chat) as part of its offering, but I prefer to keep Facebook for personal/social use only. And I feel that the Skype interface is superior to Facebook chat and to Google chat. The also-rans are:

LinkedIn useful for business networking

You probably don’t have the email addresses of many of your linked in contacts, so this gives you a way of messaging them without getting too close by asking for their email address.

Twitter has limited value

You can send contacts/followers a public tweet, which is only really useful if they’re currently online. You can also send them a Direct Message and even if they’re not online they will receive an email to say they’ve received a DM. With the 140 character limit however, Twitter is only really useful for contacts for whom you don’t have another means of contact.

So, in short, the killer communications’ apps are:

  • Email for B2B, B2C and some corporate
  • Skype or similar for rapid response and short messaging.
  • Facebook for most social emailing/messaging
Perhaps shortcuts on our smartphones and computers should now use generic terms: Quick Message (QM) or Friendly Message (FM) or Business Message (BM), and link through to the apps that you favour for each. There’s so much I haven’t talked about here including functionality, privacy issues, technology issues, video contact, the growth of mobile internet and how it will affect all of these. Overall, would you agree? What does your crystal ball tell you?

Monday, November 18, 2013

Killer Responsive Layouts With CSS Regions

As Web designers, we are largely constrained by the layout features available to us. Content placed inside a container will often naturally extend the container vertically, wrapping the content. If a design requires elements to remain a certain height, then our options are limited. In these cases, we can only add a scroll bar or hide the overflow. The CSS Regions specification provides a new option.

Support

Regions are a new part of the CSS specification, so not all browsers have implemented them, and in some cases you might have to enable a flag to use them. They have recently gained support in iOS7 and Safari 7, as well as Safari 6.1+. Adobe maintains a list of supported browsers and instructions on enabling regions and other features. However, support for regions is constantly growing. For a robust list of which browsers have implemented regions and the various features available, see Adobe’s “CSS Regions Support” page.

Regions 101

CSS regions enable us to disperse content across multiple containing elements. They provide a flow, which consists of content that may appear within multiple elements, and a region chain, which is the collection of elements the flow is spread across. Once these elements have been defined, the flow dynamically fills the elements in the region chain. We can then size our containers vertically without worrying about the content getting cut off, because it simply overflows into next element in the chain. This creates new opportunities for layout with responsive design.
To use regions, start by creating a named flow; simply add the CSS property flow-into to your content element, with the value of your flow’s name. Then, for each region through which you want the content to flow, apply the CSS property flow-from with the same flow name value. The content element will then flow through the region elements. Current implementations in browsers require the property to be prefixed, but we are using the unprefixed version here.
#myContent {
 flow-into: myNamedFlow;
}

.myRegion {
 flow-from: myNamedFlow;
}
Your HTML would contain a content element and the scaffolding of all of the regions that this content will flow through. When you use regions, the content element will not be visible in its original location and any HTML already in your region elements will disappear, replaced by the content being flowed into them. Because of this, we can have placeholder or fallback content within our region elements.
<div class="myRegion"></div>
<div class="myRegion"></div>
<div class="myRegion"></div>

<div id="myContent">...</div>
When using regions, the content being flowed is not a child of the region elements. You are only changing where the content is displayed. According to the DOM, everything remains the same, so the content does not inherit styles from the region in which it lives. Instead, the specification defines a CSS pseudo-selector, ::region(), which allows you to style the content within a region. Apply the pseudo-element to the region’s selector and then pass a selector as an argument, specifying the elements that will be styled within a particular region.
.myRegion::region(p){
    /*styles for all the paragraphs flowing inside our regions*/
}

Responsive Design With Regions

Responsive design is the technique of creating malleable layouts that stretch and change according to the given context. Frequently, designers will make elements flexible with percentages and media queries to adapt a layout to different screen sizes. Responsive design adapts content to every screen without requiring the designer to completely overhaul the design or code.
Regions facilitate responsive design in several ways. First, you no longer have to rely on height: auto for every element to ensure content fits. Instead, you can allow the content to flow into different elements within the layout. This means that the content does not dictate the layout, but rather adapts to the intended design. You can still use height: auto on the last region in the chain to ensure that it extends to display all remaining content. You can see this technique in the CodePen example below.

Regions And Events

You can use JavaScript events with regions to manage your layout and to ensure that content is displayed properly. The regions specification defines events that you can use to respond to certain conditions. The regionoversetchange event is dispatched when the regionOverset property changes for any region. This can occur when a user resizes the page, stretching out the container element so that the content no longer flows into certain regions. The value of regionOverset is either fit, overset or empty. A value of empty specifies no content inside the region. The regionOverset property is set to overset when the last region in the chain is unable to display all of the remaining content, making some of the content unreadable.
The fit value sets content to fit within the region properly, either completely (if earlier in the chain) or partially (if it is the last region in the chain). How you respond to these events will depend on the design, content and other aspects of your layout. These events could be used to dynamically add or remove regions or to apply a class that changes the layout. You can see an example of the former technique in the CodePen below.
Note: Some implementations call the event regionlayoutupdate, instead of regionoversetchange, based on an earlier version of the specification.

Regions And Media Queries

Regions are defined entirely in CSS, making them easy to use in combination with media queries. In addition to resizing and positioning elements, you can completely change which elements are defined as regions. You can also set a region to display: none, which will cause it to be skipped entirely in the region chain. This capability makes it easy to remove particular regions from a layout without worrying about the continuity of the content. You can also use this technique to display whole new templates with completely different layouts, without ever changing the content.

Regions And Break Properties

Regions also extend break properties from the multi-column layout specification, which you can use to define how content breaks within your regions. You can apply these properties to elements within the flow either to always break or to avoid breaking a region relative to the element. Using the value region for break-before or break-after will always force a region to break before or after the element, respectively. The value avoid-region can be used for break-before, break-after or break-inside to prevent regions from breaking before, after or inside the element.
This technique is useful for keeping related elements grouped together and for preventing important elements from being split. The demo below shows images along the right column and long descriptive text flowing along the left. If you reduce the width of your browser, then media queries will change the layout, causing the images to redistribute over the narrower single-column structure. Applying break-after: region to the image containers ensures that a new region break will occur after each image in the image flow.
Note: Some implementations use non-standard regions-specific break properties with a region prefix; for example, region-break-before or, with a vendor prefix, -webkit-region-break-before.
Responsive Layout
The break-after property is applied to regions with media queries.

Regions And Viewport Units

Viewport units enable you to use the window (or viewport) as the basis for sizing elements, which creates a consistent aspect ratio and harmony in the layout. You can simulate pages or blocks that break up the content cohesively. A potential pitfall of this approach is that, if you use the aspect ratio of the device to size containers, defining both the width and the height, then your content might no longer fit inside the containers.
You could, however, use regions to break up the content while respecting the variable-sized elements across different screen sizes. You can see this technique being applied in the “Demo for National Geographic Orphan Elephants.” On this website, images and text are alternated to maintain the height of the viewport. We use regions to flow the content through all of the text sections, and we adjust them when the user shrinks the screen.
elephant-demo2
Regions being used with viewport units. Notice how the image fits the window exactly. (Large view)
The typical navigation paradigm for magazines and books on a tablet is pagination — i.e. enabling the user to swipe or tap to page through the content. As a designer, you want these pages to respond to a variety of screen sizes. Regions are particularly useful for this kind of layout, because you can size columns using viewport units and create a variety of different layouts that enable content to flow across the columns. An example of this done in HTML is shown in the video below:
The Kindle Cloud Reader website has a similar two-page spread but uses JavaScript to manage the layout. Implementing this kind of layout in JavaScript requires significant development overhead, and manipulating the DOM so heavily will usually incur a performance penalty. You can use regions to bring these capabilities natively to the browser, increasing the website’s performance while reducing development time.

Debugging

When working with regions, it’s helpful to have tools to easily manage and debug various features. In Chrome Developer Tools, you can enable debugging features specific to regions. Detailed instructions on enabling these tools can be found in Christian Cantrell’s post “Web Inspector Support for CSS Regions.” With these features, you can find all of the named flows in a document, find the content and region chain associated with each named flow, and get visual cues for whether content fits in a region based on the regionOverset property.
Webkit Nightly also has some helpful visual cues. When you open the Web Inspector and inspect a region’s container, you will see a region number and links between the region containers showing the flow of the content.
region_debugging
Webkit Nightly allows you to inspect region containers, showing their number and the flow chain.