<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Meta Language - Medium]]></title>
        <description><![CDATA[Talking about programming languages - Medium]]></description>
        <link>https://medium.com/metalanguage?source=rss----3b8f86a5915b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Meta Language - Medium</title>
            <link>https://medium.com/metalanguage?source=rss----3b8f86a5915b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:06:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/metalanguage" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rubinius backtraces just got flipped right-side up]]></title>
            <link>https://medium.com/metalanguage/rubinius-backtraces-just-got-flipped-right-side-up-214482b5639a?source=rss----3b8f86a5915b---4</link>
            <guid isPermaLink="false">https://medium.com/p/214482b5639a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-tools]]></category>
            <category><![CDATA[rubinius]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Brian Shirai]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 21:14:24 GMT</pubDate>
            <atom:updated>2019-04-07T21:14:24.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improving developer experience, one error at a time.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oxhxVg_bLdcedAWETfzAA.jpeg" /><figcaption>by <a href="https://www.flickr.com/photos/pagedooley/">Kevin Dooley</a> <a href="https://www.flickr.com/photos/pagedooley/2832295909/in/photolist-5jhfU6-nqerS3-kGSzW9-8RbnbD-5S4dLJ-3UN759-9NGBho-nGqW7x-74n5GF-9NAsCc-4TQ7Sn-kGR7ip-7wRP4a-bruZyU-o4sJmz-fLuxJJ-6JEbNm-21RUAZ7-6m7iq6-8wRsHo-cxxraA-kj94cE-a8gywn-KzcH7o-GSHkK6-dKKLM-nGGgy1-e9S3nz-aRQfRk-qFR6He-6BKvm3-nEFdJE-e9XXuL-nmdN3e-29Jabm7-nqerCW-nGqVTr-8ktJCG-asAEai-e9XUyC-nJvgTP-a3CRa8-e9Soxt-4WqxeC-nkWN68-6SqKCA-BFzWxZ-nmgiWh-nGHRKX-b4KD9R/">CC BY 2.0</a></figcaption></figure><p><a href="https://medium.com/@rubinius/rubinius-backtraces-just-got-flipped-right-side-up-3d632c0b7905"><em>This article was originally published Nov 6, 2016</em></a><em>.</em></p><p>It’s easy when everything is going well. It’s when things don’t go as expected that we often need all the help we can get to figure things out.</p><p>When an exception is raised in a language like Ruby, we’re often left with a jumble of text and not much else. There’s that feeling of complete confusion about what happened and what to do next that washes over you. This is about as pure an experience of “things not going as expected” as we get.</p><p>Many years ago, <a href="https://twitter.com/defiler">Wilson Bilkovich</a> added color to the Rubinius backtraces using <a href="https://en.wikipedia.org/wiki/ANSI_escape_code">ANSI escape codes</a>. The source line where the exception was raised was rendered in red, the Ruby code in the Rubinius core library in blue, and other code (presumably application code) was rendered in the foreground color. This was a bold attempt to quell some extent of the confusion associated with backtraces.</p><p>Later, <a href="https://twitter.com/evanphx">Mx. Evan Phoenix</a> improved rendering of the backtraces by right aligning the rendering of <strong>receiver + method name</strong> and keeping the source location from obstructing the ability to read the method name by pushing rightward a source location longer than the terminal width.</p><p>The result was a backtrace that rendered something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lt25Xz2H9BlPQEL-MbesQg.png" /></figure><p>This rendering made it significantly easier to read the method names by surrounding them with whitespace and providing an almost consistent right edge for your eyes to track.</p><p>However, there are a couple critical problems with this approach. Color is a very difficult thing to use to improve readability because of how different people perceive color (potentially not at all) and how any choice of color may interact with a person’s terminal colors, something Rubinius has no control over.</p><p>Another problem is that splitting up the source location makes it nearly impossible to quickly copy-paste the location to open a file in an editor.</p><p>Finally, there is the issue of the order in which the backtrace lines are rendered. In a blog post titled, <a href="http://yellerapp.com/posts/2015-01-22-upside-down-stacktraces.html"><em>Be Mad: Stacktraces are All Upside Down</em></a><em>,</em>it is noted that many programmer minutes are wasted scrolling back up to read what the exception was and what the relevant frames are when a backtrace is rendered to a terminal and scrolls out of view.</p><p>That post really makes you question, “Why <em>do</em> we render backtraces like this?”</p><p>Maybe we’ll never know. But a useful question is, “How might we improve how we render backtraces?”</p><p>I’ve taken a crack at that and want to share the results with you. I’m not saying this is the best we can do (more on that later), but I’ll walk through the decisions I made and my rationale for them.</p><p>First, I took the upside-down criticism to heart and reversed the rendering order. I also rendered the source code location indented on a separate line when the total rendering length of the backtrace line would exceed the terminal width. This makes it possible to easily copy-paste the source location. Finally, I ditched the color and opted instead for bolding the <strong>receiver + method name</strong> component.</p><p>Here’s how that looked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKWDXTFMPQZtdZIupjL0Nw.png" /></figure><p>I was pretty happy with the result. The contrast makes it easy to read the method names. (If the terminal doesn’t render bold, it’s only the contrast that would be lost, not any content.) And the exception message at the bottom makes it a snap to read what happened and start looking at the context (the backtrace) by scanning up from where my cursor is now. If I need to copy a source location, that would be as simple as a double-click or <em>Command+click</em> to open the file (I use iTerm).</p><p>Something still bothered me a lot about this rendering. To figure out what, I broke the backtrace line down into components: 1. the fully-qualified receiver name (A::B::C); 2. the instance / module method indicator (#, .); 3 the method name; and 4. the source location.</p><p>I also considered the tension between rendering a single line of a backtrace (e.g. formatting decisions I would make in isolation considering only that line) and rendering a backtrace as a whole (more than just a set of individual lines).</p><p><em>The number one piece of information that I want to index on when trying to make sense of a backtrace is the method name.</em>This tells me the most about what may be happening. A secondary piece of information is either the fully-qualified receiver name or the instance / module method indicator. Once I’ve keyed in on one of these, I may move to examining the source code at the specified location.</p><p>So, if the method name is so important, why is it buried in a dense thicket of characters in the middle of the backtrace line? Mostly simply because <strong>A::B::C#name</strong> or <strong>A::B::C.name</strong> is a well-established convention in Rubinius to refer to a method. This convention carries over without much question to rendering a backtrace.</p><p>I decided to challenge this convention and pulled the method name to the front of the line. I also added a bit of whitespace to separate the method name, instance / module method indicator, and the fully-qualified receiver name. I retained the bold formatting for the entire <strong>receiver + method name</strong> component.</p><p>Here’s what the final rendering looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3p0BEg7htrMm5oM5Y8ScA.png" /></figure><p>This rendering provides a right-aligned edge for my eyes to track while reading method names, as well as a fixed point to start reading the fully-qualified receiver name. In contrast to the earlier rendering, aligning this component doesn’t push some names way far to the right because of a high variability in the length of the receiver name.</p><p>The source locations that are rendered on a separate line are indented and left-aligned. This creates another line in the backtrace that supports scanning up the method names.</p><p>Another thing I noticed about reversing the order of rendering the backtrace lines: I can scan <em>up</em> the relevant portion of the stack, and then back <em>down</em> mentally following the execution of code, without scrolling my terminal. This gives me the best of both options, something not possible with the previous ordering once the relevant lines scrolled out of view.</p><p>Leading with the method name also improves readability when functions will be interleaved with object-oriented method names in the backtrace.</p><p>I think the new rendering is a big improvement in readability and <a href="http://uxmag.com/articles/effective-developer-experience">developer experience</a> (DX), but I’m sure there is more we can do. Terminals are still fairly primitive devices. The <a href="https://github.com/rubinius/atom-rubinius-terminal">Atom Rubinius terminal</a> and the <a href="https://github.com/rubinius/rubinius-console">Rubinius Console</a> are two projects aimed at significantly improving developer interaction with running code without moving into the traditional IDE space. Finally, improving the modularity of backtrace rendering in Rubinius is an important aspect of making Rubinius better at being language agnostic.</p><p>So, go make something unexpected happen with your code and help us improve your developer experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214482b5639a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metalanguage/rubinius-backtraces-just-got-flipped-right-side-up-214482b5639a">Rubinius backtraces just got flipped right-side up</a> was originally published in <a href="https://medium.com/metalanguage">Meta Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[nil Is Not NULL, and Other Tales]]></title>
            <link>https://medium.com/metalanguage/nil-is-not-null-and-other-tales-febf6730f216?source=rss----3b8f86a5915b---4</link>
            <guid isPermaLink="false">https://medium.com/p/febf6730f216</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[segmentation-fault]]></category>
            <dc:creator><![CDATA[Brian Shirai]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 18:15:14 GMT</pubDate>
            <atom:updated>2019-04-07T18:15:14.751Z</atom:updated>
            <content:encoded><![CDATA[<h4>The ill-conceived origin of Ruby’s “lonely operator”.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ObGP57y2BNi5a-YnkZfCHQ.jpeg" /><figcaption>by <a href="https://www.flickr.com/photos/jircas/">JIRCAS Library</a> <a href="https://www.flickr.com/photos/jircas/36700662536/in/photolist-XV7ukJ-XXj6Yx-UvveS2-XV7pEm-XThm5Y-XXo78c-XJpFgu-XK7c6P-WHS7aR-XThmfh-WHS65e-XooyRL-XZg4gH-XooyWq-XXo5v4-XJfsJy-XXocbt-WKJZH4-XK7efZ-XXo55p-XLWQxa-XJfuL9-XV72mo-XK3e3H-XmmBRQ-XK3erP-XmqT5Y-XooAU3-XK7c1Z-XZez78-XV5pnS-WG6dHX-WKGUDk-XoeL5f-XJdMAL-XK3dYV-XXoaND-Tqwuvj-GwdgPC-XJfv5W-XThsjG-WFCCDN-WHS6ht-XZW6et-UvveHz-XXoci2-29r48LS-XmmBg1-XK3dN4-XmmBsJ">CC BY 2.0</a></figcaption></figure><p><a href="https://medium.com/@rubinius/nil-is-not-null-and-other-tales-d2c614d08da5"><em>This article was originally publish Jul 13, 2017</em></a>.</p><p>With the 2.3 release, Ruby has introduced a new operator. Designated the “lonely operator”, this new Ruby syntax (&amp;.) adds unnecessary complexity, inconsistency, and additional confusion for developers.</p><p><em>Here is the </em><a href="https://github.com/ruby/ruby/blob/trunk/doc/NEWS-2.3.0#L28-L41"><em>Ruby 2.3 News file</em></a><em> describing the “lonely operator” (aka the “safe navigation operator”). And this is the </em><a href="https://bugs.ruby-lang.org/issues/11537"><em>Ruby Redmine feature ticket</em></a><em>.</em></p><p>Ruby is often criticized for code that developers cannot easily understand or reason about. This new operator creates a second way to call a method that doesn’t improve code, nor does it improve the ability of a developer to reason about the code.</p><p>This post dissects some of the confusion about nil and explains the significant downsides of this new operator.</p><p>Fundamentally, there are two problems to solve:</p><ol><li><strong>Developers want their programs to be reasonably deterministic, and random runtime exceptions from an errant nil value are one of the most obvious things that interferes with that determinism;</strong></li><li><strong>Understanding the behavior of a program written with a dynamically-typed language requires specific tools.</strong></li></ol><p>The “lonely operator” partially and inconsistently addresses the first problem, but with significant and unnecessary complexity that does not pay for itself. It does nothing to address the second problem.</p><h3>nil is an Object, NULL is a memory pointer</h3><p>Sometimes developers from Ruby visit a mysterious and magical land, called Static Typing, and return with deliriously happy tales of programs that always work, are easy and inexpensive to write, and run for decades. Sometimes developers from that land visit Ruby and laugh. This makes some Ruby developers sad and they start thinking that Maybe if Ruby had Option “types”, they could easily write perfect code that runs for decades, too.</p><p>Sadly, when this happens, Ruby developers are confusing a simple little Ruby <em>object</em> for something that’s usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0. When 0 is used as a memory pointer, most computers very sternly complain, abort your program, and send you packing to the principal’s office.</p><p>But in Ruby, nil is an object. You can use it as a value, you can call methods on it, you can define methods for it. It’s <em>not</em> NULL and it doesn’t make your programs vulnerable to things that NULL makes your program vulnerable to.</p><p>Even when Ruby developers understand that nil is not NULL, they still often perceive it as some evil thing to be destroyed. This perspective usually comes from the fact that calling a method on nil that it doesn’t implement raises a runtime exception, which causes your program to abort.</p><p>To be absolutely clear, a <em>segmentation fault </em>and a <em>runtime exception </em>are radically different things. But the consequence, your program aborts, makes them seem quite similar.</p><p>In a statically-typed language, even if the implementation doesn’t treat its “nil-like” value as NULL, it still must resolve, <em>at compile time</em>, that a particular function or method will be called, and if its “nil” doesn’t support that, something must be done. This characteristic of a statically-typed language makes nil <em>seem </em>dangerous.</p><p>In Ruby, the fact that calling a method on nil that it doesn’t understand results in a runtime exception is not a fundamental aspect of the language. Instead, it’s a simple decision that was made, and it’s possible to make a different decision, and you can do this in your own program at any time. We’ll explore that aspect of nil later.</p><h3>nil is mathematically realistic</h3><p>In mathematics, and specifically with functions and sets, the idea of nil is both necessary and useful (just as it is in Ruby, but that’s discussed later).</p><p>A <a href="https://en.wikipedia.org/wiki/Partial_function"><em>partial function</em></a><em> </em>is a function where every input may not map to an output. A value like nil signals that “no mapping is available for that input”. It’s a very useful concept.</p><p>With sets, we also know how to compute with such a concept. For example, consider set intersection, the operation that produces from two input sets, the set of members that both have in common. For example, { 1, 2, 3 } intersect{ 3, 9, 12 } would yield the set { 3 }. In the case of two sets that don&#39;t share any members, the result of the intersection operation is the null set, often denoted by { }.</p><p>For some operation like, A intersect B union C, an exception is not raised if the result of A intersect B is the null set. There&#39;s nothing particulary odd or special about this; it&#39;s entirely natural.</p><p>So why is nil such a big deal in Ruby? Ah, now that’s a good question.</p><h3>nil is mistreated in Ruby</h3><p>There are two problems with the way nil is treated in Ruby. One problem, listed above, is that nil is misunderstood and considered an unwanted nuisance. The other, bigger problem, is that nil is ill-defined in Ruby. It’s handicapped for no good reason.</p><p>In the first case, developers tend to see nil as an <em>error</em>, and hence, it is quite unwelcomed. “Oh look, that method returned a nil, something must be <em>wrong</em>!”</p><p>No, not at all! Nothing need be wrong. The method returned a nil to say, “no value here!”</p><p>Related to the problem of seeing nil as an error condition, some Ruby APIs treat nil as a marker (or sentinel) value. In Rubinius, this is such a problem that we had to introduce a special value we called “undefined” to be able to implement the Ruby core library in Ruby. The problem is that some methods take nil as a value, but also have a default value. So, we were unable to distinguish between some_method() and some_method(nil).</p><p>Finally, because nil is ill-defined, <em>and </em>because developers are inclined to see nil as an error condition, when a method is called on nil that it doesn’t understand and a runtime exception is raised, it reinforces this dysfunctional relationship with nil.</p><p>This brings us to the ill-conceived “lonely operator”.</p><h3>The “lonely operator” is an unnecessary mistake</h3><p>The “lonely operator” supposedly solves the problem of calling a method on nil that then raises a runtime exception causing the program to abort.</p><p>Unfortunately, it only partially solves this problem, further requiring the newly introduced #dig methods (also unnecessary). It isn&#39;t necessary, and doesn&#39;t even solve the problem. What a mess.</p><p>Essentially, the “lonely operator” adds unavoidable complexity to syntax and programs, adds cognitive load to developers, and is an incomplete solution to the problem. Let’s look at each of these in turn.</p><ol><li>It increases system and code complexity: At every place a method is called, there must now be a decision about whether to use . or &amp;.. The lonely operator <em>doubles the complexity</em>of making a method call and due to interaction with other aspects of coding, significantly more than doubles overall complexity.</li><li>It makes communication about code difficult: How do we communicate to other developers when to use . and when to use &amp;.? Why is it acceptable to ignore exceptions in one area of the code, but not in another? What happens when that decision is distant from the code you are looking at? What happens when those assumptions change?</li><li>It doesn’t solve the underlying problem: The real, and legitimately painful, problem that developers need help with is understanding what their programs are actually doing when they run them. We’ll look at this problem below.</li></ol><h3>nil is A Good Thing™</h3><p>The object nil in Ruby is neither a dangerous thing, nor a bad thing. It’s actually a good thing!</p><p>If we focus on behavior, and objects inter-operating based on the behaviors they support, nil is a useful concept. It corresponds to “nothing”, “no behavior here”. It doesn’t need to interfere with code functioning, and is only relevant when delivering a result to the user. We need to be able to say, “Hello there, that thing you requested doesn’t actually have any representation”. <em>If that even matters</em>. Sometimes it doesn’t matter at all, and nil is just a blank.</p><h3>The simple alternative to the “lonely operator”</h3><p>The only thing that the “lonely operator”, and the new #dig methods, provide is the ability to ignore runtime exceptions from calling a method on nil.</p><p>A very simple alternative with no special syntax has existed in Ruby forever. Let’s see how that works.</p><p>First, we recall that nil is a singleton value of NilClass. Nothing special, just an object that already responds to a few methods, like #to_s, #to_h, #to_c, #to_a.</p><p>In Rubinius, you can find where a method in the core library is defined by calling #inspecton the Method object:</p><pre>irb(main):001:0&gt; nil.method(:method_missing)<br>=&gt; #&lt;Method: NilClass#method_missing (defined in Kernel at kernel/delta/kernel.rb:46)&gt;</pre><p>We can see that NilClass has inherited #method_missingfrom Kernel. Simple, we&#39;ll just open NilClass, define our own #method_missing, and see how that works.</p><pre>class NilClass<br>  def method_missing(*)<br>    self<br>  end<br>end</pre><p>Here’s the way to look at it: <em>nil is the value (or object) that turns every method into the identity method</em>.</p><p>The concept of an identity function is fundamental in math. A function f(x) = x for all x is the identity function; it returns its input unchanged.</p><p>We could reverse this perspective and talk about the value instead of the function. We could say, NIL is the value that when passed to any function, the result is NIL: f(NIL) = NIL for all functions f.</p><p>In Ruby, we can do this with nil: nil.m =&gt; nil for (almost) any method m.</p><p>So, with the very simple addition above, let’s compare some code, first on Ruby 2.3.0 and then on Rubinius 3.5:</p><pre>$ ruby -v<br>ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]<br>$ irb<br>irb(main):001:0&gt; a = nil<br>=&gt; nil<br>irb(main):002:0&gt; a&amp;.+2 * 3 + 5<br>=&gt; nil<br>irb(main):003:0&gt; h = {a: 1}<br>=&gt; {:a=&gt;1}<br>irb(main):004:0&gt; h[:b][:c][1]<br>NoMethodError: undefined method `[]&#39; for nil:NilClass<br>	from (irb):4<br>	from /Users/brianshirai/.rubies/ruby-2.3.0/bin/irb:11:in `&lt;main&gt;&#39;<br>irb(main):005:0&gt; h.dig(:b, :c, 1)<br>=&gt; nil</pre><p>Now, for Rubinius:</p><pre>$ ruby -v<br>rubinius 3.5 (2.2.0 1453a0a5 2016-01-10 3.5.1 JI) [x86_64-darwin15.2.0]<br>$ irb<br>irb(main):001:0&gt; class NilClass<br>irb(main):002:1&gt; def method_missing(*)<br>irb(main):003:2&gt; self<br>irb(main):004:2&gt; end<br>irb(main):005:1&gt; end<br>=&gt; :method_missing<br>irb(main):006:0&gt; a = nil<br>=&gt; nil<br>irb(main):007:0&gt; a + 2 * 3 + 5<br>=&gt; nil<br>irb(main):008:0&gt; h = {a: 1}<br>=&gt; {:a=&gt;1}<br>irb(main):009:0&gt; h[:b][:c][1]<br>=&gt; nil</pre><p>We can see that we need to use undeniably more complex syntax (a&amp;.2), and <em>inconsistent</em> syntax (#dig), to achieve the same thing on Ruby 2.3.0. In contrast, with <em>no syntax changes</em> on Rubinius 3.5, by merely using fundamental Ruby features (ie defining a method), we have consistent syntax and the same result.</p><p>Avoiding runtime exceptions when calling methods on nil is both easy and natural in Ruby. No special syntax and no extra confusion required. But solving <em>this</em> part of the problem isn’t that important. It’s the second part of the problem that is way more important to solve for developers.</p><h3>Ruby developers need to see where nil is</h3><p>The real problem that developers need Ruby to solve is the ability to know where nil values come from when they are <em>not</em> desired. As demonstrated above, the simple solution to <em>computing with nil</em> without causing runtime exceptions already exists in Ruby and has since forever.</p><p>This problem of knowing where a value comes from is much bigger than nil. It is a result of the fundamental tradeoff that a late-bound language (usually called a <em>dynamically-typed</em> language) makes relative to an eagerly-bound language (usually called a <em>statically-typed</em> language).</p><p>The tradeoff has a massive benefit that is under-appreciated. Late binding provides a malleable system that easily manages the complexity of high-uncertainty contexts. Objects can interact with other objects that provide certain behaviors. They <em>do not</em> have to be specific <em>kinds</em> of objects. The lessening of the constraints that <em>the developer’s assumptions</em> impose on the system can increase the utility and resilience of the system.</p><p>Unfortunately, as is often the case, we are seeing the world in black and white, picking one side, and missing half the picture. Late bound languages make simple code able to manage a lot of runtime complexity, but also potentially add a lot of confusion for the developer trying to understand what the runtime behavior actually is in a particular case.</p><p>The solution to the problem of understanding runtime behavior is a system that provides rich analysis features for the developer. Rubinius is building a system like this. Having a general solution is great, but we can get a lot of benefit from focusing specifically on nil.</p><h3>Traceable nils in Rubinius</h3><p>In Rubinius, there are two types of “objects”. There are objects like an Array, Object, or Hash instance, or an instance of some class in your code. These objects have <em>two parts</em>: 1. the object’s data, which lives somewhere in memory, and 2. the object’s <em>reference</em>, or pointer to the location of the object’s data.</p><p>There’s another kind of object in Rubinius. These are called <em>immediate values</em> because their data and their “reference” are the same thing. These are also called <em>tagged pointers</em> because the value is essentially a memory pointer where we’ve set one or more “tag” bits.</p><p>Values like 1, 0xcafe, true, false, and nil are immediate values, or tagged pointers, in Rubinius. This is what nil looks like as a (binary formatted) pointer value 0b11010. If the least significant five bits of a pointer match that value, the value is considered by Rubinus to be nil.</p><p>In the past, we have only ever used that precise value. In other words, all the other bits are zero. But nothing requires this, and those other bits don’t need to be wasted. On 64bit architectures, this gives Rubinius approximately 2⁵⁹ values of “nil”. That’s more than enough for a typical Rails app, I’m sure.</p><p>So, how can we use this abundance of nil values? Easy! When a method returns nil and that nil is not a value that was propagated from a value passed to the method, we can return a nil that is tagged for that specific method. The value behaves exactly as nil, when nil was a singleton value. But now we can find the source of the nil when we encounter it later. We can trace various paths of specific nils through code and help the developer understand why a particular value is nil.</p><p><em>This is the problem that developers need Ruby to solve</em>. It’s already possible with zero extra complexity of syntax, communication, and cognitive load to avoid runtime exceptions when calling methods on nil. But <em>the system</em> needs to help developers understand how their code is functioning, and why it is functioning that way.</p><p>There’s only one other feature we need to add to Rubinius, return value type caching. We already cache the type of values at method call sites, and those caches help the JIT generate more efficient machine code. With return value type caching in place, the JIT will improve and Rubinius runtime analysis tools will be even more powerful.</p><h3>A system must support writing AND running code</h3><p>Everything that we’ve been looking at in this post points to a fundamental concern with programming: Our systems have been woefully incomplete. There are extremely few problems that we know everything about up front. Most “interesting” problems have significant novelty or they would already have simple solutions. To support writing programs for these problems, we need to help the author write code <em>and</em> we need to help the author understand the code as it runs.</p><p>This is the fundamental problem that Rubinius is focused on. If that interests you, come hang out with us and talk about it <a href="https://gitter.im/rubinius/rubinius">in our Gitter chat</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=febf6730f216" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metalanguage/nil-is-not-null-and-other-tales-febf6730f216">nil Is Not NULL, and Other Tales</a> was originally published in <a href="https://medium.com/metalanguage">Meta Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Objects are for interactions, functions are for data]]></title>
            <link>https://medium.com/metalanguage/objects-are-for-interactions-functions-are-for-data-936e044cc729?source=rss----3b8f86a5915b---4</link>
            <guid isPermaLink="false">https://medium.com/p/936e044cc729</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Brian Shirai]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 17:35:04 GMT</pubDate>
            <atom:updated>2019-04-07T18:00:03.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>Does Ruby have functions?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wetP0CBKu6Izrmb3-Y1mDA.jpeg" /><figcaption>by <a href="https://www.flickr.com/photos/cogdog/">Alan Levine</a> <a href="https://www.flickr.com/photos/cogdog/23926524602/in/photolist-CsiGbf-dRcEho-2coVKMS-2odNk4-GD3EKL-z7H3DE-G3x7PY-A2sbeJ-FxcbSA-Gjuybm-FxnLdH-RWdXty-GmPd1a-WUqXy5-RvLa5K-SJfVKM-SJfUMz-SJfVFZ-RD9rao-2aDSKz7-FwfQDj-X6xsBm-VThKx3-7xvjRF-Q9W5hN-rzi7j6-PZsLqU-2dDwPeS-eZtYt7-J7zeAF-2f71bD4-eZhBV8-PqiLJG-Ptuhwi-PqiBNW-NUVFXE-QyAEPe-23Y4ydt-NdVcLo-PioJuD-RyQoAQ-29z7seF-4X9yp1-Nf9kra-Nf4KMK-2cyhgHm-2aW6jHG-NUZBpo-Nf4Mdk-PfLdKo">CC-BY</a></figcaption></figure><p><em>This article was originally published Aug 19, 2016 under the title</em> <a href="https://medium.com/@rubinius/rubinius-takes-the-fun-out-of-ruby-21db64ce87a6">Rubinius takes the fun out of Ruby</a>.</p><p>Let’s talk about fun. Not “fun” fun, but the common shortening of the word “function”. I’ll start with a question: <em>“True or false, Ruby has functions?”</em></p><p>If you’ve been writing Ruby for any time, this question probably makes you squirm a little. There’s the often touted <em>elegance</em> of Ruby where “everything is an object”.</p><p>That’s not quite true, though, and very simple to demonstrate. Just try assigning a block to a variable. No, not a Proc, a block. Oh, you can’t do that because blocks are not Ruby objects in Ruby.</p><p>In Rubinius, a block is just another real, live Ruby object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2820a8d7eb8860fc7683f4fe28822f1/href">https://medium.com/media/a2820a8d7eb8860fc7683f4fe28822f1/href</a></iframe><p>But I digress. What were we… ah, yes, functions. No wait, objects.</p><p>When everything is an object (but not really), we tend to think we have only <em>methods</em>. In Ruby, everything gets defined on some object. Even defining a method outside of any class or module, like in a script, implicitly puts the method on <strong>Object</strong>. From our earlier example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edd86874641059734397554460017526/href">https://medium.com/media/edd86874641059734397554460017526/href</a></iframe><p>Ok, so we’ve put this question to rest, right? Ruby does <em>not</em> have functions.</p><p>Ah, if only life were so simple.</p><p>Ruby, it turns out, effectively has functions. Unfortunately, they’re implemented in the most complicated, unintuitive way. I know, right? Ruby, unintuitive, the blasphemy.</p><p>Let’s look at a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a62997de24e1d24846813bfb58f492e/href">https://medium.com/media/3a62997de24e1d24846813bfb58f492e/href</a></iframe><p>Wait, what? Hold on, I could’ve sworn I’ve seen…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc0cee1acfad458539ea7efbd4fff530/href">https://medium.com/media/fc0cee1acfad458539ea7efbd4fff530/href</a></iframe><p>Ok, there we go. But it’s a <em>private</em> method. <strong>String</strong> <em>is-a</em> <strong>Object</strong>, and the method <strong>puts</strong> is defined on <strong>Object</strong>. It would be so natural to write this as <strong>”howdy”.puts</strong>. But we don’t.</p><p>Why?</p><p>Let’s look closer. We know we can invoke private methods, so let’s try that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b053f282e920b554dc4f18882d06910a/href">https://medium.com/media/b053f282e920b554dc4f18882d06910a/href</a></iframe><p>Huh, it worked, sort of. It didn’t raise an exception, anyway. But it sure didn’t print the text that I was expecting.</p><p>If you consider that example for a moment, you’ll notice that <strong>”hello”.puts</strong> and <strong>puts “hello”</strong> are very similar, yet fundamentally different.</p><p>In <strong>puts “hello”</strong>, the <em>receiver</em> is irrelevant and ignored. Even when I explicitly sent <strong>puts</strong> to the String <strong>”howdy”</strong>, the “method” ignored it. Turns out, <strong>puts</strong> only operates on its arguments; the receiver is completely irrelevant.</p><p>Now wait, where have I seen something like this before? Oh yeah, <strong><em>functions</em></strong>! In <em>y = f(a)</em>, there is no such thing as a <em>receiver</em>.</p><p>So, yes, Ruby has functions, and we use them naturally in code without batting an eye. In fact, Ruby has a peculiar, <strong>module_function</strong>, method to help define them!</p><p>We see that Ruby effectively has functions. We use them like functions in Ruby code. We even have <strong>module_function</strong> for designating them. But, underneath they are just like private methods that ignore their receiver. Kinda weird, but ok, it works.</p><p>It works, except it’s a mess, like sweeping some dirt under the rug. You don’t see it but it’s there, diminishing the elegance and making everything a little less sanitary. What if we…</p><p>Hold on. Before we wax philosophical about what might be, let’s push a little harder on this objects versus functions thing.</p><p><em>Why do we have objects?</em> Why create programming languages where this concept is a central organizing principle. Why is “everything an object” in Ruby considered a strength, something that contributes to Ruby’s <em>elegance</em>?</p><p>If you listen to some arguments, objects are apparently total, <em>ad hoc</em>, confused bullshit and we all should be using just functions, Monads and types like grown-ups, thank you very much, show yourself out.</p><p>On the other hand, there are other quite accomplished people, like <a href="https://en.wikipedia.org/wiki/Alan_Kay">Alan Kay</a>, <a href="http://bracha.org/Site/Home.html">Gilad Bracha</a>, <a href="https://www.cs.cmu.edu/~./aldrich/">Jonathan Aldrich</a>, and <a href="https://www.destroyallsoftware.com/screencasts">Gary Bernhardt</a> who suggest (even if they equivocate at times) that there is something essential to this objects thing.</p><p>I want to focus on two works here (but feel free to read anything ever written by Alan Kay and professor Bracha in your free time).</p><ol><li><a href="https://www.cs.cmu.edu/~aldrich/papers/objects-essay.pdf">The Power of Interoperability: Why Objects Are Inevitable</a></li><li><a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">Functional Core, Imperative Shell</a></li></ol><p>If reading isn’t your thing, ignore the first paper and watch Gary’s screencast. Better, read the paper <em>and</em> watch Gary’s screencast. Or just read the paper. Basically, do <em>anything</em> beyond just listening to people who say objects are bullshit and we need types or Ruby is ruined… sorry, almost started ranting there.</p><p>Ok, back to our question, why objects (and whence functions)?</p><p>I’ll offer a simple rule: <strong><em>Objects are for interactions; functions are for data</em></strong>.</p><p>What does this mean in software terms?</p><p>Fundamentally, interactions presume at least two entities. Two or more separate things “have an effect on each other”. What happens when the rates of change of those things differ?</p><p>Let’s illustrate the question with the example of a car’s internal-combustion engine and wheels. The engine and wheels move at different rates of speed (i.e. the rate of change of position). To allow these systems to <em>interact</em>, a car needs a transmission, a component that mediates the different rates of change of the engine and the wheels, even allowing one to move in the opposite direction of the other.</p><p>In this example, the engine and wheels have very limited interaction, via the transmission. Changing the oil in the engine doesn’t affect the tires, and changing the tires doesn’t impact the engine.</p><p>This principle of minimizing the surface area between two interacting components is the essence of the concept of objects in software. We build more robust systems by carefully <em>limiting</em> the scope of interaction to a small set of well-defined activities (via an API or protocol).</p><p>Now, what about functions? Consider functions in math: one key idea is whether the function is defined for a particular element of a set. For example, for the function <em>f(x) = x²</em>, we know that <em>f</em> is defined for any real number <em>x</em>. Check out <a href="http://www.wolframalpha.com/input/?i=f(x)+%3D+x%5E2">a nice plot of this</a>.</p><p>But what about a function like <em>f(x) = 1/x</em>? Check out <a href="http://www.wolframalpha.com/input/?i=f(x)+%3D+1%2Fx">the plot</a>. There’s that part of the graph at <em>x = 0 </em>that doesn’t show up. This shouldn’t be too surprising because at <em>x = 0</em>, the function value <em>y = 1/0</em> would be undefined. When a function is not defined for every element of the input set, it’s called <a href="https://en.wikipedia.org/wiki/Partial_function">a partial function</a>.</p><p>Partial functions are messy. Where the function is undefined, it’s like asking me a question and getting a blank stare in return. If you want to analyze some data by computing a function of that data, you don’t want gaps. You want a total function. You want an answer for every piece of data.</p><p>Here’s what we have so far: objects are more robust by <em>limiting</em> their interactions, and functions are more robust by being <em>unlimited</em> (i.e. defined everywhere for the input set). How do we resolve this apparent conflict?</p><p>We don’t. These forces <em>are</em> in conflict. They are both legitimate and competing, and one <em>shouldn’t </em>win. What we want is to balance them <em>in a particular context</em>. But to do that, wouldn’t we need to put objects and functions on equal footing? You betcha.</p><p>Let’s reiterate that last point, just to be sure we’re on the same page:</p><ol><li><em>When my app is talking to a remote API, for example, I want to limit that interaction as much as possible.</em> I want to get in, get my JSON, and get out while touching as little as possible of that other system. And the other system <em>really</em> doesn’t want to care about details in my app. It likely has thousands or tens of thousands of different apps to interact with. Knowing even a tiny bit about any of those would be extremely costly.</li><li><em>When I’m processing the bytes of that JSON blob I got back, I absolutely want a total function.</em> I don’t want to misunderstand a single byte. And I never should. Bytes are well defined, unambiguous, and I should expect a total function to process them. I don’t need to “interoperate” with bytes.</li></ol><p>One thing the astute reader may notice is that <em>data, functions, and types</em> go together extremely well. They are an exquisite combination. They are precise and rigorous and oh-so neat and tidy. Perfect.</p><p>And this is where the world goes to hell in a hand basket.</p><p>Someone comes along and puts types on objects. Not just any old types, but static types. It’s like oil and vinegar. They don’t mix, period. Undeterred, this brave soul just shakes it up real, <em>real</em> good, and us poor mortals end up with <strong>WidgetFactoryFactoryFactory</strong> things and lots of tears and suffering.</p><p>You think I’m kidding. I wish.</p><p>What to do? Ah yes, <em>objects are for interaction, functions are for data</em>.</p><p>We need objects to support modularity and interaction between components, <em>especially</em> when dealing with <a href="https://gbracha.blogspot.com/2011/01/maybe-monads-might-not-matter.html">the messy, stateful world of missiles and services APIs</a>. And we need functions to have well-defined semantics when operating on data, like money and bytes and lists of addresses. The two go together like peanut butter and jelly. Where have I heard this before? Oh yeah, <a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">Functional Core, Imperative Shell</a>.</p><p>I’m not making this stuff up, folks. The world’s messy; I’m just trying to deal with it.</p><p>And that brings us back to where we started: the idea of functions in Ruby. What does it mean when I say <em>Rubinius takes the fun out of Ruby</em>?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1971db15859d67e438c8eed86bcf6240/href">https://medium.com/media/1971db15859d67e438c8eed86bcf6240/href</a></iframe><p>Uh, what?!</p><p>Yep, that’s it, no more <strong>fun</strong> in Ruby; it’s a syntax error. All those happy programmers bursting into tears…</p><p>Ok, it’s not all bad. There’s another side of this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e75366472665eb50ea18872faa4cf63a/href">https://medium.com/media/e75366472665eb50ea18872faa4cf63a/href</a></iframe><p>You’ll have to excuse the syntax highlighting. It’s behind the times. But your eyes are not fooling you. That’s really a thing that looks exactly like a method but defined with <strong>fun</strong> instead.</p><p>Totally not pulling your leg.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aed7712c0fc0b5e2c9407b52e714129/href">https://medium.com/media/8aed7712c0fc0b5e2c9407b52e714129/href</a></iframe><p>The output is a bit odd. It’s the compiler saying it got a request to compile a function, but that part isn’t done yet, so it’s just a confirmation that, “yep, this here thing is a function”.</p><p>Pretty cool, right? Wait, there’s more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e11563afac9187db1efab0aebbd1752/href">https://medium.com/media/0e11563afac9187db1efab0aebbd1752/href</a></iframe><p>You’re probably way ahead of me here, but yes, <strong>defm</strong> enables defining a <em>new</em> method with the same name but different <em>arity</em> that joins, rather than replaces, the existing method. And <strong>funm</strong> is similar, but for functions instead of methods. Which method or function is invoked depends on the code calling the method or function.</p><p>You may be wondering, why does Ruby need <strong>defm</strong>? Excellent question. Let’s explore that using <strong>Array#[]</strong> as an example. In a more perfect world, Ruby would have this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7019ccd2b4b7faf14751594c317c7676/href">https://medium.com/media/7019ccd2b4b7faf14751594c317c7676/href</a></iframe><p>The Ruby core library tends to keep method names concise by overloading the meaning of the method based on the arguments passed. This can support very clear code, where the nature of the data (arguments) is an implementation detail. I love this aspect of Ruby.</p><p>In contrast, Rails would probably define this with long, explicit names:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9544267459ad1996e6ed5d890b8daaa6/href">https://medium.com/media/9544267459ad1996e6ed5d890b8daaa6/href</a></iframe><p>I’m not bagging on Rails, and maybe they wouldn’t define it this way, but I want to make the contrast clear. Using a simple name and overloading the meaning based on the arguments can make code more robust. The code says, “I want a part of this Array” (the meaning of the code), and the arguments specify the implementation detail based on what data is flowing through that code. Really nice.</p><p>In contrast, the explicit method name approach couples those two. The name of the method limits the meaning of the code to the implementation detail. Not so nice.</p><p>The problem with simple names and overloading the meaning based on the arguments is that the method bodies become a huge mess of conditional code and utility functions. Don’t believe me? Go read the Ruby C code.</p><p>The solution to this problem isn’t to hide the mess. Rather, give the programmer the ability to <em>both</em> support concise method names that capture meaning <em>and</em> implement the “method meaning” with clear code.</p><p>That’s what <strong>defm</strong> enables.</p><p>It’s not all roses, though. Earlier I said that data, functions, and types are an excellent combination. That’s true. But making it true in Ruby isn’t easy.</p><p>Ideally, we’d be able to define data types much like we define classes or modules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a268a1bb0e04737ce51935f8a95d95a8/href">https://medium.com/media/a268a1bb0e04737ce51935f8a95d95a8/href</a></iframe><p>Ideally, sure. In reality, no. A quick search on <a href="https://github.com/">GitHub</a> shows tens of thousands of uses of <strong>data</strong> and <strong>data_type</strong> in Ruby code (so much for everything’s an object, eh?). Despite this data construct looking and working extremely well, if we introduced <strong>data</strong> as a keyword, effectively taking both <strong>fun</strong> <em>and</em> <strong>data</strong> out of Ruby, there’d surely be widespread revolt. So data must remain a 2nd-class concept in Ruby (for now).</p><p>Another concern is types. Types with functions are really great and I support them 100%, <em>as an option</em>. On the other hand, I’ll go on record saying that <strong><em>any attempt to add static types, or even gradual typing, to Ruby objects will be an unmitigated disaster</em></strong>. More importantly, it’s completely unnecessary with proper support for functions.</p><p>But what about my <strong>defm</strong> for <strong>Array</strong> example above? Didn’t I essentially use some type annotations there? Sort of.</p><p>This syntax compiles fine in regular Ruby today:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dcb806450b84be2aa041d5bc0ebebc7/href">https://medium.com/media/0dcb806450b84be2aa041d5bc0ebebc7/href</a></iframe><p>But it wouldn’t actually run (that <strong>defm</strong> feature for the <strong>Integer</strong> function would be handy here):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b997a4eb2567fd064d02ac122097f25/href">https://medium.com/media/6b997a4eb2567fd064d02ac122097f25/href</a></iframe><p>However, it wouldn’t be hard to make it work. Let’s expand on the syntax a bit to be sure the ideas are clear:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b2918d701d6a50e0618a81c43437046/href">https://medium.com/media/1b2918d701d6a50e0618a81c43437046/href</a></iframe><p>By considering these more as “behaviors” than as “types”, the coercion semantics are reasonably simple. A method may take an argument that <em>is-a</em> <strong>Integer</strong> or can be coerced to an <strong>Integer</strong>. The meaning of the code is explicit, and the existing dynamic typing is unaffected. In my mind, this is still uncomfortably close to adding types to objects, but it doesn’t work against the purpose of objects.</p><p>For functions, on the other hand, this same syntax can be used, and could even be checked “statically” for appropriate function definitions. Probably more useful, though, would be to define a set of data types that do not intersect the Ruby class/module space, and preserve this syntax for defining arguments that would be objects. To elaborate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4acefbf9943423052fcc2e2a72ac941/href">https://medium.com/media/a4acefbf9943423052fcc2e2a72ac941/href</a></iframe><p>Aside from that pesky <strong>do</strong> syntax to work around not having a first class data type in Ruby, the code is reasonably natural and clear.</p><p>One final complication remains: where do these functions go? On the lexical scope object, naturally.</p><p>Just like you cannot directly access a block in Ruby, you cannot access a lexical scope either, but it exists and is involved any time you look up a constant. In Rubinius, the lexical scope is just another, you guessed it, Ruby object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5d52a06ef669744a39801df44d03ce/href">https://medium.com/media/2a5d52a06ef669744a39801df44d03ce/href</a></iframe><p>In Rubinius, functions are defined on lexical scope and ambiguous method invocations (e.g. <strong>puts “hello”</strong>) are resolved by checking the lexical scope first in cases where the function definition is not visible at compile time. When the compiler <em>can</em> see the function definition, it can emit a static call to the function.</p><p>This feature is especially useful for implementing the Ruby core library in Rubinius. There is no way to manipulate the lexical scope from Ruby. Hence, no Ruby code can change predictions that the compiler makes related to the lexical scope. These features make functions perfectly suited for the following tasks:</p><ol><li><strong>Field access</strong>. In Rubinius, core classes are written in Ruby and use “instance variables” for state, as one would expect of Ruby code. Unfortunately, Ruby programmers are accustomed to arbitrarily mucking with core classes by incompatibly redefining methods, removing methods, or adding their own instance variables. By using functions to access the fields (like instance variables but slightly different), external code cannot break Ruby core classes.</li><li><strong>Math</strong>. Despite tremendous effort in Rubinius, there is a vanishingly small chance Ruby will ever be well specified. Things like the (now deprecated) <strong>mathn</strong> library arbitrarily redefine things like <strong>Fixnum</strong> division, without regard for code that depends on well-defined <strong>Fixnum</strong> division. Of the myriad places that “math” is used in the core library, in Ruby it is just C math, not Ruby math. So mucking with <strong>Fixnum</strong> is inconsequential in Ruby. But in Rubinius, mucking with <strong>Fixnum</strong> extensively breaks core classes. By defining math via functions, Rubinius can more robustly implement the Ruby core library.</li><li><strong>Bytes</strong>. As mentioned earlier, bytes are well-defined. They are also extensively used. The flexibility of Ruby’s dynamic types are completely unnecessary for working with bytes, and the cost is prohibitive. In Rubinius, essential <strong>String</strong> operations can be implemented as functions, allowing for many optimizations while insulating them from arbitrary Ruby level modification in the same manner as math above.</li><li><strong>Object coercions</strong>. Ruby has well-known coercions, like <strong>to_str</strong>, but unfortunately, they are not well-defined and many (or most) of them exist as numerous C utility functions in Ruby.</li><li><strong>Utility functions</strong>. The object coercions are an instance of the more general category of utility functions for operations like formatting an object’s data a certain way for <strong>inspect</strong> or JSON or various other manipulations.</li></ol><p>Lest you think I whimsically happened across the idea of proper support for functions in Ruby, it was the venerable <a href="http://yehudakatz.com/">Yehuda Katz</a> who suggested them to me in late 2013 as a much more elegant way to address the concerns that spawned the abominable Ruby refinements. He was right (he usually is), but it took me several months to see just how elegantly functions fit in Ruby.</p><p>But this shouldn’t be surprising. The tension between the opposed forces of completeness on the one hand and minimizing exposure to uncontrollable change on the other requires a <em>balance</em> that is not achieved by lopsided “everything is an object” approaches.</p><p>Even worse than “everything is an object” is the attempt to mash together things like objects and types, whose fundamental natures are in opposition. Truly elegant solutions depend on proportion and collaboration between concepts like objects and functions that are fully, unapologetically themselves.</p><p>But wait, there’s more (there’s <em>always</em> more).</p><p>It’s fairly well known that every Rails application contains a poorly-specified, buggy, slow implementation of most of the <em>Fibonacci</em> function, which explains the prevalence of benchmarks comparing <strong>fib()</strong> performance. Given that, consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f07511354d3b636ad58ef5392b5d2b66/href">https://medium.com/media/f07511354d3b636ad58ef5392b5d2b66/href</a></iframe><p>Notice that despite looking like quite natural Ruby code, there’s nothing here that depends on anything in the Ruby core library. Code like this in a script should compile to a simple, stand-alone executable.</p><p>Perhaps not exactly <strong>fib()</strong>, but at least code like this should cover a fair number of scripting tasks. And generalizing from this to code that does rely on Ruby core classes or more elaborate Ruby code is possible, given the facilities Rubinius has built to manage information about running code. The possibilities are exciting.</p><p>Ok, wrapping up, here’s what we’ve covered: <em>objects are for interactions; functions are for data</em>. Rubinius adds first-class support for functions, legitimizing the half-hearted, fake functions that Ruby already has. This enables powerful extensions to existing code for dealing with performance and architectural issues that have been extremely difficult for Ruby.</p><p>Now, let’s step back and view the big picture. Ruby is a reasonably good language for a lot of tasks and a lot of people enjoy using it. Just as true, Ruby has a lot of limitations. After 8 years trying to convince Ruby to adopt a reasonably meaningful specification, and almost 10 years implementing 5 or so major versions of Ruby, I have no illusions about Ruby’s problems.</p><p>Yet with very little effort, as shown here, Ruby could be substantially better by no longer ignoring the half of the world that is not about interactions. By recognizing that <em>functions are for data</em> and welcoming those functions on equal footing with Ruby’s mostly excellent support for <em>object interactions</em>, we can protect and extend the enormous investment that’s been made in Ruby software and Ruby programmers.</p><p>Ultimately, the goal of Rubinius is to support Ruby as one of a multitude of languages that are well-suited to solve particular problems. The support for functions described here will find expression in other languages, and those may end up being just as simple for a Rails application to interoperate with when running on Rubinius as these additions to Ruby are.</p><p>That will be great; more options usually are a good thing. But there is no shorter path to utility than making these features work today. They are familiar and natural to Ruby programmers, and they are natural and seamless with existing Ruby code. If these features sound valuable to your application or business, <a href="/service/mailto:contact@rubinius.com?subject=I%E2%80%99d%20like%20to%20discuss%20Rubinius%20support%20for%20functions">start a conversation</a> or <a href="http://rubinius.com/contribute/">get involved</a> today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936e044cc729" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metalanguage/objects-are-for-interactions-functions-are-for-data-936e044cc729">Objects are for interactions, functions are for data</a> was originally published in <a href="https://medium.com/metalanguage">Meta Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>