Skip to content

Commit

Permalink
Add 50: "Naming Too Good"
Browse files Browse the repository at this point in the history
  • Loading branch information
janlelis committed May 19, 2016
1 parent d0cbb26 commit 327e6ed
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions source/categories/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ title: Idiosyncratic Ruby - Browse by Category
<li><a href="/38-sad-methods.html">Reflecting on Native Methods</a></li>
<li><a href="/43-new-ruby-startup.html">Ruby's Initial State</a></li>
<li><a href="/45-constant-shuffle">Constant Re-Assignment</a></li>
<li><a href="/50-naming-too-good.html">Identifiers to Avoid</a>/<li>
</ul>

<h2>Miscellaneous</h2>
Expand Down
61 changes: 61 additions & 0 deletions source/posts/50-naming-too-good.html.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
---
title: Naming Too Good
date: 2016-05-19
tags: core, api
---

Some words should not be chosen as identifiers for variables, parameters and methods in Ruby, because they clash with core methods or keywords.

ARTICLE

As long as you do not define a method with the name of a keyword, Ruby will not complain. Still, it is often better to avoid naming things like existing methods. It carries potential for future bugs and also confuses newcomers. You might change the name in the future, but miss some occurences, which will then do something completely different. It also [makes debugging harder](https://tenderlovemaking.com/2016/02/05/i-am-a-puts-debuggerer.html#what-if-the-thing-implements-the-method-method).

A simple workaround is to append an `_` to critical identifiers. Some variables names that I find myself wanting to choose sometimes, but which should not (or cannot) be used:

## `class`

`class` is a keyword so this is invalid code:

class = Thread

When referencing classes in your code the most common convention is to use `klass` instead.

## `in`

An example where this rarely used keyword (which is part of the `for` loop syntax) prevents good naming is working with streams:

require 'open3'
Open3.popen3(cmd){ |in, out, err|
# ...
}

## `method`

A common pattern:

def send_somewhere(method, something)
# ...
public_send(method)
# ...
end

Conflicts with: [Object#method](http://ruby-doc.org/core-2.3.0/Object.html#method-i-method)

## `hash`

Calculating a hash:

require "digest/sha2"
hash = Digest::SHA256.hexdigest "ö"

Conflicts with: [Object#hash](http://ruby-doc.org/core-2.3.0/Object.html#method-i-hash)

## `format`

"format" is a typical name for a keyword argument:

def something(format: "json")
# ...
end

I still do it sometimes, but it conflicts with: [Kernel#format](http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-format)

0 comments on commit 327e6ed

Please sign in to comment.