<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>protocols « Plataformatec Blog</title>
	<atom:link href="/tag/protocols/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>Plataformatec&#039;s place to talk about Ruby, Ruby on Rails, Elixir, and software engineering</description>
	<lastBuildDate>Mon, 01 Jun 2015 14:23:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.2</generator>
	<item>
		<title>Build embedded and start permanent in Elixir 1.0.4</title>
		<link>/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/</link>
					<comments>/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/#comments</comments>
		
		<dc:creator><![CDATA[José Valim]]></dc:creator>
		<pubDate>Fri, 10 Apr 2015 12:00:54 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[protocols]]></category>
		<guid isPermaLink="false">/?p=4454</guid>

					<description><![CDATA[<p>Elixir v1.0.4 ships with two new important options for new projects. If you generate a new application with mix new, you will see in your mix.exs: [build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod] Although those options were originally meant to be in Elixir v1.1, we have decided to bring them into v1.0.4 and do ... <a class="read-more-link" href="/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/">»</a></p>
<p>The post <a href="/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/">Build embedded and start permanent in Elixir 1.0.4</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Elixir v1.0.4 ships with two new important options for new projects. If you generate a new application with <code>mix new</code>, you will see in your <code>mix.exs</code>:</p>
<pre><code class="elixir">[build_embedded: Mix.env == :prod,
 start_permanent: Mix.env == :prod]
</code></pre>
<p>Although those options were originally meant to be in Elixir v1.1, we have decided to bring them into v1.0.4 and do a new release. In this post, we will explain why.</p>
<h2>Protocol consolidation</h2>
<p>One of Elixir&#8217;s most important features are <a href="http://elixir-lang.org/getting-started/protocols.html">protocols</a>. Protocols allow developers to write code that accept any data type, dispatching to the appropriate implementation of the protocol at runtime. For example:</p>
<pre><code class="elixir">defprotocol JSON do
  def encode(data)
end

defimpl JSON, for: List do
  def encode(list) do
    # ...
  end
end
</code></pre>
<p>We have <a href="/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/">written about protocols before</a> and I recently explored on my Erlang Factory talk <a href="https://www.youtube.com/watch?v=Lqo9-pQuRKE">the foundation protocols have allowed us to build</a>.</p>
<p>However, in order to play nicely with the dynamic nature of the Erlang VM where modules can be loaded at any time by the VM, as well as any protocol implementation, protocols need to check on every dispatch if a new implementation is available for any given data type.</p>
<p>While we would gladly pay this price in development as it gives developers flexibility, we would like to avoid such in production as deployments gives us a consolidated view of all modules in the system allowing us to skip those runtime checks. For this reason, Elixir provides a feature called protocol consolidation, that consolidates all protocols with their implementations, giving protocols a fast dispatch to use in production.</p>
<p>Prior to Elixir v1.0.4, protocol consolidation had to be manually invoked by calling <code>mix compile.protocols</code>, which would consolidate protocols into a predefined directory, and this directory had to be explicitly added to your load path when starting your project. Due to the manual nature of such commands, a lot of developers ended-up not running them in production, or were often confused when doing so.</p>
<p>For this reason, Elixir v1.0.4 introduces a <code>:consolidate_protocols</code> option to your projects which will take care of consolidating and loading all protocols before your application starts. This option is also set to true when <code>:build_embedded</code> is true.</p>
<h2>Build embedded</h2>
<p>When compiling your projects, Elixir will place all compiled artifacts into the <code>_build</code> directory:</p>
<pre><code>_build/
  dev/
    lib/
      your_app/
        ebin/
        priv/
      dep1/
      dep2/
  test/
  prod/
</code></pre>
<p>Many of those applications and dependencies have artifacts in their source that are required during runtime. Such artifacts are placed in the <code>priv</code> directory in Elixir applications. By default, Elixir will symlink to their source directories during development.</p>
<p>In production, though, we could copy those contents to avoid symlink traversal, <em>embedding</em> all relevant files to run your application into the <code>_build</code> directory, without a need for their sources.</p>
<p>That&#8217;s what the <code>:build_embedded</code> option does and it defaults to true in production for new applications.</p>
<h2>Start permanent</h2>
<p>Elixir code is packaged into applications. For example, each entry we saw under <code>_build/dev/lib</code> above is a different application. When an application is started, it can be started in one of the three following modes:</p>
<ul>
<li><code>permanent</code> &#8211; if app terminates, all other applications and the entire node are also terminated</li>
<li><code>transient</code> &#8211; if app terminates with :normal reason, it is reported but no other applications are terminated. If a transient application terminates abnormally, all other applications and the entire node are also terminated</li>
<li><code>temporary</code> &#8211; if app terminates, it is reported but no other applications are terminated</li>
</ul>
<p>The default mode is temporary, which again, makes sense for development. For example, our test library called ExUnit, is also an application. If the application being tested crashes, we still want the ExUnit application to continue running in order to finish all tests and generate the proper reports. In this case, you definitely do not want your application to run as permanent.</p>
<p>However, in production, once your application crashes permanently, beyond recovery, we want the whole node to terminate, otherwise whatever you have monitoring your application at the operating system level won&#8217;t notice any change.</p>
<p>The <code>:start_permanent</code> option starts your application as <code>:permanent</code> and it defaults to true in production for new applications.</p>
<h2>Summing up</h2>
<p>Those new options have been introduced into Elixir v1.0.4 because they are very important for running Elixir in production. They bring more performance and stability to your Elixir-based systems.</p>
<p>There are other smaller changes in this release, like support for Erlang 17.5 and 18.0-rc1, as well as bug fixes. <a href="https://github.com/elixir-lang/elixir/releases/tag/v1.0.4">Check the release notes</a> for more information and enjoy!</p>
<p><a href="http://plataformatec.com.br/elixir-radar"><img decoding="async" src="/wp-content/uploads/2015/05/elixir-radar-subscribe.png" alt="Subscribe to Elixir Radar" style="border:none;" /></a></p><p>The post <a href="/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/">Build embedded and start permanent in Elixir 1.0.4</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>/2015/04/build-embedded-and-start-permanent-in-elixir-1-0-4/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Writing assertive code with Elixir</title>
		<link>/2014/09/writing-assertive-code-with-elixir/</link>
		
		<dc:creator><![CDATA[José Valim]]></dc:creator>
		<pubDate>Wed, 24 Sep 2014 12:00:01 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[assertive code]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[pattern matching]]></category>
		<category><![CDATA[protocols]]></category>
		<guid isPermaLink="false">/?p=4228</guid>

					<description><![CDATA[<p>Functional languages are typically great languages for writing assertive code and Elixir is no exception. In this blog post, I would like to discuss some anti-patterns I have seen in Elixir code and how to rewrite them in a way to make the best of Elixir. Pattern matching Imagine you have a string with format ... <a class="read-more-link" href="/2014/09/writing-assertive-code-with-elixir/">»</a></p>
<p>The post <a href="/2014/09/writing-assertive-code-with-elixir/">Writing assertive code with Elixir</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Functional languages are typically great languages for writing assertive code and Elixir is no exception. In this blog post, I would like to discuss some anti-patterns I have seen in Elixir code and how to rewrite them in a way to make the best of Elixir.</p>
<h3>Pattern matching</h3>
<p>Imagine you have a string with format <code>foo=bar&amp;token=value&amp;bar=baz</code> where you want to extract the value for the key <code>token</code> which may appear anywhere or not at all in the string.</p>
<p>Here is one solution a developer not very-acquainted with pattern matching would try:</p>
<pre lang="ruby">
def get_token(string) do
  parts = String.split(string, "&")
  Enum.find_value(parts, fn pair ->
    key_value = String.split(pair, "=")
    Enum.at(key_value, 0) == "token" && Enum.at(key_value, 1)
  end)
end
</pre>
<p>At first the code seems to work fine but once we go deeper we can see it makes many assumptions we have not really planned for!</p>
<p>For example, what happens if someone passes <code>"foo=bar&amp;token=some=value&amp;bar=baz"</code> as argument? The code will work and will return the string <code>"some"</code>. But is that what we really want? Maybe we wanted <code>"some=value"</code> instead? Or maybe we wanted to reject it all together?</p>
<p>There are other examples where the code above would work by accident, possibly adding complexity to the codebase as other users may start to rely on such behaviour.</p>
<p>The most idiomatic way of writing the code above in Elixir is by using pattern matching:</p>
<pre lang="ruby">
def get_token(string) do
  parts = String.split(string, "&")
  Enum.find_value(parts, fn pair ->
    [key, value] = String.split(pair, "=")
    key == "token" && value
  end)
end
</pre>
<p>With pattern matching, we are asserting that <code>String.split/2</code> is going to return a list with two elements. If someone passes <code>"foo=bar&amp;token&amp;bar=baz"</code>, it will crash as the list will have only one element. If someone passes <code>"token=some=value"</code>, it will crash too as it contains 3 items.</p>
<p>Our new code does not contain any of the accidental complexity of the previous one and it will also be faster. Any input that does not match the given pattern will lead to a crash, giving us the perfect opportunity to discuss and decide how to handle those corner cases.</p>
<h3>Polymorphism is opt-in</h3>
<p>Elixir provides protocols as a mechanism for polymorphism. A protocol allows developers to express they are willing to work with any data type, as long as it implements the protocols X, Y and Z.</p>
<p>I have previously <a href="/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/">compared Elixir protocols to alternatives in languages like Swift and Ruby</a>. One nice aspect of Elixir protocols is that they are explicit, you need to explicitly outline and define a protocol for data structures to implement.</p>
<p>For example, one protocol in Elixir is the <code>String.Chars</code> protocol, which converts any data type to a string, if that data type can be converted to a human-readable string. The <code>to_string</code> function uses such protocol for conversions:</p>
<pre lang="ruby">
iex> to_string("hello")
"hello"
iex> to_string(1)
"1"
iex> to_string URI.parse("/")
"/"
iex> to_string %{hello: :world}
** (Protocol.UndefinedError) protocol String.Chars not implemented for %{hello: :world}
</pre>
<p>Imagine you have a function that converts underscores to dashes in a string:</p>
<pre lang="ruby">
def dasherize(string), do: String.replace(string, "_", "-")
</pre>
<p>Now imagine that at some point you decide to call <code>to_string/1</code> before calling <code>replace/3</code>:</p>
<pre lang="ruby">
def dasherize(data), do: String.replace(to_string(data), "_", "-")
</pre>
<p>Albeit small, this is a drastic change to our code. Our dasherize function went from supporting only strings as argument to support a large number of data types. In other words, our code became less assertive and more generic.</p>
<p>That said, before adding protocols to our code, we should ask if we really intend to open our function to all types. Maybe we want dasherize to support only atoms and strings? If so, we should rather write:</p>
<pre lang="ruby">
def dasherize(data) when is_atom(data), do: dasherize(Atom.to_string(data))
def dasherize(data), do: String.replace(data, "_", "-")
</pre>
<p>However, if we are confident we want a protocol, then we should indeed use the protocol and write a test case that guarantees our function works for at least a couple types that implement such protocol. Such tests are extremely important to guarantee we don&#8217;t make a different assumption somewhere in the same function.</p>
<p>Note this trade-off does not only happen in protocols, but in any polymorphic API, like the <code>Dict</code> module. In practice, one should rather use specific dict implementations, like the <code>Keyword</code> and <code>Map</code> modules, and rely on the <code>Dict</code> module only when polymorphism is desired.</p>
<h3>Map/struct access</h3>
<p>Elixir provides maps, known as dictionaries in other languages, as a key-value data structure. Maps are created as follows:</p>
<pre lang="ruby">
map = %{name: "john", age: 42}
</pre>
<p>Maps allow two types of access. A strict access, that requires the field name to exist in the map, and a dynamic access, that returns nil if the field does not exist in the map:</p>
<pre lang="ruby">
# Strict access
iex> map.name
"john"
iex> map.address
** (KeyError) key :address not found in: %{age: 42, name: "john"}

# Dynamic access
iex> map[:name]
"john"
iex> map[:address]
nil
</pre>
<p>Both syntaxes have their use cases but we should prefer the strict syntax when possible as it helps us find bugs early on. The same applies to structs, which are named maps:</p>
<pre lang="ruby">
defmodule User do
  defstruct [:first_name, :last_name, :age]

  def name(user) do
    "#{user.first_name} #{user.last_name}"
  end
end

User.name %User{first_name: "John", last_name: "Doe"}
#=> "John Doe"
</pre>
<p>In the example above, we have defined a User struct and a <code>name/1</code> function that receives the struct and returns its name. Since we are using <code>user.first_name</code>, if we accidentally pass a struct that does not contain such a field, it will crash immediately, with a nice error message!</p>
<p>In fact, the strict aspect of the <code>user.first_name</code> syntax is one of the reasons why structs do not support the dynamic syntax out of the box:</p>
<pre lang="ruby">
user = %User{first_name: "John", last_name: "Doe"}
user[:first_name]
** (Protocol.UndefinedError) protocol Access not implemented for %User{...}
</pre>
<p>In case you want to use the dynamic syntax, you need to derive the Access protocol for the User struct:</p>
<pre lang="ruby">
defmodule User do
  @derive [Access]
  defstruct [:first_name, :last_name, :age]

  def name(user) do
    "#{user.first_name} #{user.last_name}"
  end
end
</pre>
<p>However, only derive Access when you truly need to do so, as it is much better to push yourself to rely more on the strict syntax. I would even say relying on Access for structured data is an anti-pattern itself!</p>
<h3>Wrapping up</h3>
<p>The most interesting aspect of all examples above is that writing in the assertive style leads to faster, more concise and maintainable code. Even more, it allows us to focus on specific scenarios, postponing any complexity (incidental or accidental) to <em>only when we need them, if we need them</em>.</p>
<p style="text-align: center;">
<p><span id="hs-cta-wrapper-2aeae558-5b72-4df3-bf32-e1119f34d85e" class="hs-cta-wrapper"><span id="hs-cta-2aeae558-5b72-4df3-bf32-e1119f34d85e" class="hs-cta-node hs-cta-2aeae558-5b72-4df3-bf32-e1119f34d85e"> <a href="http://cta-redirect.hubspot.com/cta/redirect/378213/2aeae558-5b72-4df3-bf32-e1119f34d85e"><img decoding="async" id="hs-cta-img-2aeae558-5b72-4df3-bf32-e1119f34d85e" class="hs-cta-img aligncenter" style="border-width: 0px;" src="https://no-cache.hubspot.com/cta/default/378213/2aeae558-5b72-4df3-bf32-e1119f34d85e.png" alt="" /></a></span></span><br />
<!-- end HubSpot Call-to-Action Code --></p><p>The post <a href="/2014/09/writing-assertive-code-with-elixir/">Writing assertive code with Elixir</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Comparing protocols and extensions in Swift and Elixir</title>
		<link>/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/</link>
					<comments>/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/#comments</comments>
		
		<dc:creator><![CDATA[José Valim]]></dc:creator>
		<pubDate>Tue, 10 Jun 2014 13:55:16 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[extensions]]></category>
		<category><![CDATA[protocols]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[swift]]></category>
		<guid isPermaLink="false">/?p=4046</guid>

					<description><![CDATA[<p>Swift 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. The language also feels extensible. For extensibility, ... <a class="read-more-link" href="/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/">»</a></p>
<p>The post <a href="/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/">Comparing protocols and extensions in Swift and Elixir</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<p><a href="https://developer.apple.com/swift/">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>
<p>The language also feels extensible. For extensibility, I am using the same criteria we use for <a href="http://elixir-lang.org/">Elixir</a>, which is the ability to implement language constructs using the language itself.</p>
<p>For example, in many languages the short-circuiting <code>&amp;&amp;</code> operator is defined as special part of the language. In those languages, you can&#8217;t reimplement the operator using the constructs provided by the language.</p>
<p>In Elixir, however, you can implement the <code>&amp;&amp;</code> operator as a macro:</p>
<pre lang='elixir'>
defmacro left && right do
  quote do
    case unquote(left) do
      false -> false
      _ -> unquote(right)
    end
  end
end
</pre>
<p>In Swift, you can also implement operators and easily define the <code>&amp;&amp;</code> operator with the help of the <code>@auto_closure</code> attribute:</p>
<pre lang='swift'>
func &&(lhs: LogicValue, rhs: @auto_closure () -> LogicValue) -> Bool {
    if lhs {
        if rhs() == true {
            return true
        }
    }
    return false
}
</pre>
<p>The <code>@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>&amp;&amp;</code> operator.</p>
<p>However, one of the features I suspect that will actually hurt extensibility in Swift is the <strong>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>
<h2>Extensions</h2>
<p>The extension feature in Swift has many use cases. You can read them all in more detail in <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html">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>
<p>Following the example in Apple documentation itself:</p>
<pre lang='swift'>
extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}

let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"

let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
</pre>
<p>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>
<p>What troubles extensions is exactly the fact they are <strong>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>
<p>This has always been a hot topic in the Ruby community with <a href="http://timelessrepo.com/refinements-in-ruby">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>
<h2>The case for protocols</h2>
<p>Protocols are a fantastic feature in Swift. <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html">Per the documentation</a>: &#8220;a protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality&#8221;.</p>
<p>Let&#8217;s see their example:</p>
<pre lang='swift'>
protocol FullyNamed {
    var fullName: String { get }
}

struct Person: FullyNamed {
    var fullName: String
}

let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed"
</pre>
<p>In the example above we defined a <code>FullyNamed</code> protocol and implemented it while defining the <code>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>
<p>I have been long advocating this feature for Ruby. For example, imagine you have the following Ruby code:</p>
<pre lang='ruby'>
class Person
  attr_accessor :first, :last

  def full_name
    first + " " + last
  end
end
</pre>
<p>And you have a method somewhere that expects an object that implements <code>full_name</code>:</p>
<pre lang='ruby'>
def print_full_name(obj)
  puts obj.full_name
end
</pre>
<p>At some point, you may want to print the title too:</p>
<pre lang='ruby'>
def print_full_name(obj)
  if title = obj.title
    puts title + " " + obj.full_name
  else
    puts obj.full_name
  end
end
</pre>
<p>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&#8217;t want to actually modify the contract.</p>
<p>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&#8217; 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>
<p>Since Rails 3, we actually define a contract for those interactions, but there is still no way to:</p>
<ul>
<li>guarantee an object complies with the contract (besides extensive use of tests)</li>
<li>guarantee controllers and views obey the contract (besides extensive use of tests)</li>
</ul>
<p>Similar to real-life contracts, unless you write it down and sign it, there is no guarantee both parts will actually maintain it.</p>
<p>The ideal solution is to be able to define multiple, tiny protocols. Someone using Swift would rather define multiple protocols for the controller and view layers:</p>
<pre lang='swift'>
protocol URL {
    func toParam() -> String
}

protocol FormErrors {
    var errors: Dict<String, Array[String]>
}
</pre>
<p>The interesting aspect about Swift protocols is that you can define and implement protocols for any given type, at any time. The trouble though is that the implementation of the protocols are defined in the class/struct itself and, as such, they change the class/struct globally.</p>
<h2>Protocols and Extensions</h2>
<p>Since protocols in Swift are implemented directly in the class/struct, be it during definition or via extension, the protocol implementation ends up changing the class/struct globally. To see the issue with this, imagine that you have two different libraries relying on different JSON protocols:</p>
<pre lang='swift'>
protocol JSONA {
    func toJSON(precision: Integer) -> String
}

protocol JSONB {
    func toJSON(scale: Integer) -> String
}
</pre>
<p>If the protocols above have different specifications on how the precision argument must be handled, we will be able to implement <strong>only one</strong> of the two protocols above. That&#8217;s because implementing any of the protocols above means adding a <code>toJSON(Integer)</code> method to the class/struct and there can be only one of them per class/struct.</p>
<p>Furthermore, if implementing protocols means globally adding method to classes and structs, it can actually hinder the use of protocols as a whole, as the concerns to avoid name clashes and to avoid namespace pollution will speak louder than the protocol benefits.</p>
<p>Let&#8217;s contrast this with protocols in Elixir:</p>
<pre lang='elixir'>
defprotocol JSONA do
  def to_json(data, precision)
end

defprotocol JSONB do
  def to_json(data, scale)
end

defimpl JSONA, for: Integer do
  def to_json(data, _precision) do
    Integer.to_string(data)
  end
end

JSONA.to_json(1, 10)
#=> 1
</pre>
<p>Elixir protocols are heavily influenced by <a href="http://clojure.org/protocols">Clojure protocols</a> where the implementation of a protocol is tied to the protocol itself and not to the data type implementing the protocol. This means you can implement both JSONA and JSONB protocols for the same data types and they won&#8217;t clash!</p>
<p>Protocols in Elixir work by dispatching on the first argument of the protocol function. So when you invoke <code>JSONA.to_json(1, 10)</code>, Elixir checks the first argument, sees it is an integer and dispatches to the appropriate implementation.</p>
<p>What is interesting is that we can actually emulate this functionality in Swift! In Swift we can define the same method multiple times, as long as the type signatures do not clash. So if we use static methods and extension, we can emulate the behaviour above:</p>
<pre lang='swift'>
// Define a class to act as protocol dispatch
class JSON {
}

// Implement it for Double
extension JSON {
    class func toJSON(double: Double) -> String {
        return String(double)
    }
}

// Someone may implement it later for Float too
extension JSON {
    class func toJSON(float: Float) -> String {
        return String(float)
    }
}

JSON.toJSON(2.3)
</pre>
<p>The example above emulates the dynamic dispatch ability found in Elixir and Clojure which guarantees no clashes in multiple implementations. After all, if someone defines a JSONB class, all the implementations would live in the JSONB class.</p>
<p>Since dynamic dispatch is already available, we hope protocols in Swift are improved to support local implementations instead of changing classes/structs globally.</p>
<h2>Summing up</h2>
<p>Swift is a very new language and in active development. The documentation so far doesn&#8217;t cover topics like exceptions, the module system and concurrency, which indicates there are many more exciting aspects to build, discuss and develop.</p>
<p>It is the first time I am excited to do some mobile development. Plus the Swift playground may become a fantastic way to introduce programming.</p>
<p>Finally, I would personally love if Swift protocols evolved to support non-global implementations. Protocols are a very extensible mechanism to define and implement contracts and it would be a pity to see their potential hindered due to the global side-effects it may cause to the codebase.</p><p>The post <a href="/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/">Comparing protocols and extensions in Swift and Elixir</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>/2014/06/comparing-protocols-and-extensions-in-swift-and-elixir/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
