Saturday, May 21, 2011

Titanium MVC Pattern

Are you looking to simplify your Titanium programming model? Leveraging the MVC pattern will help produce cleaner code and promote reusability. Applying the MVC pattern within Titanium is relatively easy and it provides all the advantages we expect from MVC. Here is a quick example of the view and controller components:


View

The view is responsible for creating the window and adding the necessary UI components. Your views may optionally manage styling properties (color, font, and positioning). Ideally, the better practice is to extract all styling properties into external JSS files but I found this feature to be too quirky in its initial release.


/**
* View Template
* Usage: APP.ui.LoginView.createWindow();
*/

APP.ui.LoginView = (function(){

/* private methods to build UI specific components */
function buildWindow(){
return Ti.UI.createWindow({
title: 'Title',
barColor: '#225377',
backgroundColor: '#d4d2d3'
});
}

function buildUsernameTextField(win){
win.usernameTextField = Ti.UI.createTextField({
autocorrect: false,
hintText: 'Username',
left: 10,
width: 285,
suppressReturn:false,
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
returnKeyType: Ti.UI.RETURNKEY_NEXT
});
}

/* Public API only exposes the createWindow method. */
return {
createWindow: function(){
var win = buildWindow();
buildUsernameTextField(win);
//buildComponentX(win);
return win;
}
};
})();


Controller

The controller is responsible for managing events (button taps) and navigation. Events handlers communicate with server-side services when necessary.

/**
* Controller Template
* Usage: APP.ui.LoginController.init();
*/

APP.ui.LoginController = (function(){

/* Private helper methods */
function setEventListeners(win){
win.usernameTextField.addEventListener('return', function(){
win.passwordTextField.focus();
});

win.passwordTextField.addEventListener('return', function(){
handleLoginEvent(win);
});
}

/* Public API only exposes init method. */
return {
init: function(){
var win = APP.ui.LoginView.createWindow();
setEventListeners(win);
win.open();
}
};
})();


Model

The model is typically a JSON payload retrieved from a Restful service. For example, the handleLoginEvent will return user profile information after a successful login. We can save this object locally and leverage it on subsequent screens.


Advantages:
  • Small objects and methods.
  • Improved organization and readability
  • Promotes reusability of views. Also, the decoupled views allow you to swap in native-specific UIs when necessary all while reusing a single controller.
  • Simpler maintenance.
  • Allows for simpler unit testing with responsibilities split into separate objects.


I expect many developers may fall in the trap of modeling their JavaScript according to the KitchenSink examples. While those examples are useful, their programming practices should not be followed for a production ready app. For example, their examples do not leverage closure to eliminate global scope, they do not use a namespace convention for improved organization, and all MVC responsibilities were bundled within a single object.

Sunday, March 20, 2011

Mobile March

The Mobile March conference was held at the Best Buy headquarters this weekend. Here is a brief recap of the sessions I attended:

Morning Sessions

Keynote

Key points:
  • There is a low tolerance for mediocrity in mobile. Apps have a 50% abandon rate after the first 30 days.
  • Mobile trends: News via tablets, social media, location based apps, group messaging with apps like Beluga.
  • Mobile marketing, what's working: Incentives, deals, hot buys, and rebates.
  • 5 things to consider: Activate advertising with text or QR codes, activate sponsorships with mobile, launch mobile coupons, test a location based campaign, use mobile to drive app downloads.

Simple and low cost mobile technologies have proven to be very effective solutions. SMS, QR codes, and social media fall within this category. The goal is simple, get customers to engage and then extend the conversation.



Cracking the Code: QR Codes and Coupons

Key points:
  • QR code scanning is up 1000% in the last 6 months. Consumers love to scan QR barcodes.
  • QR codes link users to additional information. For example, Best Buy has QR codes next to each price tag. Launching the QR code provides the user with detailed information and user reviews. Additionally, if you scan another product you can see a side-by-side comparison of both products.
  • Looking for a QR reader? Try NeoReader.
  • Chino Latino is the first restaurant to put a QR code on a billboard.

Mobile March had QR codes at the entrance of each session. Scanning the code displayed the presenters bio. Again, this is a simple, low cost solution to interact with mobile customers.



The iPhone vs Android Showdown

Key points:
  • iPhone
    • Xcode 4, which was released a few weeks ago, has finally simplified the organization of their Interface Builder and code editor. Navigating between Interface Builder and code is much quicker via their new tab orientation instead of externalized windows found in Xcode 3.
    • Xcode is the superior IDE when compared to Android development on Eclipse. The Interface Builder is far superior and the iPhone emulator loads much faster.
  • Android
    • Android's distribution model is superior. It takes several hours to deploy to Android's Market. The Apple Store certification process may take up to 2 weeks.

