SlideShare a Scribd company logo
BEST PRACTICES
 in apps development using
TITANIUM APPCELERATOR
       Alessio Ricco
         @alessioricco

               1
Software Quality characteristic
            (user point of view)
•   Adaptability: is the app able to run in different environments ?

•   Accuracy: how well does your app do the job ?

•   Correctness: is your app able to do the job ?

•   Efficiency: minimizing system resources

•   Integrity: is your app secure ?

•   Reliability: does it crash ?

•   Robustness: does your app handle invalid inputs ?

•   Usability: is it easy to learn how to use it ?


          USERS notice STABILITY and PERFORMANCE

                                      2
Software Quality characteristic
          (developer point of view)

•   Flexibility: can you adapt the app for other uses ?

•   Maintanability: debug, improve, modify the app

•   Portability: adapting the app for other platforms

•   Readability: source code is easy to understand

•   Reusability: using parts of your code in other apps

•   Testability: the degree to which you can test the app

•   Understandability: can you understand what the app does and how it
    does it ?


        DEVELOPERS needs RAPIDITY and READABILITY

                                     3
Software Quality characteristic



User side:
STABLE	

 (applications must have a predictive behaviour)
PERFORMANT (speed must approach the speed of cpu)

Developer side:
RAPID	

 	

 (development must be fast)
READABLE	

 (code must be easy to understand)



                           4
Best Practices




      5
Avoid the global scope
•   NO GARBAGE COLLECTION
    In the global scope not null objects cannot be collected

•   SCOPE IS NOT ACCESSIBLE FROM MODULES
    app.js is not accessible within CommonJS modules
    app.js is not accessible within other contexts (windows)

•   Always declare variables

•   Always declare variables inside modules or functions

•   Assign global objects to null after the use

                                 6
Nulling out object references
// create ui objects
var window = Ti.UI.createWindow();
var myView = myLibrary.createMyView();

win.add(myView);
win.open();

// remove objects and release memory
win.remove(myView);
myView = null;
// the view could be removed by the GC


                     7
Keep local your temp var
// immediate functions help us to avoid
// global scope pollution

var sum = (function() {
    var tmpValue = 0; // local scope
    for (var i = 0; i < 100; i++) {
        tmpValue += i;
    }
    return tmpValue;
})();

// i, tmpValue are ready for GC !
                     8
Use self calling functions
// self calling function
(
function()
{
  var priv = 'I'm local!';
}
)();

//undefined in the global scope
alert(priv);


                    9
Use namespaces
Enclose your application's API functions and properties into a
single variable (namespace). This prevent the global scope
pollution- this protect your code from colliding with other
code or libraries

// declare it in the global scope
var mynamespace = {};
mynamespace.myvar = “hello”;
mynamespace.myfunc = function(param) {}



                                10
Namespaces are extendable
// extend and encapsulate by using self-calling functions
(function() {
    function helper() {
        // this is a private function not directly accessible
! !     // from the global scope
    }

    myapp.info = function(msg) {
        // added to the app's namespace, so a public function
        helper(msg);
        Ti.API.info(msg)
    };
})();
// you could then call your function with
myapp.info('Hello World');

              DON'T EXTEND TITANIUM NAMESPACES !!!!!



                                  11
Understanding the closures
A closure is a function together with a referencing environment for the
non local variables of that function

// Return a function that approximates the
derivative of f
// using an interval of dx, which should be
appropriately small.
function derivative(f, dx) {
  return function (x) {
     return (f(x + dx) - f(x)) / dx;
  };
}

the variable f, dx lives after the function derivative returns.Variables must
continue to exist as long as any existing closures have references to them

                                        12
Avoid memory leaks in global event
                        listeners
function badLocal() {
    // local variables
    var table = Ti.UI.createTableView();
    var view = Ti.UI.createView();

     // global event listener
     Ti.App.addEventListener('myevent', function(e) {
         // table is local but not locally scoped
         table.setData(e.data);
     });

     view.add(table);
     return view;
};

