<?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>assertive code « Plataformatec Blog</title>
	<atom:link href="/tag/assertive-code/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>Wed, 13 Jun 2018 18:54:58 +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>The anatomy of code documentation</title>
		<link>/2018/06/the-anatomy-of-code-documentation/</link>
		
		<dc:creator><![CDATA[Rondy Sousa]]></dc:creator>
		<pubDate>Wed, 13 Jun 2018 18:30:17 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[assertive code]]></category>
		<category><![CDATA[code documentation]]></category>
		<guid isPermaLink="false">/?p=7616</guid>

					<description><![CDATA[<p>Writing code is the activity that turns our ideas into great products and tools. Fingers over a keyboard and a text editor. This is how most people see our daily routine. Suddenly, no words emerge over the screen. The eyes gaze at the monitor and everything looks static: we’re reading code. (And we read lots ... <a class="read-more-link" href="/2018/06/the-anatomy-of-code-documentation/">»</a></p>
<p>The post <a href="/2018/06/the-anatomy-of-code-documentation/">The anatomy of code documentation</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<p><span style="font-weight: 400;">Writing code is the activity that turns our ideas into great products and tools.</span></p>
<p><span style="font-weight: 400;">Fingers over a keyboard and a text editor. This is how most people see our daily routine. Suddenly, no words emerge over the screen. The eyes gaze at the monitor and everything looks static: we’re reading code.</span></p>
<p><span style="font-weight: 400;">(And we read <strong>lots</strong> of code).</span></p>
<p><span style="font-weight: 400;">The reading process demands a huge cognitive effort from us. Once we read a piece of code for the very first time, we’re immersed in a long learning curve and a continuous cycle of questionings, doubts, and insights. Reading code requires us to dig through the mental model of a domain problem and to continuously analyze the input, processing and output flows of some business requirement.</span></p>
<p><span style="font-weight: 400;">Sure, good developers have been exposed to good writing practices, and there is nothing like reading a clean, robust and elegant piece of code. Our methods are small and expressive and intend to reveal interfaces. </span></p>
<p><span style="font-weight: 400;">Nevert</span>heless, we still must read them line by line, and gradually lay down our understanding about it.</p>
<p><em>(&#8220;Only well written and tested code is not enough to connect the dots…&#8221;, some wise person may have already said this before.)</em></p>
<p>A large number of whiteboard discussions may have been lost, merely because there was no room for those. Commit messages were laconic and our memorization skills were overestimated. Yesterday’s obvious is now a mine of untangled knowledge.</p>
<p>Furthermore, the practice of comment about code is often discouraged. After all, we prioritize working software over overwhelming documentation. We’re agile developers and we cannot afford the maintenance burden. Code comments are mostly faced as the inability to express oneself in a clever way, and the activity of documenting code is usually associated with redundant, undesired and ungrateful comments.</p>
<p>But here it goes: <strong>the key point on documenting is maintaining information that resists as time goes by.</strong></p>
<h2>A practical example</h2>
<p>Suppose our sample application deals with a concept of contracted plans on its domain, where each plan offers a storage limit in a remote storage service. One of the requirements is to present a summary of a contracted plan’s consumption, as shown in the example below:</p>
<pre><code>'2.44% (500 MB of 20 GB)' # User has consumed 2.44% from a 20 gigabytes
                          # storage limit (i.e., 500 megabytes).
</code></pre>
<p>Our source data is a domain object <code>ContractedPlan</code>, which exposes two main pieces of information: the storage limit value (in the <code>plan_storage_limit column</code>) and the total consumed (in the <code>total_consumed</code> column) until the present moment, both persisted in numeric bytes in the database.</p>
<p>The consumption summary must present these two pieces of information, in addition to the percentage of how much has been consumed until now:</p>
<pre><code>\&gt; contracted_plan = ContractedPlan.last

\&gt; contracted_plan.plan_storage_limit # Client has contracted a 20 GB plan.
# =&gt; 20_000_000_000

\&gt; contracted_plan.total_consumed # User has consumed 500 megabytes until now.
# =&gt; 500_000_000
</code></pre>
<p>The percentage of how much has been consumed can be calculated simply applying the following statement:</p>
<pre><code>\&gt; total_consumed_in_percent =
  (total_consumed * 100.to_f / total_contracted).round(2)
# =&gt; 2.44
</code></pre>
<p>Knowing that such summary statement must be rendered in an HTML page, we’re gonna create a <code>ContractedPlansHelper#plan_consumption_summary</code> helper with the following implementation:</p>
<pre><code class="ruby">module ContractedPlansHelper
  def plan_consumption_summary(contracted_plan)
    total_contracted = contracted_plan.plan_storage_limit
    total_consumed = contracted_plan.total_consumed
    total_consumed_in_percent =
      (total_consumed * 100.to_f / total_contracted).round(2)

    format(
      '%s%% (%s de %s)',
      total_consumed_in_percent,
      number_to_human_size(total_consumed, precision: 4),
      number_to_human_size(total_contracted)
    )
  end
end
</code></pre>
<p>The <code>#plan_consumption_summary</code> method has a structure divided into two main parts: data preparation and data presentation (including the step for formatting the three expected pieces of information).<br />
Even though it looks like a simple and straight logic, there are some points not so obvious for newcomers to that code. The data presentation part depends on a moderately complex structure, in a way that is not an easy piece to digest regarding the &#8220;shape&#8221; of the returned String (i.e., the syntax of the format method, besides the two calls for the <code>#number_to_human_size method</code>).</p>
<p>There are, of course, some ways to find out how the returned text will be printed out:</p>
<ul>
<li>Reading the unit tests;</li>
<li>Opening the page that uses that helper on the web browser; or</li>
<li>Executing the helper on the application console (rails console).</li>
</ul>
<p>All alternatives, however, requires the reader to make an additional effort. All of them encourage the reader to leave out its current context, which is reading the application code in the text editor. In that case, we can leverage code documentation as a technique to facilitate the expected understanding.</p>
<p>First of all, the <code>plan_consumption_summary</code> method can provide a simple usage example, with real data expected from business customers:</p>
<pre><code class="ruby"># plan_consumption_summary(contracted_plan)
# # =&gt; '2.44% (500 MB of 20 GB)'
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>The first goal was accomplished. We have diminished the learning barrier to the method logic, without breaking the flow of reading code. Moreover, by being exposed to real data examples, we had a better understanding of some concepts present in the application domain, at a very low cost.</p>
<p>The next snippet that we may add is a title that describes briefly what is the method in that case. Let&#8217;s think for a moment. How would we describe the <code>plan_consumption_summary</code> to someone who has just joined the project?</p>
<p>A possible dialog could be:</p>
<blockquote><p>
  Well, this method returns a summary of how much a user has consumed in a certain plan.
</p></blockquote>
<p>Bringing the same information to the code, we have this:</p>
<pre><code class="ruby"># A summary of how much some user has consumed in a certain plan.
#
# plan_consumption_summary(contracted_plan)
# # =&gt; '2.44% (500 MB of 20 GB)'
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>By describing the title of a method, we have the chance to reflect and identify whatever noise is between a concept and its implementation. The mere act of writing documentation helps us to give remarkable names to our objects, methods, and variables. If the previously written code has been derived only from what was talked or listened, now we have a third communication channel.</p>
<p>At this moment, our documentation has two pieces of information with different semantics: a title and an example. We can apply to it a bit of hierarchy, (i.e., setting apart free text and code), we can make this structure a bit more evident:</p>
<pre><code class="ruby"># A summary of how much some user has consumed in a certain plan.
#
# Examples
#   plan_consumption_summary(contracted_plan)
#   # =&gt; '2.44% (500 MB of 20 GB)'
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>We can also add up a piece of information that points out that the method has a public visibility and, therefore, can be used by outside application code (i.e., the view layer). In our example, we use the <code>Public:</code> keyword:</p>
<pre><code class="ruby"># Public: A summary of how much some user has consumed in a certain plan.
#
# Examples
#   plan_consumption_summary(contracted_plan)
#   # =&gt; '2.44% (500 MB of 20 GB)'
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>The third point that we can cover is about the type/shape of data that will be returned from the method. Since we know that the return type will be a String, we can add such information with <code>Returns a String:</code></p>
<pre><code class="ruby"># Public: A summary of how much some user has consumed in a certain plan.
#
# Examples
#   plan_consumption_summary(contracted_plan)
#   # =&gt; '2.44% (500 MB of 20 GB)'
#
# Returns a String.
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>In order to complete the input-processing-output triad, we also describe the expected input data, along with a brief description of each snippet. Our case is simple, as we just want an instance of <code>ContractedPlan</code> model, and there is no other primitive values involved.</p>
<pre><code class="ruby"># Public: A summary of how much some user has consumed in a certain plan.
#
# contracted_plan - A ContractedPlan instance.
#
# Examples
#   plan_consumption_summary(contracted_plan)
#   # =&gt; '2.44% (500 MB of 20 GB)'
#
# Returns a String.
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>We have now a basic backbone of code documentation. We know how to answer the &#8220;what&#8217;s&#8221; and &#8220;how&#8217;s&#8221; intrinsic to the <code>#plan_consumption_summary</code> method. We can finally include another significant piece of information, one that is mostly unfeasible to describe using just the programming language lexicon: the context.</p>
<p>We know context is everything. Unfortunately, there is information that might be lost in time, especially after some cycles of team rotation and turnovers. The context can help us out to surface the aspects of &#8220;when to use a method&#8221; and &#8220;the reason/intentions behind using this&#8221;.</p>
<p>In our example, we can describe something that conveys the following message:</p>
<blockquote><p>
  The <code>plan_consumption_summary</code> method is important so that users have access to what has already been consumed by them (since they could run out of storage space), and it can be used on pages that present data on plan consumption.
</p></blockquote>
<p>Assuming that such information is relevant, we can include it on the code documentation:</p>
<pre><code class="ruby"># Public: A summary of how much some user has consumed in a certain plan.
#
# This can be used whenever the information about a contracted plan is
# presented to the its user. This way, they can get a quick overview
# regarding the current state of the plan usage.
#
# contracted_plan - A ContractedPlan instance.
#
# Examples
#
#   plan_consumption_summary(contracted_plan)
#   # =&gt; '2.44% (500 MB of 20 GB)'
#
# Returns a String.
def plan_consumption_summary(contracted_plan)
  total_contracted = contracted_plan.plan_storage_limit
  total_consumed = contracted_plan.total_consumed
  # ...
</code></pre>
<p>We can consider the job done now.</p>
<p>It is then a good time to notice that the format used in our example was not conceived by my free will. Attentive readers may have perceived that we used the <a href="http://tomdoc.org/">TomDoc</a> format, created by Tom Preston-Werner. The TomDoc spec aims for simplicity and clarity of communication and it is hugely used in GitHub projects (and here at Plataformatec as well).</p>
<p><strong>Conclusion</strong></p>
<p>An important goal of writing code documentation is to provide an initial context to facilitate and foster the understanding of a piece of code. It&#8217;s an empathetic tool that provides a rough, overall idea of the code, even before &#8220;one starts reading the code&#8221;. By using it wisely, the reader can get a glimpse of what will be executed by the language interpreter/compiler, with little effort.</p>
<p>Code documentation is, of course, only one of many other artifacts that are at our disposal, in order to keep the knowledge base of a software system alive. I consider that as important as having well-described commit messages, README files, project wikis, architectural decision records, BDD specification. etc. They all work together focused on the same essential goal: empower developers to write better software.</p><p>The post <a href="/2018/06/the-anatomy-of-code-documentation/">The anatomy of code documentation</a> first appeared on <a href="/">Plataformatec Blog</a>.</p>]]></content:encoded>
					
		
		
			</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>
	</channel>
</rss>
