<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Clojure Q&amp;A - Recent questions tagged empty?</title>
<link>https://ask.clojure.org/index.php/tag/empty%3F</link>
<description></description>
<item>
<title>Should I prefer nil to empty collections?</title>
<link>https://ask.clojure.org/index.php/8415/should-i-prefer-nil-to-empty-collections</link>
<description>&lt;p&gt;This is a question about intersection of 3 different clojure aspects:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Collection functions treat &lt;code&gt;nil&lt;/code&gt; as empty collection. Functions like &lt;code&gt;filter&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt;, and even &lt;code&gt;assoc&lt;/code&gt; happily accept &lt;code&gt;nil&lt;/code&gt; for coll.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;if&lt;/code&gt; and derived macros (&lt;code&gt;when&lt;/code&gt;, &lt;code&gt;and&lt;/code&gt;, &lt;code&gt;or&lt;/code&gt; etc.) treat &lt;code&gt;nil&lt;/code&gt; as falsey value.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;empty?&lt;/code&gt; coerces it's input to &lt;code&gt;seq&lt;/code&gt;, which leads to unnecessary allocations, and it's idiomatic to check for not-emptyness using &lt;code&gt;seq&lt;/code&gt; instead of &lt;code&gt;(not (empty? xs))&lt;/code&gt;. This is a common source of confusion, because &lt;code&gt;(not (empty? xs))&lt;/code&gt;'s intent feels more clear then &lt;code&gt;seq&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With that said, I feel like consciously representing every empty collection in application as &lt;code&gt;nil&lt;/code&gt; might be useful, because this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(let [xs (get-non-empty-coll-or-nil)]
  (if xs
    (do-stuff-with xs)
    (do-nothing)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;  ...is more performant and clear than this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(let [xs (get-possibly-empty-coll)]
  (if (seq xs)
    (do-stuff-with xs)
    (do-nothing)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Two downsides I see to this approach:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;having to use &lt;code&gt;(fnil conj [])&lt;/code&gt; or &lt;code&gt;(fnil conj #{})&lt;/code&gt; instead of &lt;code&gt;conj&lt;/code&gt; to ensure collections are vectors/sets, because &lt;code&gt;conj&lt;/code&gt;-ing to &lt;code&gt;nil&lt;/code&gt; creates a list, which I personally almost never use.&lt;/li&gt;
&lt;li&gt;having to run all incoming collections on the boundaries of a system through &lt;code&gt;not-empty&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;What do you think?&lt;/p&gt;
</description>
<category>Collections</category>
<guid isPermaLink="true">https://ask.clojure.org/index.php/8415/should-i-prefer-nil-to-empty-collections</guid>
<pubDate>Wed, 14 Aug 2019 09:12:35 +0000</pubDate>
</item>
</channel>
</rss>