{"id":4046,"date":"2014-06-10T10:55:16","date_gmt":"2014-06-10T13:55:16","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=4046"},"modified":"2014-09-19T13:07:48","modified_gmt":"2014-09-19T16:07:48","slug":"comparing-protocols-and-extensions-in-swift-and-elixir","status":"publish","type":"post","link":"http:\/\/blog.plataformatec.com.br\/2014\/06\/comparing-protocols-and-extensions-in-swift-and-elixir\/","title":{"rendered":"Comparing protocols and extensions in Swift and Elixir"},"content":{"rendered":"

Swift<\/a> has been recently announced by Apple and I have been reading the docs and playing with the language out of curiority. I was pleasantly surprised with many features in the language, like the handling of optional values (and types) and with immutability being promoted throughout the language.<\/p>\n

The language also feels extensible. For extensibility, I am using the same criteria we use for Elixir<\/a>, which is the ability to implement language constructs using the language itself.<\/p>\n

For example, in many languages the short-circuiting &&<\/code> operator is defined as special part of the language. In those languages, you can’t reimplement the operator using the constructs provided by the language.<\/p>\n

In Elixir, however, you can implement the &&<\/code> operator as a macro:<\/p>\n

\ndefmacro left && right do\n  quote do\n    case unquote(left) do\n      false -> false\n      _ -> unquote(right)\n    end\n  end\nend\n<\/pre>\n

In Swift, you can also implement operators and easily define the &&<\/code> operator with the help of the @auto_closure<\/code> attribute:<\/p>\n

\nfunc &&(lhs: LogicValue, rhs: @auto_closure () -> LogicValue) -> Bool {\n    if lhs {\n        if rhs() == true {\n            return true\n        }\n    }\n    return false\n}\n<\/pre>\n

The @auto_closure<\/code> attribute automatically wraps the tagged argument in a closure, allowing you to control when it is executed and therefore implement the short-circuiting property of the &&<\/code> operator.<\/p>\n

However, one of the features I suspect that will actually hurt extensibility in Swift is the Extensions<\/strong> feature. I have compared the protocols implementation in Swift with the ones found in Elixir and Clojure on Twitter and, as developers have asked for a more detailed explanation, I am writing this blog post as result!<\/p>\n

Extensions<\/h2>\n

The extension feature in Swift has many use cases. You can read them all in more detail in their documentation<\/a>. For now, we will cover the general case and discuss the protocol case, which is the bulk of this blog post.<\/p>\n

Following the example in Apple documentation itself:<\/p>\n

\nextension Double {\n    var km: Double { return self * 1_000.0 }\n    var m: Double { return self }\n    var cm: Double { return self \/ 100.0 }\n    var mm: Double { return self \/ 1_000.0 }\n    var ft: Double { return self \/ 3.28084 }\n}\n\nlet oneInch = 25.4.mm\nprintln(\"One inch is \\(oneInch) meters\")\n\/\/ prints \"One inch is 0.0254 meters\"\n\nlet threeFeet = 3.ft\nprintln(\"Three feet is \\(threeFeet) meters\")\n\/\/ prints \"Three feet is 0.914399970739201 meters\"\n<\/pre>\n

In the example above, we are extending the Double type, adding our own computed properties. Those extensions are global and, if you are Ruby developer, it will remind you of monkey patching in Ruby. However, in Ruby classes are always open, and here the extension is always explicit (which I personally consider to be a benefit).<\/p>\n

What troubles extensions is exactly the fact they are global<\/strong>. While I understand some extensions would be useful to define globally, they always come with the possibility of namespace pollution and name conflicts. Two libraries can define the same extensions to the Double type that behave slightly different, leading to bugs.<\/p>\n

This has always been a hot topic in the Ruby community with Refinements<\/a> being proposed in late 2010 as a solution to the problem. At this moment, it is unclear if extensions can be scoped in any way in Swift.<\/p>\n

The case for protocols<\/h2>\n

Protocols are a fantastic feature in Swift. Per the documentation<\/a>: “a protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality”.<\/p>\n

Let’s see their example:<\/p>\n

\nprotocol FullyNamed {\n    var fullName: String { get }\n}\n\nstruct Person: FullyNamed {\n    var fullName: String\n}\n\nlet john = Person(fullName: \"John Appleseed\")\n\/\/ john.fullName is \"John Appleseed\"\n<\/pre>\n

In the example above we defined a FullyNamed<\/code> protocol and implemented it while defining the Person<\/code> struct. The benefit of protocols is that the compiler can now guarantee the struct complies with the definitions specified in the protocol. In case the protocol changes in the future, you will know immediately by recompiling your project.<\/p>\n

I have been long advocating this feature for Ruby. For example, imagine you have the following Ruby code:<\/p>\n

\nclass Person\n  attr_accessor :first, :last\n\n  def full_name\n    first + \" \" + last\n  end\nend\n<\/pre>\n

And you have a method somewhere that expects an object that implements full_name<\/code>:<\/p>\n

\ndef print_full_name(obj)\n  puts obj.full_name\nend\n<\/pre>\n

At some point, you may want to print the title too:<\/p>\n

\ndef print_full_name(obj)\n  if title = obj.title\n    puts title + \" \" + obj.full_name\n  else\n    puts obj.full_name\n  end\nend\n<\/pre>\n

Your contract has now changed but there is no mechanism to notify implementations of such change. This is particularly cumbersome because sometimes such changes are done by accident, when you don’t want to actually modify the contract.<\/p>\n

This issue has happened multiple times in Rails. Before Rails 3, there was no official contract between the controller and the model and between the view and the model. This meant that, while Rails worked fine with Active Record (Rails’ built-in model layer), every Rails release could possibly break integration with other models because the contract suddenly became larger due to changes in the implementation.<\/p>\n

Since Rails 3, we actually define a contract for those interactions, but there is still no way to:<\/p>\n