October 13, 2016

The Algorithms Of Discrimination

Go read this. If you prefer you can listen too.

I posted a blog post a few weeks ago about an experience I had interviewing at a rather large and well known company that had a white board interview where I was being asked to implement a linked list in Java.

I expressed that I felt this was a useless task.

I got a lot of pushback from people on Twitter about this. A lot of older programmers chastised me that you can’t be a great programmer if you don’t understand data structures and algorithms. I tried to make the point that if you are an iOS developer that most of your job is to have knowledge of the iOS frameworks and that the language is secondary. Someone who had never owned a Mac or opened Xcode could theoretically get a job as an iOS developer.

Janie sparkled a conversation about this. I'm on her side (not that anyone's taking sides, anyway).

I remember when I interviewed at TopTal for an iOS Developer position, and they had me writing algorithms in C. A company that posts about what to ask developers in iOS interviews.


October 11, 2016

Facebook announces Yarn, a new package manager for JavaScript

From Facebook's announcement:

In the JavaScript community, engineers share hundreds of thousands of pieces of code so we can avoid rewriting basic components, libraries, or frameworks of our own. Each piece of code may in turn depend on other pieces of code, and these dependencies are managed by package managers.

Exactly. That's the problem.

From NPM's blog, acknowledging the release of Yarn:

Today, Facebook announced that they have open sourced Yarn, a backwards-compatible client for the npm registry. This joins a list of other third-party registry clients that include ied, pnpm, npm-install and npmd. (Apologies if we missed any.)

Trying to solve the dependency management problem by adding another layer of dependencies to the equation is as stupid as it sounds.

From an outsider that doesn't do web development for a living, this is crazy. I don't know how people cope with the web ecosystem. Specially the front-end part.

If you're a web developer, my condolences.

P.S.: this article really resonated with me, as I've been spending some time doing web development for the past few weeks.


September 20, 2016

Is the open source culture hurting new developers?

That’s a bold question to ask. But I’ve been thinking about it.

As a member of the iOS developer community, I see people interested in learning how to create iOS apps almost every day.

I’m a member of various Facebook groups dedicated to share tips and tricks for iOS development, or just asking simple questions to the community. It hurts a little when I see someone new to this world asking, for instance, how to download an image from the network and set it to an UIImageView, and all the responses just tell them to “install this pod,” or “download this library.” You can translate that example to almost every common problem new developers face when first starting to learn iOS Development.

Why it hurts? Because these youngsters are never going to learn all the details behind doing what they can so easily accomplish with a pod install.

I often respond with “it’s not that hard, and you don’t really need all of Alamofire to do that.” And that’s true. To download an image from the network and assign it to a image view you, at most, need 30 lines of code.

The open source community makes it so easy to add code that a) maybe you don’t need, b) maybe you don’t fully understand, that I fear the new generations won’t really know how the system works, but will know really well how CocoaPods or Carthage works. (Remember left-pad?)

If you’re someone starting in this trade, I urge you to spend some time learning what the ecosystem you’re trying to start developing for is really like, it being iOS, Rails, the week's popular JavaScript framework, whatever.

Spend some time learning what it’s really like inside the frameworks you’re going to be using for the next years. Learn their tricks. Hack them. 

Don’t get me wrong: using third party code can be (and is) a really easy solution to get things done. But in my experience, the actual learning happens when I get in there and mess things up. Don’t be afraid to mess things up.

The next time you’re trying to figure out how to do something specific, try to come up with a solution, and only then, look at what everyone else is doing. Rinse, repeat. That’s how you get good at something, not just blindly using someone else’s code.

Look for mentors that don’t show you the easy way, but that guide you through the rough way.


September 16, 2016

Bringing piping syntax from Elixir to Swift

I've been writing Elixir for my main backend needs for the past few months and I've really liked it — specially its syntax. In fact, I've gotten so into its syntax that I've often found myself trying to write Swift as if it were Elixir.

Oops!

So I decided to experiment a little bit with bringing my favourite syntax from Elixir over to Swift natively.

Disclaimer: This is just an experiment. To get this to work on an actual project, a lot more work needs be done.


Elixir is a functional language that's gained a lot of traction in the past few months thanks to its simplicity and core features, such as the supervision tree.

Every type in Elixir is a value, which means that it gets copied when passed to a function — the function gets a new copy of the value, which it can then modify without affecting the original instance.

> aMap = %{a: 1}
  %{a: 1}

> bMap = Map.update(aMap, :a, 0, &(&1 * 3))
  %{a: 3}

