5 June 2014
Notes from coding in Swift

I had to find out what Swift is all about so I thought using real production code will be a good idea.

I’ve taken the short task of porting the Sequencer code from Objective-C to Swift (result is here).

The Sequencer Obj-C code uses blocks extensively so the resulting Swift code revolves around closures.

It wasn’t a swift to do, but here are some stuff I learned along the way:

I suggest opening up the resulting file Sequencer.swift and the Objective-C source Sequencer.h and Sequencer.m

Defining Closures

I started by converting the blocks definitions to closure definitions.

Objective-C uses typedef for that:

typedef void(^SequencerNext)(id result);
typedef void(^SequencerStep)(id result, SequencerNext next);

In swift, this can be done with typealias:

typealias SequencerNext = (AnyObject? -> Void)
typealias SequencerStep = (AnyObject?, SequencerNext) -> Void

There’s a lot to see here, but focus on the, but the code pretty much speaks for itself. Except for the question mark, but we’ll get to that soon.

Void is still okay

As you can see from the code above, closures can be defined to return no value.

(Int, String) -> Void

AnyObject

I was looking for the equivalent of id and was tempted to use NSObject. Finally I found that the answer is AnyObject.

The only difference you can’t set it to nil. Take a look at Optionals for an answer.

Optionals

Optionals offer a variable with either a typed value or no value at all.

This is done by a question mark:

var str: String?

You can resolve the optional by using the ! sign:

println(str!)

When str is nil, it will throw an exception.

Declaring arrays

Next up was declaring the array of steps. The Obj-C way is:

NSMutableArray *steps;

Notice that it’s mutable and can store any kind of object. Now the Swift code goes directly into the class definition:

var steps: SequencerStep[] = []

This is also mutable, noted by the var keyword. It’s now typed to only accept SequencerStep closures. It’s also already initialized to an empty array.

Functions

From that point, it was simply a matter of directly porting the Sequencer’s methods from Obj-C to Swift.

It’s all straight forward, but two things can be noticed here:

1. Operator overloading

Didn’t we agree this was a bad practice? What does the following line do?

steps += step

Answer: the same as the next line:

steps.append(step)

I personally prefer the second.

2. Inferring Types

Again, powerful closures can be written with very little characters in them. Take a look at this:

step(result, { result: AnyObject? in return self.runNextStepWithResult(result) })

vs. this:

step(result, { self.runNextStepWithResult($0) })

They both do the same thing. The $0 knows its type and the compiler is happy.

The syntax might only be understood by the writer of the code. It seems this is the recommended way.

Summary

After getting used to the new syntax and new concepts it all went smoothly.

Finally there is no need for an header file. This cuts done almost 1/4 of the code.

The code is also notably shorter, but this comes at the cost of readability.

Will this kill Objective-C? We’ll have to wait and see.

Let’s talk more on Twitter (@ketacode)

10 May 2014
The secret for creating amazing products

I’m gonna share the secret for creating awesome products your users will love.

I’ll get to that in a bit, but before that I’m going to share my experience from today’s soccer session with my friends.

We met at the regular court and divided all the players into two teams. For some reason, the person who chose my team had no idea who plays well and who sucks. The other team had great players and the people on my team were about to raise a white flag before we even started playing.

The game started and to everyone’s surprise we found out we were playing so much better than the other team. Well, we won 5:0. Underdogs can win, who knew?

How could that be? They had the better players. What I’ve noticed is that this knowledge drove each one of us to give his best to the team.

We cared more. When someone lost the ball, he ran as fast as he could to defend. When someone passed the ball to the wrong side, he cared and tried to get it back. The strikers knew we won’t have a lot of chances so they scored each one they had.

We weren’t making a product, but we did produce something: a win.

So what’s the secret? You probably know it by now. The secret is to care more.

Care more to make the user experience amazing.

Care more about what your users feel.

Care more for your new users.

Care more for your existing users.

Care more when the pixels aren’t aligned.

Care more about the texts your users see.

Care more when a team member needs help.

Care more before your user is a user.

Care more after a user leaves.

Care more and win.

15 March 2014
Move until you see it

Chess

Here’s a good advice for playing Chess:

"Don’t move until you see it"

There’s one best move to make and it’s your job to find it. It’s much easier to take the first move that seems good enough. It’s much harder to think each move through and follow the consequences. The ones who have the patience and stubbornness to do so - win.

I’m not a Chess player, I barely know the rules of the game.

Software Development

I’m a developer and I’d like to offer a different advice:

"Move until you see it"

The development process is also full of small moves.

- How should I name this method so my teammates understand it?

- Is it okay to use a global variable for this bug-fix?

- Should I encapsulate this in a new object?

- What framework should I use to solve this task?

Each task can be solved with many different moves. Some are very poor choices, others might be okay and some are pure genius. Yes, even in programming, some “moves” are better than others.

One of them is the best. It’s your job to find it.

In Chess, you only get one opportunity to take the correct move, but programming allows you to play around and find it.

So move a lot and start seeing it. It happens that the simpler moves to spot are the poor choices.

Yes, it’s easier to add a global variable to solve a bug, but what goes around comes around and that small hack will hunt you in the future. And yes, it’s easier to copy-paste code instead of making things DRY, but then each change multiplies work.

