DEV Community

Cover image for Clojure 101 / ! and ?
icncsx
icncsx

Posted on

Clojure 101 / ! and ?

One thing I really liked about working with Ruby was the fact that core methods sometimes had a ! or a ? in the end. The bang methods in Ruby, by convention, indicate that the method mutates the object. Methods that end with a question mark (boolean methods), also by convention, return a boolean.

I found both conventions to be super helpful in terms of readability. For example, a boolean method such as empty? reads like a question: "Hey is this thing empty?" Without a question mark, it could be confusing. Am I declaring that something is empty or asking if something is empty?

The bang operators in methods such as downcase! and filter! also help readability. You want those methods to run so forcefully that you want their effects to be permanent (mutating).

All of this is to say that I was pleasantly surprised that Clojure also adopted a similar naming convention.

(contains? #{ :jets :eagles } :jets)
;; does the set contain :jets?

(even? 4)
;; is 4 even?

(empty? [100 400])
;; is [100 400] empty?
Enter fullscreen mode Exit fullscreen mode
(def player (atom {:score 0
                   :name "Charlie"}))
(swap! player update :score + 5)
;; increase player's score by 5
Enter fullscreen mode Exit fullscreen mode

As you can see, the function names in Clojure are just as nice as those of Ruby's. The addition of ? and ! is the cherry on top. Speaking of cherry, I need to finish that Cherry Coke I had opened two hours ago...

Warmly,
DH

Top comments (2)

Collapse
 
itsjzt profile image
Saurabh Sharma • Edited

AFAIK ruby got ? From lisp

Collapse
 
icncsx profile image
icncsx

That makes sense! I love it when the best ideas get marinated together.