Creating a mobile wireframe is easily 2-3 times faster in Xcode. While Android finally released a UI builder with their 3.0 SDK it is far from perfect. A major Android advantage is their time to market on app upgrades. If you have a production defect will you have the patience to wait for the Apple certification process?



Grill yourself

Key points:
  • Think about UX as soon as you have an idea.
  • Keep apps simple and moving parts to a minimum.
  • You can sell anything if you can do it simple, quick, and cheap.
  • Share the analytics about your mobile users with your organization.


Afternoon Sessions

The Current State of the Mobile Web

Key points:
  • Native advantages: performance, consistency, safety, convenience, functionality.
  • Native disadvantages: harder to build, approval process, hard to discover, fragmentation.
  • Mobile Web advantages: open, connected, ubiquitous, unregulated.
  • Mobile Web disadvantages: unregulated, performance is slower.
  • Mozilla and Google are coming out with web app stores soon.
  • Looking for a fixed header and footer for your scrollable window on iOS? Try iScroll.

There are clearly many advantages to Mobile Web. Its deployment model is instantaneous and it helps reduce fragmentation and development costs. If you are interested in jQuery Mobile, here is a good presentation.



Blackberry Playbook

Key points:
  • Cost of entry
    • BlackBerry: Free
    • Android: $25 (one time)
    • Apple: $99/yr
  • Distribution
    • Google: lass than hour
    • BlackBerry: 4-6 hours
    • Apple: up to 2 weeks
  • BlackBerry has a "try before you buy" program in their AppWorld store which is unique.

The Playbook tablet by BlackBerry will be released soon. While competition is good, they definitely have an uphill battle to climb.

Sunday, March 6, 2011

No Fluff Just Stuff: Minneapolis Summary (Spring)

The No Fluff Just Stuff conference was back in Minneapolis. Here is a brief recap of the sessions I attended:

Friday Sessions

NoSQL Smackdown!

Key points:
  • NoSQL is a set of different approaches to storing and retrieving data
  • Cassandra:
    • Implementation Language: Java 6
    • Data Model: BigTable
    • Advantages: Highly scaleable
    • Deployments: facebook, twitter
  • MongoDB:
    • Implementation Language: C++
    • Data Model: JSON
    • Advantages: Simple
    • Deployments: sourceforge, bit.ly, shutterfly, Etsy

I like the fact MongoDB persists JSON. I implemented a similar solution on a recent mobile application where JSON objects were persisted on the client database. This solution is simple, requires minimal code, and provides great flexibility. If the domain model changes the database requires ZERO changes!



Pragmatic Architecture

Key points:
  • Architects will be much more effective if they have a solid understanding of the business domain.
  • A good architecture makes it easy for developers to make "right" decisions.
  • Avoid architectures that were designed with Resume Driven Design (RDD).
  • Architects must be familiar with all technologies.
  • Prefer full-time architects or architects that at least see the consequences of their design after deploying to production.

Over the past twelve years I have observed that the most effective architects code at least 49%. The more the better. If this isn't the case they simply won't be effective long term. The best architects produce working code in addition to their design artifacts.



Introducing Spring Roo: From Zero to Working Spring Application in Record Time

Key points:
  • The rapid scaffolding is intriguing.
  • The de-Rooing is convenient when you need to remove the Roo footprint.
  • I particularly like the ability to replay your commands for project setup. Extract the Roo scripts and replaying them for the next project can offer rapid productivity.

Roo makes sense for rapid prototyping or if you need to build an application in 24-hours.



Saturday sessions

HTML5: The JavaScript Parts