So go play and find the right move. And keep moving until you see it.

Let’s talk about this on Twitter, I’m @ketacode.

1 March 2014
5 Javascript debugging tips you’ll start using today

I’ve used printf debugging since forever and I always seem to solve my bugs faster that way.

Some cases calls for better tools so here are some gems that I’m sure you’ll find useful:

1. debugger;

As I’ve mentioned before, you can use the “debugger;” statement to force a breakpoint in your code.

Need a conditional breakpoint? Just wrap it with an IF clause:

if (somethingHappens) {

    debugger;

}

Just remember to remove these before going live.

2. Break on node changes

Sometimes the DOM just gets a mind of its own. Weird changes take place and it’s hard to get to the source of the problem.

The Chrome Developer Tools has one super useful trick for debugging this. It’s called "Break on…" and you can find it by right clicking a DOM node on the elements tab.

Breakpoints can be set when the node is removed, the node’s attributes change or one of its subtree nodes changes.

image

3. Ajax breakpoints

XHR Breakpoints, or Ajax breakpoints as I call them, allow to break when a desired Ajax call is made.

This is an amazing tool when debugging your web app’s networking.

image

4. Emulate different mobile devices

Chrome added interesting mobile emulation tools that will make your life much easier.

Find them by choosing any tab that isn’t the Console tab, press esc key on your keyboard and choose the device you wish to emulate.

You won’t get a real iPhone, but the dimensions, touch events and user agent will be emulated for you.

image

5. Improve your site with Audits

YSlow is a great tool. Chrome also includes a similar tool under the developer tools called Audits.

Take a quick audit of your site and get useful and practical tips for optimizing it.

image

What else?

I can’t imagine developing without these tools. I’ll post more tricks as I find them, so stay tuned.

Find me on twitter: @ketacode

17 February 2014
Javascript is hard. Let’s not keep it that way.

Javascript is hard. I know, I’ve been programming in it since the GeoCities era.

Yeah, it was only a few lines of code back then, but today entire web apps are built around it ((frontend and backend). Thats’ pretty insane for a language that hides your errors until it meets the user’s browser.

Coding without a compiler is super hard so I do my best to keep the code as simple as possible. This becomes challenging as the codebase grows and more developers are added to the team.

I love Javascript and eager to change all that. The computer is so much better than us at detecting issues and keeping our code organized. I’m looking for the best tools to deliver a maintainable codebase.

Here are some libs and tools my team and I already use today:

Backbone

Backbone keeps everything in its place. It’s an MVC framework (sorta), but the important thing is it breaks your code into reusable modules.

I have much more to write about keeping backbone code ticking well, but I’ll keep that for a future post.

Requirejs

Requirejs breaks the code into modules and maps the dependencies between them.

I once hated requirejs. It just wasn’t working for real projects. Version 2 changed all that and now I have no idea how we maintained the project without it.

We use it to break the project into logical files. Each model, view, router, whatever gets its own file (Like a “real” programming language).

It also allows to easily port modules from one project to another without going insane.

r.js optimizer

Requirejs comes with the r.js optimizer that can concatenate your entire project into one file (and much more). This usually makes your code load faster.

A side effect of optimizing is the detection of typos and lowercase/uppercase issues while loading your files. Better now then on the user’s browser.

SourceMaps with UglifyJS

We use UglifyJS(2) to minify the code after the optimization with r.js. There’s a great feature that allows to generate source maps.

This maps the minified code to the original code. When faced with a bug in the real world, Chrome lets you debug it like it isn’t minified at all.

Errorception

"What you don’t know can’t hurt you" - Novice Javascript developer.

Think of all the bugs happening in the browsers of your users. You just have no idea about them. You’ll probably want to catch uncaught exception and report to your server.

We rolled out our own solution for that, but then decided errorception just does it better. Bugs will be collected with their stack traces and.

WebStorm

We love Sublime Text, but WebStorm is the winner for larger projects. Yes, it takes forever to load, but once it does, you get so much benefits out of it.

It understands your code, shows you warnings and errors and has great Git integration. History and blames are a click away and it has a wonderful merge tool.

Oh, we also use it to debug the node.js code and it’s surprisingly good.

JSHint

JSHint is an impressive tool. It protects us from common javascript gotchas and can make sure the entire team is using the same coding conventions.

It’s already baked into WebStorm, but for some reason it’s not on by default. Enable it from Preferences and you’re good to go.

Jasmine + Phantomjs

Unit testing isn’t always easy, but with Jasmine and phantomjs it becomes pretty simple.

We found out it’s more reasonable to test the models. It’s a good idea to keep the data-logic inside the models so it could be easily tested.

We have a lot more to learn about testing our code. The main thing I’d like to do is add it into the IDE and we’ll probably migrate over to  using Karma in the future.

Jenkins

We configured Jenkins to “build” the project after each commit. Yes, “build” is a weird concept for a dynamic language, but we do transform it with the r.js optimizer, minifying with UglifyJS(2) and add some extra pulp.

The build process also runs the tests on each commit and fails the build if the tests are broken.

Once you break the build, Jenkins will email you and ask you to fix it.

Are we missing anything obvious?

I’m probably only touching the tip of the iceberg with these libs and tools.

Let me know if I’m missing out on other great tools. I’d love to make Javascript easier.