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.


July 25, 2016

Filtering has_many relationships in Ecto

This is sot-of a follow up to my last post, about self-referencing many_to_many relationships using Ecto.

I find myself in a scenario where I have a User:

# User model
defmodule MyApp.User do  
  use MyApp.Web, :model

  alias MyApp.Contact

  schema "users" do
    has_many :_internal_contacts, MyApp.Contact
    has_many :contacts, through: [:_internal_contacts, :contact]

    timestamps
  end
end  

and an association model Contact through which the User has many contacts (User instances):

defmodule MyApp.Contact do  
  use MyApp.Web, :model

  alias MyApp.User

  schema "contacts" do
    field :status, :integer

    belongs_to :user, User, foreign_key: :user_id
    belongs_to :contact, User, foreign_key: :contact_id

    timestamps
  end

  def status_code(status) do
    case status do
      :accepted ->
        1
      :pending ->
        0
      :rejected ->
        -1
      _ ->
        0
    end
  end

I created an endpoint on my app that's supposed to get me only the user's contacts that have the :accepted status (1). How can this be accomplished?

The Repo module has a set of handy functions that let you preload associations on your models.

user = User |> Repo.get(1) |> Repo.preload(:contacts)  

The above will preload all contacts on the user. Pay attention to the fact that it is of type has_many and it goes through the :_internal_contacts property. This is the important cue.

Turns out that the preloads parameter on Repo.preload/3 can be accompanied by a query.

import Ecto.Query

#1
query = from c in Contact, where: c.status == 1 and c.user_id == 1

u = User  
    |> Repo.get(1) #2
    |> Repo.preload(_internal_contacts: query) #3
    |> Repo.preload(:contacts) #4

The code above will:

  1. Create a query that will ask for Contacts with status 1 and with user_id 1.
  2. Get a User instance.
  3. Preload the _internal_contacts on that instace using our query (these are Contact instances, not User instances)
  4. Preload the :contacts on our user. And since :contacts goes through: _internal_contacts, :contacts has only valid contacts now (User instances).

Notes:

Honestly, I don't know if this is the right approach here (let me know!). I did find this thread on GitHub where the general issue that we're facing here is described. It seems that there's an interest to have the ability to filter the relationships on the declaration itself:

It would look something like this:

has_many :comments, MyApp.Comment, foreign_key: :commentable_id,  fn (query) ->  
  from c in query, where: c.commentable_type == "articles"
end  

However, right now, the saner approach seems to be the use of composable queries.

Have anything to add to this article or did I miss something? Please let me know on Twitter.


July 23, 2016

Self-referencing many-to-many relationships using Ecto

EDIT: I've changed the last section of this article to reflect my findings in actually using this in production.


I've decided to do the backend for a new app I'm creating myself, using Elixir/Phoenix. I've been learning Elixir for the past few months and thought it would be a great opportunity to put what I've learned to good use.

There's a lot of documentation about the new many_to_many macro in Ecto 2 — but somehow, it still was a bit of a pain to get this right the first time. I couldn't find a concrete example of how a self-referencing many-to-many relationship would work with Ecto, and after some digging and the help of the awesome Elixir community, I got it working. I'm writing this post just to put this out there so you can go through this quicker.

In the app, a User can have contacts, which are themselves Users. (Let's omit the authentication stuff for now) The migration looks like this:

# priv/repo/migrations/create_users_table.ex
defmodule MyApp.Repo.Migrations.CreateUsersTable do  
  use Ecto.Migration

  def change do
    create table(:users) do
      add :username, :string
    end

    create unique_index(:users, [:username])
  end
end  

Then, the module that defines the schema looks like this:

defmodule MyApp.User do  
  use MyApp.Web, :model

  schema "users" do
    field :username, :string

    timestamps
  end

  # Omitting changesets
end  

In order to create a many-to-many relationship correctly we must have an associative table, that we'll call "contacts". This is the migration for that:

defmodule MyApp.Repo.Migrations.CreateContactsTable do  
  use Ecto.Migration

  def change do
    create table(:contacts) do
      add :user_id, references(:users, on_delete: :nothing), primary_key: true
      add :contact_id, references(:users, on_delete: :nothing), primary_key: true
      add :status, :int

      timestamps()
    end
  end
end  

To expand a bit, the "Contacts" table has... :

  1. a column user_id, which is the id for the user that initiated the "friend request".
  2. a column contact_id, which is the id for the user that must accept or reject the "friend request"
  3. a column status, which represents the friendship status (0=pending, 1=accepted, -1=rejected).

Now for the interesting part, we have to create a "Contacts" schema that Ecto can work with in order for the association to work correctly. On to it:

defmodule MyApp.Contact do  
  use MyApp.Web, :model

  alias MyApp.User

  schema "contacts" do
    belongs_to :user, User
    belongs_to :contact, User
  end
end  

We define the Contact module, that belongs to both a user and a contact, both being User types. We now have to update the User model to reflect the many-to-many relation:

defmodule MyApp.User do  
  use MyApp.Web, :model

  schema "users" do
    field :username, :string
    # Add the many-to-many association
    many_to_many :contacts, MyApp.User, join_through: "contacts", on_replace: :delete
    timestamps
  end

  # Omitting changesets
end  

Using the many_to_many macro we only have to specify the field on the User model, tell Ecto what table use as association table, and that's it!

You can now do this in your code:

user = Repo.get(User, 1) |> Repo.preload(:contacts)  
contact = hd(user.contacts)  

However...

A member of the Elixir community told me on Slack that this looks more like a one-to-many relationship, and that I should try to represent it that way in my app. It would look like this:

defmodule MyApp.User do  
  use MyApp.Web, :model
  alias MyApp.Contact

  schema "users" do
    field :username, :string
    # Add the many-to-many association
    has_many :_contacts, MyApp.Contact
    has_many :contacts, through: [:_contacts, :contact]
    timestamps
  end

  # Omitting changesets
end  

It works, however I don't like the fact that now we basically have cluttered our model, having _contacts and contacts in it. Then there's the fact that Ecto models are just backed by a simple struct, so there's no way to "hide" details about it (as-in: make _contacts private). I decided to stick with the many_to_many version of this code because it hides the association table quite nicely.

After playing with this for a bit, I realised that this is the correct approach, although it clutters the user instance space.

During actual testing in my Phoenix app, I noticed that the query that Ecto was generating with the former association type was the wrong one. Switching it from many_to_many to has_many as above, fixed the issue.

Have something to add to this article, or did I miss something? Hit me up on Twitter.