Consider to use callback functions instead of custom global events
Place global event handlers in app.js
Rule : global events handle global objects

                                            13
Lazy script loading
      Load scripts only when they are needed
 JavaScript evaluation is slow, so avoid loading scripts if they are not necessary

// load immediately
var _window1 = require('lib/window1').getWindow;
var win1 = new _window1();
win1.open()
win1.addEventListener('click', function(){
! // load when needed
! var _window2 = require('lib/window2').getWindow;
! var win2 = new _window2();
! win2.open()
})

BE AWARE: Some bugs could not be discovered until you load the script...




                                          14
Cross Platform
BRANCHING
useful when your code is mostly the same across platforms but vary in some points

// Query the platform just once
var osname = Ti.Platform.osname;var isAndroid = (osname ==
'android') ? true : false;var isIPhone = (osname ==
'iphone') ? true : false;

// branch the code
if (isAndroid) {
   // do Android code
   ...
} else {
   // do code for other platforms (iOS not guaranteed)
   ...
};

// branch the values
var myValue = (isAndroid) ? 100 : 150;

                                            15
Cross Platform: branch
// Query the platform just once
var osname = (Ti.Platform.osname == 'ipod') ? 'iphone' :
Ti.Platform.osname;
os = function(/*Object*/ map) {
    var def = map.def||null; //default function or value
    if (map[osname]) {
        if (typeof map[osname] == 'function') { return
map[osname](); }
        else { return map[osname]; }
    }
    else {
        if (typeof def == 'function') { return def(); }
        else { return def; }
    }
};

// better than if statement and ternary operator.
var myValue = os({ android: 100, ipad: 90, iphone:   50 });

                                 16
Cross Platform: JSS
PLATFORM-SPECIFIC JS STYLE SHEETS (JSS)
JSS separate presentation and code.

module.js
var myLabel = Ti.UI.createLabel({
! text:'this is the text',
! id:'myLabel'
});

module.jss
#myLabel {
! width:149;
! text-align:'right';
! color:'#909';
}

for platform specific stylesheets you can use module.android.jss and
module.iphone.jss, but module.jss have the precedence.

                                             17
Images
Minimize memory footprint
Image files are decompressed in memory to be converted in
bitmap when they are displayed.
No matter the .png or .JPG original file size

         Width       Height        Colors   Footprint
           320        480           24bit    450KB
           640        960           24bit   1800KB
          1024        768           24bit   2304KB
                                   2304KB
          2048        1536          24bit     9216

                              18
Image optimization

•   use JPG for displaying photos- use PNG for displaying icons, line-art, text

•   use remove() when the image is not visible on screen

•   set image views to null once no longer need those objs

•   resize and crops images to the dimensions you need

•   resize images to minimize file storage and network usage

