Confessions
of a Traitor
How Objective C Made Me a Better
JavaScript Programmer



@szafranek
Game developer
at Wooga


Front-end architect
at Nokia


Front-end developer,
manager at Roche
github.com/wooga/Pocket-Island




The last HTML5 project I was a part of is now available as open source.
In May 2012, after 7 years of professional front-end development, I started to work on native
iOS game.
[self
   learn:@"Objective C"
];
We make our tools,
our tools make us
• C with class-based OOP
• [syntax awkward:YES];
• Compiled
• No garbage collection!
[Disclaimer]

I will not try to convince you that JavaScript should be more like other languages.
Yet we can be more effective JS developers by learning something from others.
JavaScript
 AD 2004
-----------------------------------------------------------------
 Language       files          blank        comment           code
 -----------------------------------------------------------------
 Javascript       100           3764           1858          22258
 HTML               9             73             23            690
 Ruby               4             90             15            237
 Bourne Shell       2             13              0             27
 -----------------------------------------------------------------
 SUM:             115           3940           1896          23212
 -----------------------------------------------------------------




Codebase size of Pocket Island. The project didn’t use external libraries.
-----------------------------------------------------------------
Language       files          blank        comment           code
-----------------------------------------------------------------
Javascript       717          79132         184499         425289
HTML             452          84159           4819         198471
XML              133           2155           1391         122219
Java             527          10215           6633          42287
CSS               94           3067           2101          23727
Ruby              33            599            146           1794
XSLT               1             57             29           1453
Bourne Shell      47            285            293            865
Python             5            244            256            828
XSD                2              0              2            244
JSP                4              7              0             92
DTD                1             37             32             92
Perl               2             26              0             55
DOS Batch          4              4              1             18
-----------------------------------------------------------------
SUM:            2022         179987         200202         817434
-----------------------------------------------------------------



Codebase size of my previous JavaScript project. That one included several external libraries.
JavaScript
 AD 2004
JavaScript
 AD 2012
Building
• minification
    • linting
    • unit testing
    • deployment
    • template processing
    • much more
Currently Grunt offers over 200 plugins.
Automate




* Let machines do what they're best at:

    * catching silly mistakes

    * optimization

    * boring but necessary tasks
Unit tests
Everybody has heard about unit tests, but have you actually seen or wrote them?
Cr Buste
                                                                                                                                                         oss r.J
                                                                                                                                                            c S
                                                                                                                                                    En DOH heck
                                                                                                                                                      h
                                                                                                                                                    Fir ance
                                                                                                                                                   J3U eUnit JS
                                                                                                                                                JSN nit
                                                                                                                                                JSS Uni




writing tests?
                                                                                                                                              JST pec t
                                                                                                                                          JST e
                                                                                                                                             est st
                                                                                                                                            JSU .NE
                                                                                                                                          JSp nit T
                                                                                                                                       Jas ec
                                                                                                                                          U
                                                                                                                               Js- Jasm nit
                                                                                                                             Js- test ine
                                                                                                                                tes -dr
                                                                                                                               Mo t-run iver
                                                                                                                            No ch ne
                                                                                                                               de a r
                                                                                                                            QU u n i
                                                                                                                          Rh nit t
                                                                                                                       Rh Un
                                                                                                                         ino it
                                                                                                                      S OA Uni
                                                                                                                     Sin tes t
                                                                                                                   Su on.js t
                                                                                                                 Te ite
                                                                                                               Te st.M st
                                                                                                               st.S or
                                                                                                            Te im e
                                                                                                              stC pl
                                                                                                            Te ase e
                                                                                                      Un   T stI
                                                                                                           yrt t
                                                                                                        itT le
                                                                                                           est
                                                                                                       Vo in
                                                                                                     YU ws g
                                                                                                  jsU I T
                                                                                                     nit est
                                                                                                  jsU Te
                                                                                              scr ni st
                                                                                                 ew ty
Is the number of JS unit testing frameworks higher than the number of JavaScript developers




                                                                                               wr -u n i
                                                                                                   u t
In Objective C world unit testing is supported out of the box.
“No one pays you
      for testing”


The above quote comes from a PHP talk I listened to recently.

* Don’t ask your boss or client if you can write tests – tests are part of the code, not
something extra
* The point of writing tests is to make you faster at delivering quality product, not slower.
* Tests enforce better coding style.
Getting started
1) Pick any framework