> aMap 
  %{a: 1}

> bMap
  %{a: 3}

Also, Elixir has this great "pipe" operator that lets you write cleaner code and streamline data manipulation in a really easy way:

> cMap = aMap |> Map.update(:a, 0, &(&1 / 3))

The "pipe" (|> ) operator takes the value on its left and passes it to the function on the right as its first parameter. This is included as part of the language and works with any function.

Let's bring that to Swift!

In this example, I'm going to use two simple structs (value types in Swift):

struct Company {  
    let name: String
}

struct Person {  
    let name: String
    let work: Company
}

let apple = Company(name: "")  
let joe = Person(name: "Joe", work: apple)  

A characteristic of functional programming languages is that they strive for immutability. Vaues should not mutate during program execution, but copying values and modifying them is good.

Tipically, if we wanted to update joe's name, we'd do something like

joe.name = "Joe Wood"  

If we did this, the Swift compiler would raise two errors:

  1. the name property on Person is declared as a constant (let), which means it can't mutate during execution — a change to var is suggested.
  2. the joe instance was declared as a constant (let), which means it can't mutate during execution — a change to var is suggested.

What we don't want, though, is enable the ground to shift under our feet, so let's keep everything as a constant.

Another approach would be to create a function that did so:

extension Person {  
  mutating func update(name: String) {
    self.name = newName
  }
}

But again, that mutating keyword there is a code-smell in the functional world. The way to do this the functional way is:

extension Person {  
  func update(name: String) -> Person {
    return Person(name: newName, work: self.work)
  }
}

We created a function that changes only one property on the instance — it receives the new value for the property, and returns a whole new instance of the type with that value replacing the original one.

joe.update(name: "Joe Wood").name // Joe Wood  
joe.name                          // Joe  

Now, the problem with this is that the function that we created is operating on the type-instance.

Note: In Elixir, a map literal can be written as %{a: 1}, but to transform and operate on that instance, we have to use the Map module. That's kind of what we want to achieve here.