•   cache remote images (https://gist.github.com/1901680)




                                      19
Database
             Release the resultset as soon as you can
exports.getScore = function (level) {
! var rows = null;
! var score= 0;
! try {
! ! rows = db.execute( "select max(score) as maxscore from score where level=?",
level );
! ! if( rows.isValidRow( )) {
! !       Ti.API.info( "SCORE: (score,level) " + rows.field( 0 ) + ' ' + level );
! !       score= rows.field( 0 )
! ! } else {
! !       Ti.API.info( "SCORE: error retrieving score [1]" );
! ! }
! }
! catch (e) {
!    ! Ti.API.info( "SCORE: error retrieving score [2]" );
! }
! finally {
! ! rows.close( );
! }
! return score;
}


                                           20
Database
      Close the database connection after insert and update
var db = Ti.Database.open('myDatabase');

try{
! db.execute('BEGIN'); // begin the transaction
! for(var i=0, var j=playlist.length; i < j; i++) {
! var item = playlist[i];
  !
! db.execute('INSERT INTO albums (disc, artist, rating) VALUES
  !
(?, ?, ?)', !! item.disc, item.artist, item.comment);
             !
! }
! db.execute('COMMIT');
}
catch (e){
! Ti.API.info( "SCORE: error retrieving score [2]" );
}
finally {
! db.close();
}
                                 21
Database
                 Minimize your database size

•   Big Databases increases your app package file size

•   The database is duplicated on your device because is copied to the
    ApplicationDataDirectory

•   On some Android releases the installer cannot uncompress assets over 1MB (if
    you have a 2MB database you need some workarounds)



      Keep your db small and populate it on the 1st run !

      read sql-lite FAQ:
      http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html




                                       22
Style and convention
Learn and follow language rules, styles and paradigms	

javascript
isn't c# or java or php	

   titanium appcelerator is not just javascript	


Follow coding style best practices	

  Naming Conventions	

  Indentation	

  Comments Style	


Follow language related communities and forums	

  don't reinvent the wheel	

  learn community best practices

                                  23
Language Rules
Learn and follow language rules, styles and paradigms	

javascript
isn't c# or java or php	

   titanium appcelerator is not just javascript	


Follow coding style best practices	

  Naming Conventions	

  Indentation	

  Comments Style	


Follow language related communities and forums	

  don't reinvent the wheel	

  learn community best practices

                                  24
Language Rules
Always declare the variables

When you fail to specify var, the variable gets placed in the
global context, potentially clobbering existing values. Also, if
there's no declaration, it's hard to tell in what scope a variable
lives.

So always declare with var.	




                                  25
Language Best Practices
Use the Exactly Equal operator (===)

comparing two operands of the same type is, most of the
time, what we need
           var testme = '1';
           if(testme == 1) // '1' is converted to 1
           {
           ! // this will be executed
           }

           var testme = '1';
           if(testme === 1) {
           ! // this will not be executed
           }


                               26
Language Best Practices
     Is better wrap self functions with parenthesis
var myValue = function() {
     //do stuff
     return someValue;
}();

// the same code, but it's clear that
myValue is not a function
var myValue = (function() {
    //do stuff
    return someValue;
})();
                             27
References
Titanium Appcelerator online documentation
http://docs.appcelerator.com/

Code Complete 2nd Edition – Steven C. McConnell - Microsoft Press
http://www.cc2e.com/Default.aspx

SQLite Optimization FAQ
http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html

Douglas Crockford
http://javascript.crockford.com/

Google Javascript Style Guide
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

TwinsMatcher
http://itunes.apple.com/app/twinsmatcher/id429890747?mt=8

@alessioricco
http://www.linkedin.com/in/alessioricco


                                             28

More Related Content

What's hot

Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScriptKevin Whinnery
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
Wim Selles
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
Lukas Ruebbelke
 
Xamarin.iOS introduction
Xamarin.iOS introductionXamarin.iOS introduction
Xamarin.iOS introduction
Guido Magrin
 
Testing Mobile JavaScript
Testing Mobile JavaScriptTesting Mobile JavaScript
Testing Mobile JavaScript
jeresig
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
Darren Cruse
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
Paul Jensen
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
Paul Jensen
 
Building testable chrome extensions
Building testable chrome extensionsBuilding testable chrome extensions
Building testable chrome extensions
Seth McLaughlin
 
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNAOGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
Buff Nguyen
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
Jim Jeffers
 
Accessors Vs Direct access to properties & Design Pattern
Accessors Vs Direct access to properties & Design PatternAccessors Vs Direct access to properties & Design Pattern
Accessors Vs Direct access to properties & Design Pattern
CocoaHeads France
 
Calabash Andoird + Calabash iOS
Calabash Andoird + Calabash iOSCalabash Andoird + Calabash iOS
Calabash Andoird + Calabash iOS
Anadea
 
Calabash my understanding
Calabash my understandingCalabash my understanding
Calabash my understanding
FARHAN SUMBUL
 
applet using java
applet using javaapplet using java
applet using java
Kartik Kalpande Patil
 
Cordova: APIs and instruments
Cordova: APIs and instrumentsCordova: APIs and instruments
Cordova: APIs and instruments
Ivano Malavolta
 
Testing desktop apps with selenium
Testing desktop apps with seleniumTesting desktop apps with selenium
Testing desktop apps with selenium
Filip Braun
 
SeConf_Nov2016_London
SeConf_Nov2016_LondonSeConf_Nov2016_London
SeConf_Nov2016_London
Pooja Shah
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3
Rob Gietema
 
Electron - Build cross platform desktop apps
Electron - Build cross platform desktop appsElectron - Build cross platform desktop apps
Electron - Build cross platform desktop apps
Priyaranjan Mohanty
 

What's hot (20)

Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScript
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
 
Xamarin.iOS introduction
Xamarin.iOS introductionXamarin.iOS introduction
Xamarin.iOS introduction
 
Testing Mobile JavaScript
Testing Mobile JavaScriptTesting Mobile JavaScript
Testing Mobile JavaScript
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Building testable chrome extensions
Building testable chrome extensionsBuilding testable chrome extensions
Building testable chrome extensions
 
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNAOGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
OGDC2012 Cross-Platform Development On Mobile Devices_Mr.Takaaki Mizuno_DeNA
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Accessors Vs Direct access to properties & Design Pattern
Accessors Vs Direct access to properties & Design PatternAccessors Vs Direct access to properties & Design Pattern
Accessors Vs Direct access to properties & Design Pattern
 
Calabash Andoird + Calabash iOS
Calabash Andoird + Calabash iOSCalabash Andoird + Calabash iOS
Calabash Andoird + Calabash iOS
 
Calabash my understanding
Calabash my understandingCalabash my understanding
Calabash my understanding
 
applet using java
applet using javaapplet using java
applet using java
 
Cordova: APIs and instruments
Cordova: APIs and instrumentsCordova: APIs and instruments
Cordova: APIs and instruments
 
Testing desktop apps with selenium
Testing desktop apps with seleniumTesting desktop apps with selenium
Testing desktop apps with selenium
 
SeConf_Nov2016_London
SeConf_Nov2016_LondonSeConf_Nov2016_London
SeConf_Nov2016_London
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3
 
Electron - Build cross platform desktop apps
Electron - Build cross platform desktop appsElectron - Build cross platform desktop apps
Electron - Build cross platform desktop apps
 

Similar to Titanium appcelerator best practices

BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...
BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...
BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...Whymca
 
Voiture tech talk
Voiture tech talkVoiture tech talk
Voiture tech talk
Hoppinger
 
React native
React nativeReact native
Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBrian Sam-Bodden
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
Sang Don Kim
 
Extending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptExtending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScript
Roy Clarkson
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
Vibrant Technologies & Computers
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
Birol Efe
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
Android - Android Application Configuration
Android - Android Application ConfigurationAndroid - Android Application Configuration
Android - Android Application Configuration
Vibrant Technologies & Computers
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
Chris Cowan
 
Intro To webOS
Intro To webOSIntro To webOS
Intro To webOS
fpatton
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbai
CIBIL
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
[2015/2016] Apache Cordova
[2015/2016] Apache Cordova[2015/2016] Apache Cordova
[2015/2016] Apache Cordova
Ivano Malavolta
 
Android - Anatomy of android elements & layouts
Android - Anatomy of android elements & layoutsAndroid - Anatomy of android elements & layouts
Android - Anatomy of android elements & layouts
Vibrant Technologies & Computers
 
Introduction to Palm's Mojo SDK
Introduction to Palm's Mojo SDKIntroduction to Palm's Mojo SDK
Introduction to Palm's Mojo SDK
Brendan Lim
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
xMartin12
 

Similar to Titanium appcelerator best practices (20)

BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...
BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...
BEST PRACTICES PER LA SCRITTURA DI APPLICAZIONI TITANIUM APPCELERATOR - Aless...
 
Voiture tech talk
Voiture tech talkVoiture tech talk
Voiture tech talk
 
React native
React nativeReact native
React native
 
Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion Workshop
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
 
Extending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptExtending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScript
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Android - Android Application Configuration
Android - Android Application ConfigurationAndroid - Android Application Configuration
Android - Android Application Configuration
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Intro To webOS
Intro To webOSIntro To webOS
Intro To webOS
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbai
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
[2015/2016] Apache Cordova
[2015/2016] Apache Cordova[2015/2016] Apache Cordova
[2015/2016] Apache Cordova
 
Android - Anatomy of android elements & layouts
Android - Anatomy of android elements & layoutsAndroid - Anatomy of android elements & layouts
Android - Anatomy of android elements & layouts
 
Introduction to Palm's Mojo SDK
Introduction to Palm's Mojo SDKIntroduction to Palm's Mojo SDK
Introduction to Palm's Mojo SDK
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
 

More from Alessio Ricco

Co-design tools and techniques - world usability day rome 2015
Co-design tools and techniques - world usability day rome 2015Co-design tools and techniques - world usability day rome 2015
Co-design tools and techniques - world usability day rome 2015
Alessio Ricco
 
Mobile1st ux/ui with Titanium
Mobile1st ux/ui with TitaniumMobile1st ux/ui with Titanium
Mobile1st ux/ui with Titanium
Alessio Ricco
 
Fifty shades of Alloy - tips and tools for a great Titanium Mobile development
Fifty shades of Alloy - tips and tools for a great Titanium Mobile developmentFifty shades of Alloy - tips and tools for a great Titanium Mobile development
Fifty shades of Alloy - tips and tools for a great Titanium Mobile development
Alessio Ricco
 
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppoIl lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
Alessio Ricco
 
Ti.conf titanium on firefoxos
Ti.conf titanium on firefoxosTi.conf titanium on firefoxos
Ti.conf titanium on firefoxos
Alessio Ricco
 
Titanium Mobile and Beintoo
Titanium Mobile and BeintooTitanium Mobile and Beintoo
Titanium Mobile and Beintoo
Alessio Ricco
 
Titanium appcelerator sdk
Titanium appcelerator sdkTitanium appcelerator sdk
Titanium appcelerator sdk
Alessio Ricco
 
Titanium appcelerator my first app
Titanium appcelerator my first appTitanium appcelerator my first app
Titanium appcelerator my first app
Alessio Ricco
 
Titanium appcelerator kickstart
Titanium appcelerator kickstartTitanium appcelerator kickstart
Titanium appcelerator kickstart
Alessio Ricco
 
Un'ora sola ti vorrei
Un'ora sola ti vorreiUn'ora sola ti vorrei
Un'ora sola ti vorrei
Alessio Ricco
 
tempi e scaletta presentazione
tempi e scaletta presentazionetempi e scaletta presentazione
tempi e scaletta presentazioneAlessio Ricco
 
Interim presentation GSJ11
Interim presentation GSJ11Interim presentation GSJ11
Interim presentation GSJ11Alessio Ricco
 
documentazione e presentazione GSJ11 1/4
documentazione e presentazione GSJ11 1/4documentazione e presentazione GSJ11 1/4
documentazione e presentazione GSJ11 1/4Alessio Ricco
 
Writing videogames with titanium appcelerator
Writing videogames with titanium appceleratorWriting videogames with titanium appcelerator
Writing videogames with titanium appcelerator
Alessio Ricco
 
My personal hero
My personal heroMy personal hero
My personal hero
Alessio Ricco
 

More from Alessio Ricco (15)

Co-design tools and techniques - world usability day rome 2015
Co-design tools and techniques - world usability day rome 2015Co-design tools and techniques - world usability day rome 2015
Co-design tools and techniques - world usability day rome 2015
 
Mobile1st ux/ui with Titanium
Mobile1st ux/ui with TitaniumMobile1st ux/ui with Titanium
Mobile1st ux/ui with Titanium
 
Fifty shades of Alloy - tips and tools for a great Titanium Mobile development
Fifty shades of Alloy - tips and tools for a great Titanium Mobile developmentFifty shades of Alloy - tips and tools for a great Titanium Mobile development
Fifty shades of Alloy - tips and tools for a great Titanium Mobile development
 
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppoIl lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
Il lato oscuro della forza - L'eterna lotta tra progettisti e team di sviluppo
 
Ti.conf titanium on firefoxos
Ti.conf titanium on firefoxosTi.conf titanium on firefoxos
Ti.conf titanium on firefoxos
 
Titanium Mobile and Beintoo
Titanium Mobile and BeintooTitanium Mobile and Beintoo
Titanium Mobile and Beintoo
 
Titanium appcelerator sdk
Titanium appcelerator sdkTitanium appcelerator sdk
Titanium appcelerator sdk
 
Titanium appcelerator my first app
Titanium appcelerator my first appTitanium appcelerator my first app
Titanium appcelerator my first app
 
Titanium appcelerator kickstart
Titanium appcelerator kickstartTitanium appcelerator kickstart
Titanium appcelerator kickstart
 
Un'ora sola ti vorrei
Un'ora sola ti vorreiUn'ora sola ti vorrei
Un'ora sola ti vorrei
 
tempi e scaletta presentazione
tempi e scaletta presentazionetempi e scaletta presentazione
tempi e scaletta presentazione
 
Interim presentation GSJ11
Interim presentation GSJ11Interim presentation GSJ11
Interim presentation GSJ11
 
documentazione e presentazione GSJ11 1/4
documentazione e presentazione GSJ11 1/4documentazione e presentazione GSJ11 1/4
documentazione e presentazione GSJ11 1/4
 
Writing videogames with titanium appcelerator
Writing videogames with titanium appceleratorWriting videogames with titanium appcelerator
Writing videogames with titanium appcelerator
 
My personal hero
My personal heroMy personal hero
My personal hero
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

Titanium appcelerator best practices

  • 1. BEST PRACTICES in apps development using TITANIUM APPCELERATOR Alessio Ricco @alessioricco 1
  • 2. Software Quality characteristic (user point of view) • Adaptability: is the app able to run in different environments ? • Accuracy: how well does your app do the job ? • Correctness: is your app able to do the job ? • Efficiency: minimizing system resources • Integrity: is your app secure ? • Reliability: does it crash ? • Robustness: does your app handle invalid inputs ? • Usability: is it easy to learn how to use it ? USERS notice STABILITY and PERFORMANCE 2
  • 3. Software Quality characteristic (developer point of view) • Flexibility: can you adapt the app for other uses ? • Maintanability: debug, improve, modify the app • Portability: adapting the app for other platforms • Readability: source code is easy to understand • Reusability: using parts of your code in other apps • Testability: the degree to which you can test the app • Understandability: can you understand what the app does and how it does it ? DEVELOPERS needs RAPIDITY and READABILITY 3
  • 4. Software Quality characteristic User side: STABLE (applications must have a predictive behaviour) PERFORMANT (speed must approach the speed of cpu) Developer side: RAPID (development must be fast) READABLE (code must be easy to understand) 4
  • 6. Avoid the global scope • NO GARBAGE COLLECTION In the global scope not null objects cannot be collected • SCOPE IS NOT ACCESSIBLE FROM MODULES app.js is not accessible within CommonJS modules app.js is not accessible within other contexts (windows) • Always declare variables • Always declare variables inside modules or functions • Assign global objects to null after the use 6
  • 7. Nulling out object references // create ui objects var window = Ti.UI.createWindow(); var myView = myLibrary.createMyView(); win.add(myView); win.open(); // remove objects and release memory win.remove(myView); myView = null; // the view could be removed by the GC 7
  • 8. Keep local your temp var // immediate functions help us to avoid // global scope pollution var sum = (function() { var tmpValue = 0; // local scope for (var i = 0; i < 100; i++) { tmpValue += i; } return tmpValue; })(); // i, tmpValue are ready for GC ! 8
  • 9. Use self calling functions // self calling function ( function() { var priv = 'I'm local!'; } )(); //undefined in the global scope alert(priv); 9
  • 10. Use namespaces Enclose your application's API functions and properties into a single variable (namespace). This prevent the global scope pollution- this protect your code from colliding with other code or libraries // declare it in the global scope var mynamespace = {}; mynamespace.myvar = “hello”; mynamespace.myfunc = function(param) {} 10
  • 11. Namespaces are extendable // extend and encapsulate by using self-calling functions (function() { function helper() { // this is a private function not directly accessible ! ! // from the global scope } myapp.info = function(msg) { // added to the app's namespace, so a public function helper(msg); Ti.API.info(msg) }; })(); // you could then call your function with myapp.info('Hello World'); DON'T EXTEND TITANIUM NAMESPACES !!!!! 11
  • 12. Understanding the closures A closure is a function together with a referencing environment for the non local variables of that function // Return a function that approximates the derivative of f // using an interval of dx, which should be appropriately small. function derivative(f, dx) { return function (x) { return (f(x + dx) - f(x)) / dx; }; } the variable f, dx lives after the function derivative returns.Variables must continue to exist as long as any existing closures have references to them 12
  • 13. Avoid memory leaks in global event listeners function badLocal() { // local variables var table = Ti.UI.createTableView(); var view = Ti.UI.createView(); // global event listener Ti.App.addEventListener('myevent', function(e) { // table is local but not locally scoped table.setData(e.data); }); view.add(table); return view; }; Consider to use callback functions instead of custom global events Place global event handlers in app.js Rule : global events handle global objects 13
  • 14. Lazy script loading Load scripts only when they are needed JavaScript evaluation is slow, so avoid loading scripts if they are not necessary // load immediately var _window1 = require('lib/window1').getWindow; var win1 = new _window1(); win1.open() win1.addEventListener('click', function(){ ! // load when needed ! var _window2 = require('lib/window2').getWindow; ! var win2 = new _window2(); ! win2.open() }) BE AWARE: Some bugs could not be discovered until you load the script... 14
  • 15. Cross Platform BRANCHING useful when your code is mostly the same across platforms but vary in some points // Query the platform just once var osname = Ti.Platform.osname;var isAndroid = (osname == 'android') ? true : false;var isIPhone = (osname == 'iphone') ? true : false; // branch the code if (isAndroid) { // do Android code ... } else { // do code for other platforms (iOS not guaranteed) ... }; // branch the values var myValue = (isAndroid) ? 100 : 150; 15
  • 16. Cross Platform: branch // Query the platform just once var osname = (Ti.Platform.osname == 'ipod') ? 'iphone' : Ti.Platform.osname; os = function(/*Object*/ map) { var def = map.def||null; //default function or value if (map[osname]) { if (typeof map[osname] == 'function') { return map[osname](); } else { return map[osname]; } } else { if (typeof def == 'function') { return def(); } else { return def; } } }; // better than if statement and ternary operator. var myValue = os({ android: 100, ipad: 90, iphone: 50 }); 16
  • 17. Cross Platform: JSS PLATFORM-SPECIFIC JS STYLE SHEETS (JSS) JSS separate presentation and code. module.js var myLabel = Ti.UI.createLabel({ ! text:'this is the text', ! id:'myLabel' }); module.jss #myLabel { ! width:149; ! text-align:'right'; ! color:'#909'; } for platform specific stylesheets you can use module.android.jss and module.iphone.jss, but module.jss have the precedence. 17
  • 18. Images Minimize memory footprint Image files are decompressed in memory to be converted in bitmap when they are displayed. No matter the .png or .JPG original file size Width Height Colors Footprint 320 480 24bit 450KB 640 960 24bit 1800KB 1024 768 24bit 2304KB 2304KB 2048 1536 24bit 9216 18
  • 19. Image optimization • use JPG for displaying photos- use PNG for displaying icons, line-art, text • use remove() when the image is not visible on screen • set image views to null once no longer need those objs • resize and crops images to the dimensions you need • resize images to minimize file storage and network usage • cache remote images (https://gist.github.com/1901680) 19
  • 20. Database Release the resultset as soon as you can exports.getScore = function (level) { ! var rows = null; ! var score= 0; ! try { ! ! rows = db.execute( "select max(score) as maxscore from score where level=?", level ); ! ! if( rows.isValidRow( )) { ! ! Ti.API.info( "SCORE: (score,level) " + rows.field( 0 ) + ' ' + level ); ! ! score= rows.field( 0 ) ! ! } else { ! ! Ti.API.info( "SCORE: error retrieving score [1]" ); ! ! } ! } ! catch (e) { ! ! Ti.API.info( "SCORE: error retrieving score [2]" ); ! } ! finally { ! ! rows.close( ); ! } ! return score; } 20
  • 21. Database Close the database connection after insert and update var db = Ti.Database.open('myDatabase'); try{ ! db.execute('BEGIN'); // begin the transaction ! for(var i=0, var j=playlist.length; i < j; i++) { ! var item = playlist[i]; ! ! db.execute('INSERT INTO albums (disc, artist, rating) VALUES ! (?, ?, ?)', !! item.disc, item.artist, item.comment); ! ! } ! db.execute('COMMIT'); } catch (e){ ! Ti.API.info( "SCORE: error retrieving score [2]" ); } finally { ! db.close(); } 21
  • 22. Database Minimize your database size • Big Databases increases your app package file size • The database is duplicated on your device because is copied to the ApplicationDataDirectory • On some Android releases the installer cannot uncompress assets over 1MB (if you have a 2MB database you need some workarounds) Keep your db small and populate it on the 1st run ! read sql-lite FAQ: http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html 22
  • 23. Style and convention Learn and follow language rules, styles and paradigms javascript isn't c# or java or php titanium appcelerator is not just javascript Follow coding style best practices Naming Conventions Indentation Comments Style Follow language related communities and forums don't reinvent the wheel learn community best practices 23
  • 24. Language Rules Learn and follow language rules, styles and paradigms javascript isn't c# or java or php titanium appcelerator is not just javascript Follow coding style best practices Naming Conventions Indentation Comments Style Follow language related communities and forums don't reinvent the wheel learn community best practices 24
  • 25. Language Rules Always declare the variables When you fail to specify var, the variable gets placed in the global context, potentially clobbering existing values. Also, if there's no declaration, it's hard to tell in what scope a variable lives. So always declare with var. 25
  • 26. Language Best Practices Use the Exactly Equal operator (===) comparing two operands of the same type is, most of the time, what we need var testme = '1'; if(testme == 1) // '1' is converted to 1 { ! // this will be executed } var testme = '1'; if(testme === 1) { ! // this will not be executed } 26
  • 27. Language Best Practices Is better wrap self functions with parenthesis var myValue = function() { //do stuff return someValue; }(); // the same code, but it's clear that myValue is not a function var myValue = (function() { //do stuff return someValue; })(); 27
  • 28. References Titanium Appcelerator online documentation http://docs.appcelerator.com/ Code Complete 2nd Edition – Steven C. McConnell - Microsoft Press http://www.cc2e.com/Default.aspx SQLite Optimization FAQ http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html Douglas Crockford http://javascript.crockford.com/ Google Javascript Style Guide http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml TwinsMatcher http://itunes.apple.com/app/twinsmatcher/id429890747?mt=8 @alessioricco http://www.linkedin.com/in/alessioricco 28

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n