buster.js, js-test-driver, QUnit, Jasmine are all good places to start.
2) Start writing tests
Unit test is a function
       that tests
 another function
implementation
function factorial(n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n-1);
}




test
function testFactorial() {
    assert.equals(120, factorial(5));
}
3) Automate with test
      runner


If you haven’t already picked a framework with integrated runner, like buster.js or js-test-
driver, use testem to run your tests.

You will NOT keep writing tests if you don’t automate running them with Continous
Integration tool like Jenkins.
Test runner
     vs.
Unit testing
framework
Modern test runners can execute your tests in a variety of JS environments.
buster.js
      Framework and runner
      ... that doesn’t run on
      Windows. Yet.
Authors are working on it. Version 1.0 will run on Windows.
testem
Cross-platform test runner
Needs test framework
QUnit
Test framowork used by jQuery
http://szafranek.net/works/articles/javascript-unit-testing/
http://bit.ly/writing-testable-javascript




Presentation contains practical example of making typical jQuery-based code testable.
Static
analysis
Early warning system in an editor.
jslint
         jshint
Your sadly
      pathetic
      bleatings are
      harshing my
      mellow.


Douglas Crockford commenting on complaints about jslint being too restrictive.
This quote was one of the reasons to create jshint.
1) Make your intent
obvious
Anything that isn’t
                                          crystal clear to a
                                        static analysis tool
                                       probably isn’t clear
                                             to your fellow
                                            programmers,
                                                     either.

Highly recommended article on the value of static analysis, by John Carmack:
http://www.altdevblogaday.com/2011/12/24/static-code-analysis/
2) Catch mistakes early
Integrate jslint or jshint with your editor.
Automate




Use continuous integration to run static analysis checks on your code.
Refactoring
Improving
the design of code
without changing
its external behavior
Improving
the design of code
without changing
its external behavior
Goals

Before starting refactoring, think for a moment what you want to achieve.
Remove duplication


Extract method, extract variable
if (player.coins < budget.getMin()) {
    offerCredit();
}
if (friend.coins < budget.getMin()) {
    offerFriendCredit();
}


var min = budget.getMin();
if (player.coins < min) {
    offerCredit();
}
if (friend.coins < min) {
    offerFriendCredit();
}
Make your intent
clear obvious
[taskShortcut
         performSelector:selector
         withObject:param
      ];


Named parameters in Objective C encourage explicit naming.
data, t, manager
are not good names

formData, timeLeft,
urlRouter are better
Explanatory variables
button.setPosition(0,
     parseInt(parentDiv.height, 10) / 2
     - parseInt(border.size, 10) / 2
  );



  var verticalCenter =
     parseInt(parentDiv.height, 10) / 2
     - parseInt(border.size, 10) / 2;

  button.setPosition(0, verticalCenter);


It’s worth to introduce a variable to communicate intention clearly, even if it doesn’t reduce
duplication.
Design patterns


Design patterns make the intent of the design easy to see.
If you are using a pattern, make sure it’s communicated through naming.
Clean code first,
optimization second
Premature
optimization
is the root of
all evil.
Improving
the design of code
without changing
its external behavior
Tests!

How do you verify that behavior didn’t change?
Tests?
Refactoring without tests (aka “happy development”) is all too common.
It’s not a very responsible thing to do.
IDE

The problem with refactoring JavaScript:
poor tool support -> makes refactoring require courage -> makes refactoring less likely to
happen.

Search and replace doesn’t constitute “tool support” for refactoring – it’s only text-based and
doesn’t guarantee that the semantics of your program will be preserved.
My reaction to the word “IDE”...
... was deeply rooted.
WebStorm IDE has good support for essential refactorings.
•Web Storm
      •...
      •...
      •...
      •Cloud9
      •...?
We need better and more tools for refactoring JavaScript!
Automate




Refactoring has to be performed by a human, but good tool (like WebStorm) can make it
much safer and easier.
auto
Unit testing  mate
         auto
Static analysis
              mate
         auto
Refactoringmat
                 e
                @szafranek
Thank you!
Image credits:
eclectic echoes    Philippe Semeria
The Facey Family   Nick Treby
chrisnb20          QuakeCon
Esther Gibbons

WebConf_Riga_Confessions of-a-traitor_Krzsysztof Szafranek