Key points:
  • Prefer document.querySelector() over document.getElementById() for much improved performance gains.
  • By default, navigator.geolocation is not enabled in Chrome. The user must explicitly enable it.
  • Modernizr can help with progressive enhancement by detecting browser feature availability and reacting appropriately.
  • Web Workers are not supported on mobile browsers:(
  • When can I use... shows feature compatibility by browser.
  • findmebyIP shows feature support for your current browser.

I predict a strong enterprise push for mobile web development starting this year. Mobile Web is device agnostic and jQuery Mobile will simplify the adoption. Even facebook has admitted to the pain, duplication, and cost of supporting five separate native apps.



Developing Social-Ready Web Applications

Key points:
  • Enable twitter integration with @Anywhere
  • Dynamically search for tweets from twitter's restful API: http://search.twitter.com/search.json?q=nfjs
  • Dynamically find the friends of a twitter user: http://api.twitter.com/1/friends/ids.json?screen_name=<username>
  • Enable facebook integration with their Social Plugins
  • Dynamically retrieve the user info for a facebook user: https://graph.facebook.com/<username>
  • LinkedIn's developer widgets

The greatest benefit of Spring Social is its simplification of SSO integration.



Git Going with Distributed Version Control

Key points:
  • Git is 10-100 times faster than Subversion.
  • Git can bisect bugs or find the commit that broke a test.
  • Git can search (grep) the entire revision history without checkouts. For example, I can find a particular commit where a line was added.
  • Git persists the versioned artifacts to the file system as 40 character hashes. This approach is very lightweight and provides extremely fast compares.
  • Unlike Subversion, Git does not pollute the source directories with version control meta data.

I have been working with Git for several weeks. Matthew's DZone Refcard about Git has also been a very valuable resource. Git was my favorite session so far!



Sunday sessions

jQuery: Ajax Made Easy

Key points:
  • jQuery has a small footprint, the code is clean, it has good documentation, has excellent CSS selector support, and it's the most popular.
  • If you only need the CSS selector support it's available in Sizzle.

If you want read well written JavaScript it is worth your time to checkout jQuery's source code.



Going Mobile with jQuery

Key points:
  • 50% of population will have smartphone by the end of 2011
  • Tablet support is now available
  • Favorite quote: "Using an iPhone during a meeting makes you look like a proactive employee." --Nathaniel Schutta

I have been working with jQuery Mobile for several months now and it is a simple framework. The team is extremely eager to support nearly every device. After spending time learning Git, I am finally setup to help contribute to the project. Now I need to find the time to focus on a task, defect, or test! In addition to jQuery Mobile there are also mobile web frameworks available from YUI, jQTouch, and Jo.



Code Craft

Key points:
  • We need to spend more time reading code.
  • There is nothing wrong with simplicity! Simple code == good
  • If you are having difficulties with code reviews try Crucible.


Mobile GUI Frameworks

Key points:
  • jQTouch is the smoothest mobile web framework on the market today. However, only iOS is able to reap many of these benefits.
  • Jo is a new mobile framework I definitely want to look at closer. It's lighter weight than jQuery Mobile and the end user codes primarily in JavaScript whereas jQuery Mobile is more markup driven.

Monday, February 14, 2011

Agile Strategy for 24-hour Coders Challenge

clock

Can we build an app in twenty-four hours? We definitely can with the right planning and tools. The Nerdery is organizing an overnight website challenge in the Twin Cities where teams compete to build the best Web application within twenty-four hours. I have always watched these competitions on TV but never with software developers! What is the ideal strategy for this competition?



Agile Planning Strategy

Pre-competition planning is the most important step to success. Literally, every detail must be planned prior to competition. This will yield great efficiencies during the competition. Pre-competition planning considerations must include:

  • Technology stack: Java, Grails, Rails, PHP
  • Tool suite: IDE, graphic editors
  • Source repository: GIT, shared local repository
  • Hosting platform: Google App Engine (GAE), local environment
  • Identify roles: developer, designer, QA, manager, presenter
  • Database: relational, NoSQL (GAE)
  • Scaffolding for rapid application development (RAD):
  • Requirements gathering techniques: wireframes, use cases
  • Task management: whiteboard, electronic
  • Pre-designed templates for common functionality: Home page, dashboards, login, reports


Multiple Platform Strategy

When I initially saw the 10 member team size I knew that could lead to inefficiencies. Often a team of 3-6 is an ideal size. To remedy this issue why not split the team into two smaller sub-groups? Have one group focus on a desktop Web solution and the other on a mobile Web solution. I see two huge advantages of this strategy. First, it should help eliminate critical paths. Again, with ten team members I see too many members waiting idle for others to complete dependent tasks. And most importantly, this strategy should help deliver that extra punch to help wow the judges.



Execution Strategy

Prior to the competition, every developer and designer must have a fully integrated development environment. Everyones environment must build a template project, sync to the repository, and deploy to the production-ready hosting environment. Once competition begins the focus must be solely about requirements gathering, task definition, prioritization, and efficient implementation.



Kudos

I wanted to thank the Nerdery for hosting such a unique event in the Twin Cities! This is 100% voluntary and the solutions are built for non-profits!

Sunday, January 16, 2011

JavaScript Performance: Creational Patterns

Which JavaScript creational pattern is the most efficient? Is it an object literal, functional, or pseudoclassical object? With JsTestDriver, I setup a quick performance test to gather the metrics.


Creational Patterns to Test

I tested the three most popular creational patterns in JavaScript. Object literals, functional objects, and pseudoclassical objects. In particular, I wanted to test their singleton and instance based execution times.
/*
* Pseudoclassical object designed as a singleton
*/

var PseudoclassicalSingleton = new function(){
this.getName = function(){
return 'Pseudoclassical';
};
};

/*
* Functional object designed as a singleton
*/

var FunctionalSingleton = (function(){
return {
getName: function(){
return 'Functional';
}
};
})();

/*
* Object literal (implicitly singleton)
*/

var ObjectLiteralSingleton = {
getName: function(){
return 'ObjectLiteral';
}
};

/*
* Pseudoclassical object designed as a non-singleton
*/

var PseudoclassicalInstance = function(){
this.getName = function(){
return 'Pseudoclassical';
};
};

/*
* Functional object designed as a non-singleton
*/

var FunctionalInstance = function(){
return {
getName: function(){
return 'Functional';
}
};
};


Performance Test Runner

I setup JsTestDriver to execute the test cases against Firefox. One advantage of JsTestDriver is I can run my test cases against any browser! Each performance test will instantiate its creational pattern 1.4 million times as indicated by the RUN_TIMES constant. Additionally, I ran the performance test suite twenty times to gather an adequate average.
CreationalPatternsPerformanceTest = TestCase("CreationalPatternsPerformanceTest");

var RUN_TIMES = 1400000;

var performanceTest = function(name, f){
console.time(name);
for (var i = 0; i < RUN_TIMES; i++){
f();
}
console.timeEnd(name);
};

CreationalPatternsPerformanceTest.prototype.testResponseTimes = function(){
performanceTest("ObjectLiteral (singleton)", function(){
ObjectLiteralSingleton.getName();
});
performanceTest("Pseudoclassical (singleton)", function(){
PseudoclassicalSingleton.getName();
});
performanceTest("Functional (singleton)", function(){
FunctionalSingleton.getName();
});
performanceTest("Pseudoclassical (instance)", function(){
new PseudoclassicalInstance().getName();
});
performanceTest("Functional (instance)", function(){
FunctionalInstance().getName();
});
};



Performance Test Results
 Object Literal (singleton)Pseudoclassical (singleton)Functional (singleton)Pseudoclassical (instance)Functional (instance)
Avg (ms)10931095109433013341
Min (ms)10701064106232253246
Max (ms)11121114111334603476



Areas of Interest


I had three specific comparisons I wanted to evaluate heading into this experiment:
  1. Object literals vs the others (functional and pseudoclassical): I knew object literals were going to be the most efficient. However, I really wanted to see how much faster they really are. The result was surprising. Object literals (1093 ms) barely out performed functional (1094 ms) and pseudoclassical (1095 ms) response times. This difference is really negligible. Unlike object literals, functional and pseudoclassical objects can provide security. And the performance degradation is almost non-existent.
  2. Functional vs Pseudoclassical: There are always debates over these two objects. While I personally prefer pseudoclassical objects when security is a concern I definitely wanted to see which one was the more performant option. In the end, neither pattern distanced itself from the other in regards to performance.
  3. Singletons vs Instance based Objects: I knew singletons would be the most efficient. However, I wanted to see what this difference really was. On average, singletons were three times faster.


Lessons Learned

  1. Prefer singletons over instance based objects when possible.
  2. Prefer object literals when you are not concerned about privacy.
  3. The performance metrics alone are not enough to sway the functional vs pseudoclassical debate.

Sunday, January 2, 2011

JavaScript: Securing Pseudoclassical Objects

Which JavaScript pattern do you prefer for object creation? Functional or pseudoclassical? This question makes for a very interesting debate. The first time I read JavaScript: The Good Parts I was sold on the functional pattern based upon the knowledge that it was the only pattern that supported privacy. However, the pseudoclassical pattern can be secured! Based upon the fact that pseudoclassical objects can be secured and its many additional advantages make it the ideal choice for object creation.


Securing Pseudoclassical Objects

/**
* Pseudoclassical object with private variables and functions.
*
* @constructor
* @param {string} name
* @param {number} age
*/

var Person = function(name, age) {

/** @public variable */
this.name = name || 'Brad';

/** @private variable */
var age = age || 34;


/** @private function */
function setAge(a) {
age = a;
}

/** @public function with access to private methods and variables (privileged) */
this.getAge = function () {
return age;
};
};


Why is Everything Public?

Security is not often documented within JavaScript books and I rarely see examples where developers secure their JavaScript objects. Typically, everything is exposed publicly. If you develop mobile applications with Titanium or are developing a JavaScript framework you absolutely must apply security with either the functional or pseudoclassical pattern. And of all the Titanium code I have read over the past month not a single example or sample application was concerned about privacy. Training can remedy this problem.


JavaScript Code Completion

auto completeA simple way to quickly view the publicly available methods of an object is with code completion. For example, the Aptana Eclipse plug-in has code completion built-in and works very well for JavaScript development.