Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Guys - it seems there's a need for polymorphism here that just can't be solved by fiddling with the flow control within one method.</p> <p>Here's my attempt starting with the expanded out version:</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) (controller == 'foos' &amp;&amp; item.widgets.blank?) || (controller == 'foos' &amp;&amp; item.doohickeys.blank?) || (controller == 'bars' &amp;&amp; item.widgets.blank?) || (controller == 'bars' &amp;&amp; item.doohickeys.blank?) || (controller == 'bazes' &amp;&amp; item.widgets.blank?) || (controller == 'bazes' &amp;&amp; item.contraptions.blank?) end </code></pre> <p>So there are <strong>three different behaviours - one per controller</strong>.... If each controller was smart enough to contain controller-specific decision making, and you pass in the actual controller not just a name of a controller you reduce the method to this:</p> <pre><code>def has_just_one_kind_of_thing?(item, controller) controller.has_just_one_kind_of_thing?(item) end </code></pre> <p>This requires each controller to do the relevant item handling for the kind of controller it is. So let's define a method on each of foos, bars and bazes, called <code>has_just_one_kind_of_thing?</code></p> <p>Example for foos:</p> <pre><code>def has_just_one_kind_of_thing?(item) item.widgets.blank? || item.doohickeys.blank? end </code></pre> <p>Example for bazes:</p> <pre><code>def has_just_one_kind_of_thing?(item) item.widgets.blank? || item.contraptions.blank? end </code></pre> <p>On every controller that you want to return <code>false</code> on, just apply the "constant method" pattern:</p> <pre><code>def has_just_one_kind_of_thing?(item) false end </code></pre> <p>This code will even run faster because now, we don't have to make as many checks as there are types of controllers - we just do one method dispatch against the controller. </p> <p>So <strong>it's faster in interpreted ruby</strong> - and it <strong>might even go a lot faster in jruby</strong> or one of the other rubies that can heavily optimise method dispatching...</p> <p>We could probably make it even smarter but I'd need to know on which class this method lives and maybe a few other things about <code>item</code>. </p> <p>The alternative refactoring would have been to make <code>item</code> smart and have different methods on each type of <code>item</code>. Again, we'd need to know more about the object model to tell which is best...</p> <p>Still it's a first cut.</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