Find every other element in an array with Swift

There are times when you need to extract a subset of an array. For example, you might need to find all elements in an array at an odd index. Or maybe you need all items at an even index. In other words, you're looking for every "other" element in an array. This might seem like a non-trivial task and you may have tried this before using a for loop as follows:

var itemsAtEvenIndices = [Int]()
let allItems = [1, 2, 3, 4, 5, 6, 7]

var index = 0
for item in allItems {
  if index % 2 == 0 {
    itemsAtEvenIndices.append(item)
  }
  index += 1
}

This isn't a bad approach, but we can do better. A slightly nicer way would be to use the enumerated() method that is defined on Sequence:

var itemsAtEvenIndices = [Int]()
let allItems = [1, 2, 3, 4, 5, 6, 7]

for (index, item) in allItems.enumerated() {
  if index.isMultiple(of: 2) {
    itemsAtEvenIndices.append(item)
  }
}

This works and saves you some bookkeeping because you don't have to increment the index in every iteration of the loop but you still have to define a mutable array that you append items to. Let's take a look at one last way to extract all items at even indices without any mutable arrays and without unneeded bookkeeping:

let allItems = [1, 2, 3, 4, 5, 6, 7]
let itemsAtEvenIndices = allItems.enumerated().compactMap { tuple in
  tuple.offset.isMultiple(of: 2) ? tuple.element : nil
}

The code above uses compactMap to transform tuples of (offset: Int, element: Int) into an array of [Int]. Since compactMap filters out all nil values and only keeps the Int values, we can use a ternary statement that checks whether tuple.offset.isMultiple(of: 2) is true. If it is, we return tuple.element and if it isn't, we return nil. The end result is the same as the previous two examples except it's cleaner and doesn't involve any mutable state, or intermediate variables.

If you want to learn more about compactMap, check out the following post I wrote: When to use map, flatMap and compactMap. If you have any questions, feedback, or just want to get in touch. Don't hesitate to reach out to me on Twitter.

Special thanks to Bas Broek for pointing out that tuple.offset.isMultiple(of: 2) is maybe a bit nicer than tuple.offset % 2 == 0.

Exploring protocols and protocol extensions in Swift

In 2015 Apple announced Protocol extensions at WWDC and went on to explain the idea of Protocol Oriented Programming (video here), I think every iOS developer got really exited when they saw this.

The ability to add default implementations to protocol methods through extensions makes it seem like everything we will ever build can and should be protocol based instead of inheritance based like we do in classical OOP. In this post, we'll explore protocols and protocol extensions to see what we can make them do.

Taking advantage of Protocols today

To take advantage of the awesomeness of Protocols we could think of a Protocol as a mixin more than an interface. I've seen people compare Protocols to interfaces in, for instance, Java. While they are similar they will become quite different once we get to use protocol extensions.