We want that the Person struct (or module, if you're thinking in Elixir) to have a series of methods that receive Person instances to operate with.

In order to achieve that, we need to do a bit of groundwork.

Lenses

There is a concept in functional programming called "data lenses". Explaining in detail what a data lens is, is way out of scope of this post, but you can read more about it here and here, and generally, just searching "lenses functional programming" in any search engine.

The idea is to have a data type (a Lens) that is generic and lets us get and set (a.k.a. zoom to) information on the type that the Lens is generic to.

Example:

struct Lens<Whole, Part> {  
  let get: (Whole) -> Part
  let set: (Whole, Part) -> Whole
}

let personNameLens = Lens<Person, String> (  
  get: { $0.name },
  set: { Person(name: $1, work: $0.work) }
)

personNameLens.get(joe)                  // Joe  
personNameLens.set(joe, "Joe Wood").name // Joe Wood  

That's a Lens. However, we'll only need a subset here, so let's define a new data type that gives us only the set method:

struct SetLens<Whole, Part> {  
  let set: (Whole, Part) -> Whole
}

To update a Person instance, we can do this now:

let setPersonNameLens = SetLens<Person, String> (  
  set: { Person(name: $1, work: $0.work) }
}

setPersonNameLens.set(joe, "Joe Wood")  

Now lets do a bit of work to move the interface up to type-level by making our SetLens a static property of Person, for brevity:

extension Person {  
  static let SetName = SetLens<Person, String> (
    set: { Person(name: $1, work: $0.work) }
  ) 
}

Person.SetName.set(joe, "Joe Wood")  

We still have the problem that we'd have to interact with the SetLens directly. To mimic the Elixir behaviour, we need to wrap the SetName property on a static function that returns a function that when called, calls the set method on the lens.

extension Person {  
  static func Update(name: String) -> Person -> Person {
    return { p in SetName.set(p, newName) }
  }
}

We define a static function that takes a new name as a parameter, and returns a function that takes a Person and returns a Person. Calling this function just passes the values to the SetLens.

Now, let's introduce the pipe operator:

precedencegroup Applicable {  
    associativity: left
}
infix operator |>  
func |> <A, B>(a: A, rhs: (A) -> B) -> B {  
    return rhs(a)
}

This new custom operator takes a value to the left and a function on the right, and just calls the function on the right passing the value on the left. How convenient!

We can now do this:

joe |> Person.UpdateName("Joe Wood")  

Ta'da!

Doing the appropriate amount of work, we could be writing this really soon:

joe  
  |> Person.Update(name: "Joe Wood")
  |> Person.Update(work: Company(name: "Apple"))

And voilá, we've migrated one of Elixir's core features to Swift, while maintaining type-safety!

Final comments

Admittedly, it took a long of work just to migrate this one feature over to Swift. This does not mean, though, that it can't be done for big code-bases and "real apps." One of the best features of Swift is that the compiler is real smart and can tell us on compile-time if we messed something up. ❤️

This was just a small exercise, but I do appreciate the similarities that Swift and Elixir have, and the fact that both languages are flexbile enough that we can do these sort of things. Pretty cool.


Hey! I'm writing a book on best practices for iOS development with Swift, and it's called (drum roll) Best Practices for Developing iOS Apps with Swift.

Subscribe below to get a 50% off coupon code when the book is released — also get the first chapter for free when it is ready!


September 16, 2016

Singletons in Swift

If you come from the Objective-C world, you're probably familiar with the singleton pattern.

@implementation MyClass 

+ (id)sharedInstance 
{
    static MyClass *__instance = nil
    static dispatch_once_t token;

    dispatch_once(&token, ^{
        __instance = [[MyClass alloc] init];
    });

    return __instance;
}
@end

Okay, here's how you declare a singleton in Swift:

class MyClass {  
    static let sharedInstance = MyClass()
}

And that's it.

Thanks to Swift's immutability (using let properties), we're able to declare the static property on the type and have it resolve its value when the type declaration is first used.

Many say that singletons are an antipattern and should be avoided. I say that it depends. If you assess that a singleton is the right way to go to solve your current proble, go for it.

However, I should remind you that Swift is not Objective-C, and the fact that you can still use the same constructs that are used in Objective-C doesn't mean you sould. Swift is a great language to exploit value semantics and immutability.


September 15, 2016

On Apple's take on how to handle JSON with Swift 3

A couple of days ago, Apple published this post in which they describe some ways one can parse JSON using core languages of Swift 3.

Weird thing, they suggest that it is OK to have a type download JSON by itself:

You can create a type method on the Restaurant structure that translates a query method parameter into a corresponding request object and sends the HTTP request to the web service. This code would also be responsible for handling the response, deserializing the JSON data, creating Restaurant objects from each of the extracted dictionaries in the "results" array, and asynchronously returning them in a completion handler.

Please don't do this. Having a type inflate itself from the network is just a cry for trouble.

One thing I did like of Apple's post is that they put all of their custom code on an extension of the type they're trying to add JSON support to. What I didn't like, though, is that they're relying in initializers that decide wether the type can be inflated or not.

I really don't like that.

For me, the correct approach is to have a type method that validates wether the JSON is valid or not, and then return a type instance from that:

extension Restaurant {  
    static func with(json: [String:Any]) -> Restaurant? {
        // Verify that the JSON contains the correct values, etc.
    }
}

You could either return nil there, or just throw a custom error with the key that's missing, as they do in their example.

Swift is a language that pushes us to think functionally, and in terms of values. The static method on the type is the correct approach, I think. It also feels cleaner.

In case you want to read my full take on how I think JSON should be handled with Swift 3, you can read this post.


September 12, 2016

Introducing my new book, Best Practices for Developing iOS Apps with Swift

Hey there!

That's right, I'm launching the first book in what I expect will be a long list of titles that I'll be publishing in the following months.

Best Practices for Developing iOS Apps with Swift, available late October, focuses on how to avoid the mistakes that I've already made, so you don't have to make them and your apps can be future-proof.

Register now to get get notified when the book launches. You'll get the first chapter for free when it's ready. Oh, also, a 50% off discount code on launch day.

Fun fact: this is actually the English version of the original book I wrote "Mejores Prácticas Del Desarrollo de Aplicaciones para iOS con Swift", which is going to be out by the end of the month. If you're interested, go check it out now.

Thanks for reading, and see you later!


September 08, 2016

› Tesla, the new HTTP client for Elixir

As I've written before in this blog, I've been playing with Elixir/Phoenix for the past few months — I even have a couple of production applications running right now!

Just learned about Tesla, a new HTTP client for Elixir. I've taken a quick look at it and it seems that's something I'll be using for my next proyects.

What I like the most is the plug based architecture that it uses to build clients. It relfects a lot the way I build HTTP clients with Swift, so it feels right.

If you're looking for a replacement for httpotion or httpoison, definitely take a look at this.