Use of special characters in function names

Justin Ethier picture Justin Ethier · Oct 21, 2009 · Viewed 13.8k times · Source

In Ruby, a standard convention is to use a question mark at the end of a method name to indicate the method returns a boolean result:

[].empty?   #=> true 

Another standard convention is to end a method name with an exclamation point if the method is destructive (that is, it modifies the original data):

mylist.sort! # sort mylist in-place

Recently I have seen these same conventions used in Scheme. Which makes me wonder, what other languages use/support this convention? Are there any other special characters that are commonly used for naming by these or other languages?

Answer

user166390 picture user166390 · Oct 21, 2009

The answer is, of course, language (and language culture) specific.

For example, depending on the language, all of the following are appropriate: empty-p, empty?, empty, is_empty or isEmpty. (These examples are, of course, not inclusive).

The examples in the original question come from Ruby where such use of ? and ! to end method names are, where appropriate, accepted. This acceptance comes from 1) readily accessible as symbol terminators in the grammar 2) use of ? and ! in the standard library. However, it should be note that ! is not used universally to imply "side-effect" and is generally only present on alternative forms: save/save!, sort/sort!, etc. There are an overwhelming number of methods that perform side-effects which do not have the ! prefix.

Personally, if I was designing a language, I would allow ?, ! and ' to be valid unquoted trailing characters in symbol names. Even though that some languages allow full symbol escaping, such as Scala, such symbols are usually avoided because it's a pain to have to quote them for use.

// in Scala, esp. with Java-compat, the last form is generally used although
// the first two are perfectly valid -- do what makes sense in the language
foo.`empty?`
foo.empty_?
foo.isEmpty

When in Rome...

  • Scala - empty? or empty_? (not common)
  • C/C++/JS/Java/Python/Perl - no ? or ! in identifiers; JS/Java allow $; $ is a sigil in Perl
  • C/C++/Perl/JS - hands up in the air?
  • C# - IsEmpty (method or property) or Empty (property)
  • Python - is_empty or isEmpty per Guido-guide (although usually len protocol: if not len(foo): "empty!")
  • Java - isEmpty per Language Guide
  • Ruby - special trailing ? and ! (quoting?)
  • JS - indirect identifier access: obj["empty?"] (not common for this)
  • Lisp (conventional): empty-p for predicate; variations in reader/quoting
  • Julia - appends ! to functions that modify their arguments

Glad to see corrections and/or additions -- is only a drop in a bucket.