If we can provide default implementations for our Protocol methods we should look at Protocol as little mixins of functionality that can be used to enhance existing types. Mixins are not exactly new in programming and if you look at functional programming mixins are considered pretty important. The cool thing about a mixin (or Protocol) driven approach is that it avoids complex, confusing and inflexible class hierarchies. Instead you can provide multiple Protocols, or mixins, to compile an object with. By doing this, the object will be very explicit about what it can and can't do and the object type itself won't matter throughout your code. What does matter throughout your code is the fact that an object contains certain functionality. And to make sure that an object has certain functionality it conforms to a protocol you wrote. Since this could be pretty confusing if you don't use Protocol oriented programming yet, or if you've never heard of mixin based programming (or even Python's multiple inheritance model), we should probably look at an example now.

An example

So let's imagine that we're mapping out some part of the animal kingdom, let's start with an Animal class. This class will only contain the name of the animal and it's size:

class Animal {
  var name: String?
  var size: AnimalSize?
}

A subclass of animal will be Bird. A Bird will have an amount of legs and it will have a number of wings:

class Bird: Animal {
  var legs = 2
  var wings = 2
}

Now we'll also create a Reptile class which will have a favoriteTemperature property so we know when the Reptile will be nice and comfortable.

class Reptile: Animal {
  var favoriteTemperature = 37.0
}

A subclass of Reptile is a Crocodile, technically this is probably very incorrect, but that's okay, in our imaginary animal kingdom anything goes. The Crocodile will get a number of legs property, just like the bird. It won't get the wings though, flying crocodiles would be too scary for me.

class Crocodile: Reptile {
  var legs = 4
}

As you might have noticed both Bird and Crocodile have a legs property. But if we were to create an application where somebody could pass any Animal they'd like and we'd try to make it walk we could do a check similar to this:

func walk(animal: Animal) {
  if let a = animal as? Bird {
    print("walking an animal with \(a.legs) legs")
  } else if let a = animal as? Crocodile {
    print("walking an animal with \(a.legs) legs")
  }
}

But this approach is prone to error because if we add a new animal with legs we will need to add a new section to our if statement to make sure that we allow that legged animal to walk. Not very developer friendly and basically a bug waiting to happen. We can do better than this by using protocols. Let's refactor the Bird and Crocodile to implement a LeggedAnimal protocol:

protocol LeggedAnimal {
  var legs: Int { get set }
}

class BetterBird: Animal, LeggedAnimal {
  var legs = 2
  var wings = 2
}

class BetterCrocodile: Reptile, LeggedAnimal {
  var legs = 4
}

All I did was define a protocol that forces implementers of that protocol to add a legs property to their object that can be get and set. That's exactly what Bird and Crocodile already did so all we need to do is tell the outside world that we have implemented the LeggedAnimal protocol. Now we can also refactor the walk function:

func betterWalk(animal: LeggedAnimal) {
  print("walking an animal with \(animal.legs) legs")
}

Now that we have a protocol we can just make sure that anything we pass to the function is an implementer of the protocol we just wrote. Much cleaner and a lot less error prone. If we add new animals we just need to make sure that we make them comply with the LeggedAnimal protocol if we want them to be able to walk.

Wrapping up

In my own programs I only started making more use of protocols recently. I usually use them to make completely unrelated things relate to each other just like we did with the LeggedAnimal example. It's a small protocols like this that allow for very flexible modeling and less worrying about subclasses and superclasses. Less inheritance usually means less unused code in classes and that's a good thing.

The only downside at this moment is that you still have to provide an implementation of the required properties and methods. In swift 2.0 this will change because then you will be able to provide a default implementation via protocol extensions. These extensions will allow for even more flexible, DRY and powerful code. I'm looking forward to using those in my projects soon.

You can get the example code from this blogpost from my GitHub.

Icon fonts vs. svg icons

We can all agree that using png sprites for icons is not the most modern (or best) way to present icons on the web. Png is a rasterized format which means that if you try to make the image (or icon) larger, the quality will become worse. When browsers started properly supporting @font-face and svg some people chose to use icon fonts to serve their icons, others chose svg sprites to do this. These methods share the big benefit of scalability. This matters because our websites get viewed on many devices and you want your icons to be crisp on every device, not just the ones you optimized for by hand. This post is intended to give an overview of these two methods and to explore the benefits and drawbacks of each method. At the end of this post you will hopefully have an understanding of both svg icons and iconfonts and you'll be able to choose one of these icon delivery methods for your own projects.

TL;DR: The comparison is very close, both have their big upsides and no real big downsides. I'd say iconfonts win because they're a bit easier to use. Svg icons are a easier to position and manipulate. The code for this blogpost is on Github.

Getting set up

gulpfile

The first thing I'm going to compare is the set up process for each method. The method you end up choosing should not only work well but it should also be easy to manage. The first method I will set up is the iconfont. I will be using Gulp to automate the asset creation process. I made this decision because I use Gulp on all my projects. Also, Gulp seems like the right tool for this type of job; I don't want to create my assets by hand. The icons I'm going to use were created by Jamison Wieser for The Noun Project.

Icon font

Like I mentioned, I will be using Gulp to generate my assets. The gulp-iconfont plugin seems like a good plugin to generate a font with. I also used the gulp-iconfont-css plugin so I didn't have to create my own css template. With a couple of lines in my gulpfile and two plugins I managed to convert my svg icons into a font. Not bad!

svg icons

To make using the icons easy I will create a spritesheet that contains all my svg icons. I'll be using gulp for this as well, just like I did for the iconfont. I've set up my output in "defs" mode. Which means that I can use the icons like Chris Coyier descrives in this css-tricks.com post. This method only uses one gulp plugin but the fact that this gulp plugin uses svg-sprite which has a ton of options, it does seem a little less straightforward to set up. The output that was produced seems decent on first viewing so that's good.

Easiest to set up

Both methods are actually easy to set up within about 5-10 minutes. Therefor, this section will be a tie. Both methods are easy to set up and there isn't a clear winner.

Filesize

Something we should always take into consideration is the file size of the things we end up using. So, a simple comparison in filesize:

iconfont: 8kb (or 12kb if the svg font is used)
spritesheet: 25kb

Best filesize

The winner in this example is the iconfont. The iconfont is significantly less Kb than the spritesheet is.

Ease of use

Whenever I pick a technique I want to use, it has to be something that's easy to use. Of course it's important that something works well, is fast and lightweight and more but I feel like ease of use should be mentioned right alongside those requirements because in the end you might end up working with the tool or technique you chose for quite some time. So for my own sanity, I like something that's easy to use.

Implementing

To implement the iconfont all you have to do is add the stylesheet to the head  of your document. In order to use the icons you just create span  elements and give them the icon class. The second class you give them is your icon's name. An example:

Up arrow: <span class="icon icon-arrow_top"></span>

Easy enough, right? This results in the following rendered output:

Schermafbeelding 2015-04-16 om 19.51.31

 

To implement the svg spritesheet I needed a polyfill to make everything work. That's because IE doesn't support the <use> method for external svgs and I didn't want to include the whole svg inside of my html body. For more info refer to this css-tricks.com post. The html I ended up using looks like this:

Up arrow: <svg viewBox="5.0 -11.0  100.0 135.0" class="icon"><use xlink:href="assets/icons.svg/defs/svg/sprite.defs.svg#arrow_top"></use></svg>

This is quite a bit more complicated than the iconfont method. I had to figure out the proper viewBox settings for my icon and I have to do a lot more typing.

Positioning

When you want to position your icon with the iconfont method you'll run into some weird and complicated stuff eventually. That's because the iconfont is rendered as text so for example, there's line-height applied to it. This could lead to unpredictable and strange behavior in some cases.

When you use the spritesheet approach you get to decide almost everything. The sizing, positioning, display style, you can all directly manipulate it as if you're manipulating an image. So for positioning, the spritesheet is definitely better.

Styling

When you want to style your icons you're going to love the spritesheet approach. because you're working with actual svg icons you can set strokes, fill colors and everything. Just like you might do with any other svg! The iconfont however is flattened in a way. You can set a color for the whole icon bt you can't style individual sections, so the spritesheet is more customizable than the iconfont is.

The easiest to use method

Even though it's a little bit more work to implement, the spritesheet wins. It's easier to position and the more powerful styling options are also a big advantage over an iconfont. So the winner for this section is spritesheet, hands down.

Render quality

Personally I haven't seen the difference yet but there are definitely some potential rendering differences between the spritesheet and an iconfont. Because an iconfont is rendered by the browser as a font, it is also anti aliased. The result of this could be that your icons look less sharp if they're used as a font. Like I said, I haven't had any issues with this in the real world but the potential is there.

The best rendering method

Even though the rendering seems to be nearly identical the spritesheet wins here. That's because an iconfont can potentially suffer from a lack of sharpness due to anti aliasing of the browser.

Browser support

The @font-face method of embedding custom fonts is supported by all major browsers so it's very safe to use. The spritesheet method is supported by all browsers except for IE. However, a polyfill called svg4everybody is available so at the end of the day both methods are available on all major browsers.

The best browser support

Because the spritesheet method requires a polyfill and the iconfont doesn't I declare the iconfont the winner of the browser support section.

And the winner is..

After exploring and comparing both the iconfont and spritesheet approach I can honestly say that the comparison is very close. The iconfont is better at the implementation, more lightweight and it has better browser support. The spritesheet is more flexible, easier to work with and has great browser support if you include a polyfill.

Earlier in the article I mentioned that one of the major factors for me to decide on things like this is ease of use. And because of that I would say that the iconfont wins. The decision is really tough actually because I'm not a fan of how you have to mess around in order to position an icon with this technique. Nor am I a fan of the anti aliasing risks because I like my icons to be sharp and crisp. But iconfonts are lightweight, easy to use and implement in general and I've never come across a situation where I actually had to style parts of an icon rather than change the color of the entire icon. So, yeah, that concludes this post. Iconfonts win. If you beg to differ or have feedback for me, please send me a Tweet. I'd love to your opinions on this.

If you want to have a look at the source files I've used, the repo is on located right here on Github.

How to choose between rem and em

A few days ago I found this article that argues for using rem units when defining font sizes. Generally speaking this is good advice. The rem comes with great predictable behavior, just like pixels do. But the rem also comes with accessibility advantages. When a user changes the font size in their browser settings, the rem and em unit will both respect that and resize accordingly while the pixel unit doesn't. That's great news for the user. But how do you choose between rem or em? Time to go in depth on what these units do. First I'll explain how each unit works and what they do. Based on that I'll explain how you can make the decision for a sizing unit.

The rem unit

Since the rem unit is the easiest one to understand and use, it will be the sizing unit I start off with. The rem is relatively new but if you don't have to support IE8 anymore you can safely use it. Rem is short for "root em", that's because it is a lot like the em unit except it is relative to the root font size.

So, what does this all mean? The rem unit is a sizing unit that's related to font size. With default browser settings 1 rem should be equal to 16px. That is because the default browser font size is, you may have guessed it, 16px. So using rems is almost as easy as using pixels. Want to make something 80px wide? That will be 5 rem please.

More complicated things like 100px will require you to do some math but if you use something like Sass I recommend that you check out Bourbon.io, it provides a rem-calc function to help you calculate rems.

A workaround many people use is to set the body's main font-size to 10px so 1 rem equals 10px on their website instead of 16px which will make working with rems a lot easier. The cool thing about the rem unit is the fact that 1 rem will always be the same size everywhere on the page, no matter what.

The em unit

The em unit is a lot like the rem unit. The difference between them is that the rem unit is always relative the the root font size. The em unit is relative to it's containing element. An h1 that is directly inside of the body and has a font size of 2 em will have a font size of 32px if we assume the default browser font size is in tact. If you would add a link inside of that h1 and you would want that to be 24px you first instinct would probably be to use 1.5 em as a font-size for that anchor tag. Let's try this out.

So... what went wrong here? The header has a 2 em font size, the anchor is 1.5 em so the anchor should be smaller that the rest of the text, right? Except, the anchor is larger than the rest of the header text which makes no sense. Remember that I stated earlier that the em unit is relative to it's containing element? That's why the anchor is larger than the header text. The anchor is a child of the header so a 1.5 em font-size means that the anchor's font size should be 1.5 times the size of the anchor text.

This is something that makes the em a complicated unit to work with, you can imagine that deep nesting with multiple font sizes can get really ugly at some point. A simple demonstration:

What you see here is a list with a nested list. The outer list has a larger font size than the inner list. This happened because I set a 0.8 em font size on the ul tag. So when there's a nested list, this 0.8 em is relative to the 0.8 em font size the outer list already has. So the outer list is 80% the font size of the body. The nested list is 80% the font size of the outer list. Confused? I understand, the em isn't a very straightforward unit.

Making the decision

Now that we know how both units work we should be able to make an informed decision. So, should we use rem or do we use em for our sizing? The answer, according to me, should be both. Whenever you want to have absolute control over a size you probably want to use rem. An example would be an element that you would normally make 100px wide. You want that element to have the same size, no matter where in the document you use it, the size has to be 100px. That is a case where you should convert that 100px to rems.

However, there are cases like the link inside of an header element where you might not want to set an absolute size. You might want to say this header element should have a font size that is two times larger than the body text that it's above. That would mean that you want to use a 2 em font size because then you know that your header is always two times larger than the body text of the element. Taking this one step further you might want to say that the anchor tag's font size should be 75% percent of the header's font size. That's 0.75 em.

What I would like to conclude here is that both of these sizing units are extremely powerful. One is very good for setting absolute sizes that are still accessible and adaptable. The other is good for setting relative sizes, whenever something should be x times the size of something else, regardless how big, the em unit is your friend. I do think, however that the rem units should be the unit of choice in many situations. But especially with margins, paddings and certain spacing situations I have found the em unit to be the best choice because all those sizes are usually relative to another size and that's where the em shines bright.

So, next time you're faced with the rem vs. em decision I hope you think about the way they each work and make an informed decision. My rule of thumb is: rem replaces absolute pixel sizes, em is for relative sizes. If you have questions for me, feedback or want to get in touch you can always contact me on Twitter.

Consistency and discipline over motivation

One of the beautiful things about being a developer is that many of us actually have the opportunity to take an activity we enjoy, and make it our job. Many developers are happy to do some extra work or learn something when they're at home or in the weekend just because they are so eager to learn and play. While this is pretty awesome, it won't last forever. You won't be motivated to learn every single day. Especially once you start doing development as a full-time job. I experience this as well, sometimes I have a couple of days or even weeks where my motivation is through the roof. I'll get tons of work done and the days just fly by. On other days I just can't seem to get started, everything is distracting and the motivation just doesn't seem to be there. When I look at some of the more senior developers I know, it seems that they have moved past this phase. They always seem to be motivated and sometimes they just seem extra motivated. They just seem to have no shortage of the good stuff! How do they do this?

Is it motivation you should look for?

If you think about it, motivation isn't worth much. It's just not there all the time and you can't build a solid career based on it. When I was looking for ways to improve motivation I came across posts like this, telling me that I should get disciplined. Some went even further and said that motivation just isn't worth your time.

Because of these posts I started to realize that motivation is a great driver of productivity. But only when it's there. When motivation isn't there, every job seems like a chore. Have to adjust a form on a website? It sounds terrible when you're not motivated. You'd have to create a new input field, maybe change a database table and more. You get tired just by thinking about it. But then consider doing that same thing when you're motivated. You probably would get excited because you get to possibly improve the product and code base that you're working on. This isn't feasible in the long run though, when you want a job in development you'll need to train yourself to become more consistent, more disciplined. Motivation will be the bonus, not the requirement.

Changing motivation into discipline

If you want to be more disciplined you'll sometimes have to be pretty tough on yourself. There's rarely a valid excuse to not do what you're supposed to do. So instead of postponing things until you feel motivated or obliged to do them, just get started. If you do this, and are consistent about it, you'll see that it helps. I often find that it helps to not jump in headfirst like you would when you're super motivated but to just sit back first. Take 15-20 minutes to figure out what it is that you're going to build, what code are you going to write. Figure out what sub tasks there are and split them up in blocks that will take about 40 minutes to complete. If you do this, you will have a great structured overview of what you're going to do. You'll know how busy you are for the day or week and you'll be able to plan accordingly. During those 40 minute work cycles try to turn off notifications that might distract you. Discipline yourself to only check notifications in between your 40 minute cycles.

After a 40 minute cycle it's time to take a quick break. And try to make it an actual break, get up and grab a drink. If there's email or anything similar that requires your attention, take a peek. Reply if needed or add replying to your to-do list. Make it a part of a 40 minute cycle if the email requires you to figure something out in-depth. Otherwise, use the break or extend the break a little (but not too much, 10 minutes should be the maximum). In the beginning you might feel like you're restricting yourself because everything has to be thought about or planned in, you can't just start doing something and then do something else until you're out of motivation. That's fine, you are training yourself to have a consistent and disciplined workflow. If you find that 40 minutes is too long or too short for you you can always change the cycles. You could even do that on a day-to-day basis if you feel like it's appropriate for the tasks you're working on. I personally found after a few weeks that I prefer 50 minute cycles with 10-15 minute breaks.

The benefits are real

When I look at more senior developers I notice that many of them have a workflow similar to this. They take multiple short breaks throughout the day and between those breaks they tend to be very focused on the tasks they have to complete. They don't have their Slack open all the time and they work on a single thing at a time. And they are consistent about that. Everyday they seem to be able to flick the switch and go into work mode. Of course they still have more and less motivated days, but a motivated day will just make them super productive instead of only productive because being productive is their default setting.

So let's get out there and become consistently more disciplined!

Using Flexbox in the real world

The Flexbox module for css was built with the intent to make a more robust, less hacky way to layout elements on pages. When you're building a webpage you often don't know how high or wide every element could or should be. This can cause problems in certain layouts which lead to ugly hacks. Flexbox solves this widespread layout issue. The module has been in development for quite some time and the W3C gave the spec a "last call working draft" status back in september of 2014. The browser support for this module is very good if you don't have to support IE9 so you can safely use it. In this post I will provide a few code examples to show you how you can use Flexbox in some everyday situations.

Creating a filmstrip

Have you ever created a horizontally scrolling filmstrip kind of module? You know the size of the each element in the strip and the size of the containing element but the size of the inner element, the filmstrip itself is unknown. This would normally result in a layout like this and you would have to use Javascript or hardcode the size of the inner element to make this work.

So what would happen if you used Flexbox for this? Well, Flexbox allows an element to grow, not only on the y axis like an element normally does, but also on the x axis. It's one of the reasons Flexbox is really cool. Let's try this.

It's pretty neat, isn't it? Between the first and second example there's only three lines of code that are different. Okay, actually there's a little more but I'm not counting in the vendor prefixes because you don't have to write those if you use an autoprefixer. The first difference is that we give overflow-x: scroll; to the filmstrip container, that's just to make the contents scroll. The second step is to set display: flex; on the inner element. If you did only these two things, the items inside of the inner element will shrink to fit inside of their container. You don't want this so the last thing you do is add flex-shrink: 0; to the filmstip items. The shrink property has a value of 0(false) or 1(true). There's also a flex-grow  property, it's the same as the shrink property but it determines whether an element will grow or not.

Vertical centering

Ever since I started writing css this has been a problem. How do you center an element, with or without a known height, in a container that is or isn't flexible? No matter how you look at it, vertical centering is annoying. I've used hacks that would absolutely position the centered element at 50% from the top and then I would use a negative top margin to push the element towards the center. Another method is to use translating which is slightly cleaner but you still have to use position absolute and a top offset of 50%. You could display your stuff as if it's a table and then vertically center content which works well but it just doesn't feel right. It starts to feel plain wrong once you've tried to do this with Flexbox.

So in this example I've set up a container and inside of that container is an image. Flexbox is used to center the image both vertically and horizontally inside of it's containing element. The property that is used for vertical centering is align-items . The property that is centering horizontally in this example is justify-content . In my opinion, this is the best way to vertically align items I've seen.

Fitting things into a container

The filmstrip example gave this one away already but Flexbox can be used to fit an unknown number of items into a container. This is really nice if you have a couple of images but you can't really be sure of how many. You could optimize for a certain number, let's say four in the case of this example. And then for the edge cases where you have five images or more, you have Flexbox to make the images smaller so everything will still fit nicely into the containing element. Let's check it out.

All we had to do to achieve this is add display: flex; to the containing element. In the first example we saw that, by default, children of an element with display: flex; will shrink to fit inside of that container.

Conclusions and further resources

In this post I showed you three examples of what you can achieve with Flexbox and how you can do that. Note that we just used Flexbox for three small things and that I didn't mention Flexbox as a method of laying out your entire page. The reason for this is that Flexbox is not intended for that. There is a spec on the way for laying out your entire page and it's called grid.

If you're looking for a good overview of how Flexbox works I recommend that you visit this cheatsheet on css-tricks.com. This cheatsheet provides a lot of information on how you can use Flexbox and what properties it has. Lastly, if you're looking for more examples of what problems you can solve with Flexbox check out this "solved by Flexbox" page.

Service workers are awesome

In the war between native and web apps there's a few aspects that make a native app superior to a web app. Among these are features like push notifications and offline caching. A native app, once installed, is capable of providing the user with a cache of older content (possibly updated in the background) while it's fetching new, fresh content. This is a great way to avoid loading times for content and it's something that browser vendors tried to solve with cache manifests and AppCache. Everybody who has tried to implement offline caching for their webpages will know that the AppCache manifest files are a nightmare to maintain and that they're pretty mysterious about how and when they store things. And so the gap between native and web remained unchanged.

In comes the service worker

The service worker aims to solve all of our issues with this native vs. web gap. The service worker will allow us to have a very granular controlled cache, which is great. It will also allow us to send push notifications, receive background updates and at the end of this talk Jake Archibald mentions that the Chrome team is even working on providing stuff like geofencing through the service worker API. This leads me to think that the service worker just might become the glue between the browser and the native platform that we might need to close the gap once and for all.

If you watch the talk by Jake Archibald you'll see that the service worker can help a great deal with speeding up page loads. You'll be able to serve cached content to your users first and then add new content later on. You're able to control the caching of images that aren't even on your own servers. And more importantly, this method of caching is superior to browser caching because it will allow for true offline access and you can control the cache yourself. This means that the browser won't just delete your cached data whenever it feels the need to do so.

How the service worker works

When you want to use a service worker you have to install it first. You can do this by calling the register function on navigator.serviceWorker . This will attempt to install the service worker for your page. This is usually the moment where you'll want to cache some static assets. If this succeeds the service worker is installed. If this fails the service worker will attempt another install the next time the page is loaded, your page won't be messed up if the installation fails.

Once the service worker is installed you can tap into network requests and respond with cached resources before the browser goes to the network. For example, the browser wants to request /static/style.css . The service worker will be notified through the fetch event and you can either respond with a cached resource or allow the browser to go out and fetch the resource.

HTTPS only!!

Because the server worker is such a powerful API it will only be available through HTTPS when you use it in production. When you're on localhost HTTP will do but otherwise you are required to use HTTPS. This is to prevents man-in-the-middle attacks. Also, when you're developing locally you can't use the file:// protocol, you will have to set up a local webserver. If you're struggling with that, I wrote this post that illustrated three ways to quickly set up an HTTP server on your local machine. When you want to publish a demo you can use github pages, these are server over HTTPS by default so service workers will work there.

A basic server worker example

Browser support

Before I start with the example I want to mention that currently Chrome is the only browser that supports service workers. I believe Firefox is working hard to make an implementation happen as well and the other vendors are vague about supporting the service worker for now. This page has a good overview of how far the completion of service workers is.

The example

The best way to illustrate the powers of the service worker probably is to set up a quick demo. We're going to create a page that has ten pretty huge pictures on it, these pictures will be loaded from several resources because I just typed 'space' in to Google and picked a bunch of images there that I wanted to include on a webpage.

When I load this page without a service worker all the images will be fetched from the server, which can be pretty slow considering that we're using giant space images. Let's speeds things up. First create an app.js  file and include that in your page html right before the body tag closes. In that file you'll need the following script:

navigator.serviceWorker.register('worker.js')
    .then(function(){
        console.log("success!");
    },
    function(){
        console.log("failure..");
    });

This code snipper registers a service worker for our website. The register function returns a promise and when it gets resolved we just log the words 'success' for now. On error we'll log failure. Now let's set up the service worker.

// You will need this polyfill, at least on Chrome 41 and older.
importScripts('serviceworker-cache-polyfill.js');

var files_to_cache = [
    // an array of file locations we want to cache
];

this.addEventListener('install', function(evt){
    evt.waitUntil(
        caches.open("SPACE_CACHE")
            .then(function(cache){
                console.log("cache opened");
                return cache.addAll(files_to_cache);
            })
        );
    });

The code above creates a new service worker that adds a list of files to the "SPACE_CACHE" . The install eventHandler will wait for this operation to complete before it returns a success status, so if this fails the installation will fail as well.

Now let's write the fetch handler so we can respond with our freshly cached resources.

this.addEventListener('fetch', function(evt){
    evt.respondWith(
        caches.open("SPACE_CACHE").then(function(cache){
            return cache.match(evt.request).then(function (response) {
                return response || fetch(event.request.clone());
            });
        })
    );
});

This handler will take a request and match it against the SPACE_CACHE. When it finds a valid response, it will respond with it. Otherwise we will use the fetch API that is available in service workers to load the request and we respond with that. This example is pretty straightforward and probably a lot more simple than what you might use in the real world.

Debugging

Debugging service workers is far from ideal, but it's doable. In Chrome you can load chrome://serviceworker-internals/ or chrome://inspect/#service-workers to gain some insights on what is going on with your service workers. However, the Chrome team can still improve a lot when it comes to debugging service workers. When they fail to install properly because you're not using the cache polyfill for instance, the worker will return a successful installation after which the worker will be terminated without any error messages. This is very confusing and caused me quite a headache when I was first trying service workers.

Moving further with service workers

If you think service workers are interesting I suggest that you check out some examples and posts online. Jake Archibald wrote the <a href="http://jakearchibald.com/2014/offline-cookbook/" target="_blank">offline cookbook</a>. There's many information on service workers in there. You can also check out his <a href="https://github.com/jakearchibald/simple-serviceworker-tutorial" target="_blank">simple-serviceworker-tutorial</a> on Github, I learned a lot from that.

In the near future the Chrome team will be adding things like push notifications and geofencing to service workers so I think it's worth the effort to have a look at them right now because that will really put you in the lead when service workers hit the mainstream of developers and projects.

If you feel like I made some terrible mistakes in my overview of service workers or if you have something to tell me about them, please go ahead and hit me up on Twitter.

The source code for this blog post can be found on Github.

Filling in the blanks with calc()

One of the things in css3 that I don't see used very often is the calc() function. Even though this function might not be useful in every scenario it certainly has it's own use cases. In this post I'll try to outline a few of these use cases for you. First, let's start with a quick introduction to the calc() function.

What is calc()?

Calc()  is a function that was added to css3. It allows you to perform calculations on a certain property value, for example the width, font-size or even the margins of an element can be calc()-ed. The syntax for it is quite simple:

.my-class {
    width: calc(100% - 3em);
}

This code snippet sets the width of an element to 100% minus 3em. What's interesting about this is that we're combining both percentages and em values. So you can be partially fluid and partially fixed in your layout. Calc is very powerful and will perform this calculation whenever the element is being layed-out on the screen, making it incredibly flexible. An important thing to notice here is that there are spaces around the minus operator. These spaces are required.

Using calc for gutters

When building your layout you will often want to have a certain gutter in it. For instance, you could want a gutter that is exactly .75em all the time between two elements. For these cases calc is a perfect fit. Here's an example of that.

In the embedded codepen you'll see that we used only a small amount of css to accomplish this layout. A quick look at the css:

.item {
    height: 50px; 
    float: left; 
} 

.item-1 {
    width: 25%;
    background-color: #c0ff3e; 
} 

.item-2 { 
    width: calc(75% - .75em); 
    margin-left: .75em; 
    background-color: #0ff1ce;
}

The nice part about this is that a use can adjust their font-size and the layout will adapt to that because we've used ems. The calc()  function will make sure that our page will still look pretty. If you take this approach to the next level I'm pretty sure it should be possible to use calc()  in a very advanced and flexible grid system.

Calc to fill up the page

There are times where you might want to make an element take up all the width minus some known portion of the page. This becomes interesting in the case of a sidebar with a known width and content that should make up the rest of the page. Let's jump straight in with an example, shall we?

If we ignore all the kitten cuteness that Placekitten.com is providing this example with we're left with this piece of relevant css.

.item-1 {
    width: 250px;
}

.item-2 {
    width: calc(100% - 250px - .75em);
    margin-left: .75em;
}

What this demonstrates is that it suddenly becomes easy to have a partially fixed and partially flexible layout and that calc is very powerful because you can mix all kind of values. Pixels, ems, percentages, calc()  will calculate them for you. It's pretty cool actually.

How about browser support?

I'm glad you asked, browser support is more than decent for the calc feature. All new browsers have implemented it and they have done so for quite some time. Even IE has had support for some time, they only didn't implement multiplying and dividing until IE10. For an up to date list of support you can refer to caniuse.com.

Conclusion

In this post you've learned what the calc()  function is in css3 and I've showed you two real word examples of when you might want to use calc()  in your own projects. Browser support is good so there's nothing stopping you from sprinkling some calculations in to your css. If you have questions, suggestions or feedback you can always send me a Tweet.

Some tips for new front-end developers

You've decided you want to get into front-end development and you've managed to learn a few things. The time has come for you to get some working experience and start growing your career in a beautiful field. I was in that position not so long ago and I noticed that actually having a job and working is a lot different than writing code from the safety of your own environment. So how do you present yourself in a professional way? How do you make sure that you learn as much as you can? Today I want to share some of the things I have learned about this.

Take yourself seriously

But don't be cocky. It's good to show to other people that you're serious about development. It will make sure that they don't just steamroll right over you. It will show that you have passion and aren't just there to put in a couple of hours and then go home aftwerwards. The things you say and do matter and it's okay to make sure that people know. However, at the same time you should be aware that you're just starting out. You're a junior developer and you're in the position to learn. Which brings me to my next point.

Ask questions

When you're trying to proof yourself it's easy to isolate yourself and work really hard. When your get assigned a task you're probably going to want to solve it on your own. It makes sense, you're trying to make a name for yourself and you're trying to be taken seriously. How will your colleagues be able to do that if you can't even be trusted with doing a small, simple task on your own? So you try to keep everything to yourself. Even though this mindset makes a lot of sense I want to advice you to ask questions. A lot of them. Don't just ask about the tasks you're trying to complete but also ask why certain things work the way they do. Ask what motivated a certain technology or design choice in your code base. Even ask you colleagues for their opinions on work related topics. You can learn a lot from them and it will prove to them that you care enough about your job to ask somebody for help with finding the best solutions.

Take responsibility for the code you work with

Now that you're part of a team of developers, you're sharing in the responsibility over a code base. When I was listening to Ben Orenstein's podcast a few days ago he mentioned something he noticed in interviews which really stuck with me. He said that when he asked people he interviewed why a certain piece of code worked the way it did many candidates would come up with a variety of excuses why they didn't know or care about how the code worked. What these excuses usually came down to was that somebody else wrote that piece of code and it wasn't 100% relevant to the task they were trying to do. So they would just assume that the person who wrote the code knew what they were doing and they didn't feel responsible for the code, so they wouldn't touch it.

When I thought about that I figured that I take code written by my colleagues for granted a lot of the time. Event though they often double check my code to see what it does and how it can be improved. They don't do that because they don't trust me, they do that because they feel responsible for the code I write because we all share a code base. So when you touch a piece of code somebody else wrote and you're not sure how it works you should ask somebody. If you do this it will show that you actually care about the bigger picture and that you're taking responsibility for the code that you're working with. And that is a good thing.

Don't pretend you know everything

When I was doing my first internship I though I actually knew a lot. Whenever my boss would come up with a project I would have a solution immediately. I think I kept that up for about a few months until I realized that in fact I didn't really know anything. I knew the very basics of Actionscript and I knew how to create simple things with Adobe Flash and that was it. I wasn't a good programmer, I just didn't know what I didn't know. So I want to advice you to be humble, be aware that you probably don't know half of what you think you know. You don't have the experience to know what works and what doesn't work. And nobody is going to blame you for that. It's okay to say that you're not sure about something, it's also okay to just say that you don't have a clue about how you should approach something. And again, it's okay to ask questions.

If anything, your colleagues and your boss will appreciate the fact that you ask them for help, it gives them a sense of comfort knowing that you're not just doing whatever. Many good developers also seem to enjoy the act of teaching, sharing their knowledge with others. So actually by not pretending you know it all you're learning more, making sure you don't do anything weird and you're providing others with the opportunity to share knowledge.

Take the time to read and learn

If you pick up a book on development every once in a while it will give you a much better understanding of the topic you're reading about. Even though the modern world allows you to find almost anything online I have found that books are a great way to take a more casual approach at learning. I feel like reading a book speaks to a whole different mindset for me and I seem to be able to focus a lot better and longer when I'm reading a book. Also, some subjects require the repetition and explanation that a book can give you.

This also applies to learning a new tool or framework. It's okay to sit down for an hour or two so you can read about it before you start working with it. I have found that doing this will provide a sense of context and it can really help with exploring the feature of the given framework. You'll also be able to gain a much deeper understanding of what goes on because sometimes the framework documentation will go in to why they made certain choices. While these choices may seem insignificant at first sight they might provide you with some context when you're actually working with the framework. Which can help you a lot in the long run.

Conclusions

When you're just starting out as a developer it's really easy to overlook all the things you don't know. When I was just starting out I worked with some people who kept emphasizing that some things were easy but I never knew why. I never asked. And if there's something I've noticed, it's that asking is key to becoming a better developer. And it doesn't stop there, you also have to listen. Listening is a great way to learn. Opinions of more experienced people aren't based on the latest and greatest, they're based on what works and what doesn't. They tend to have experience with a lot of things and also, they tend to admit when they aren't sure. So if somebody with tons of experience tells you something, assume that they know what they're talking about. And if you have doubts, ask them. They will most likely be happy to explain to you what they think and why. They will probably even be excited about hearing what you have to say as well. So I guess this whole post comes down to a few things. Be confident, be eager, ask questions and don't fake it.

Death by papercut (why small optimizations matter)

It's not easy to write good code. It's also not easy to optimize code to be as fast as possible. Often times I have found myself refactoring a piece of code multiple times because I could make the code easier to read or perform faster. Sometimes I've achieved both. But when a project would grow larger and larger things would still feel a little slow after a while. For instance, changing something from doing four API calls to six wouldn't matter that much, right? I mean, each call only takes about 10ms and everything is very optimized!

This is death by papercut

In the example I mentioned above, doing two API calls, 10ms each, isn't a very big deal in itself. What is a big deal though, is the fact that we're doing four other calls as well. So that means that we went from 40ms in API calls to 60ms. that's a 50% increase. And then there's also the overhead of possibly extracting the data you want to send to the API from the DOM and also parsing the API's response on the client will take extra time. Slowly all these milliseconds add up. On their own every part of the application is pretty fast, but when put together it becomes slower and slower.

I'm not sure where I heard this first but I think it's a great one. All these not-so-slow things stacking up and then becoming slow is like dying from papercuts. Each cut on it's own isn't a big deal, but if you do enough of them it will become a big deal and eventually you die a slow and painful death. The same is true in web development, and any other development field for that matter.

So if we should avoid dying by a papercut, and papercuts on their own don't really do damage, how should we do that? Every block of code we write will cost us a very tiny bit of speed, that's inevitable. And we can't just stop writing code in order to keep everything fast, that's not an option.

Staying alive

The death by papercut scenario is a difficult one to avoid, but it's also quite simple at the same time. If you take a good hard look at the code you write you can probably identify small bits of code that execute but don't actually do much. Maybe you can optimize that? Or maybe you're doing two API calls straight after each other. One to fetch a list and a second one to fetch the first item on that list. If this is a very common pattern in your application, consider adding the first item in that initial API response. The win won't be huge, but imagine finding just 4 more of these situations. You may have just won about 50ms of loading time by just optimizing the obvious things in your API.

Recently I came across an instance in my own code where I wanted to do a status check for an X amount of items. Most of the items would keep the default status and I used an API to check all statuses. The API would check all of the items and it would return the 'new' status for each item. It was pointed out to me that the amount of data I sent to the API was more than I would strictly need to identify the items. Also, I was told that returning items that won't change is a waste of bandwidth, especially because most items wouldn't have to change their status.

This might sound like 2 very, very small changes were made:

  • Send a little less data to the API
  • Get a little less data back from the API

As small as these changes may seem, they actually are quite large. First of all, sending half of an already small request is still a 50% cut in data transfer. Also, returning less items isn't just a bandwidth win. It's also a couple less items to loop over in my javascript and a couple less DOM updates. So this case save me a bunch of papercuts that weren't really harming the project directly, but they could harm the project when it grows bigger and bigger and more of these small oversights stay inside of the application, becoming harder and harder to find.

Call it over optimizing or call it good programming

One might argue that what I just described is over optimization, which is considered bad practice because it costs quite some effort and yields only little wins. In this case, because the functionality was still being built it was easy to see one of these small optimizations. And the right time to do a small optimization is, I guess, as soon as you notice the possibility to do that optimization.

I haven't really thought of code in this mindset often, but I really feel like I should. It keeps me on top of my code and I should be able to write more optimized code right from the start. Especially when it comes to data fetching from an API or from a database, I think a very careful approach might be a good thing. Let's not send a request to the server for every little thing. And let's not run to the database for every little thing all the time, that's what caching is for. The sooner you optimize for these small things, the easier it is and the less trouble it will cause you later on.