Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For a little more comprehensive solution, you could check out the <a href="http://Refactoring.Com/catalog/introduceNullObject.html" rel="nofollow noreferrer"><em>Introduce Null Object</em> Refactoring</a>. The basic mechanics of this refactoring is that instead of checking for <code>nil</code> in the <em>client</em> code you instead make sure that the <em>provider</em> never produces a <code>nil</code> in the first place, by introducing a context-specific <em>null object</em> and returning that.</p> <p>So, return an empty string, an empty array, an empty hash or a special empty customer or empty user or something instead of just <code>nil</code> and then you will never need to check for <code>nil</code> in the first place.</p> <p>So, in your case you would have something like</p> <pre><code>class NullUser &lt; User def name return '' end end </code></pre> <p>However, in Ruby there is actually another, quite elegant, way of implementing the Introduce Null Object Refactoring: you don't actually need to <em>introduce</em> a Null Object, because <code>nil</code> is <em>already</em> an object! So, you could monkey-patch <code>nil</code> to behave as a NullUser – however, all the usual warnings and pitfalls regarding monkey-patching apply even more strongly in this case, since making <code>nil</code> silently swallow <code>NoMethodError</code>s or something like that can totally mess up your debugging experience and make it <em>really</em> hard to track down cases where there is a <code>nil</code> that shouldn't be there (as opposed to a <code>nil</code> that serves as a Null Object).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload