How to refactor to avoid passing "special values" into a Java method?
<p>I'm sure there must be a standard way to do this, but my attempts to search Stackoverflow have failed. </p>

<p>I have a method like:</p>

<pre><code>public void processSomeWidgetsForUser(int userItemId) {
    Iterator&lt;Widgets&gt; iter = allWidgets.values().iterator();
    while(iter.hasNext()) {
        Widget thisWidget = iter.next();
        if (userItemId == -1 || thisWidget.getUsersItemId() == userItemId) {                 
             widget.process();
        }
    }
}
</code></pre>

<p>As you can see -1 is a "special value" meaning process all. Doing this saves repeating the loop code in another method called processSomeWidgetsForAllUsers. </p>

<p>But I dislike special values like this because they are easy to misuse or misunderstand, which is exactly the situation what I'm having to fix now (where someone thought -1 meant something else).</p>

<p>I can only think of two ways to improve this.</p>

<ol>
<li>have a constant, containing -1 called something like
Widget.ALLWIDGETS which at least is self-documenting, but doesn't
stop code from using a -1 (if someone integrates old code in, for
example) </li>
<li>change the method to take a list of all user ids to
process, which can be empty, but that doesn't seem great
performance-wise (would need to retrieve all user ids first and then loop through 
removing. Also what happens if the number of widgets in the list changes between 
retreiving the ids and removing</li>
</ol>

<p>Is there a better way? I'm sure I'm missing something obvious.</p>

<p>The above code has been changed slightly, so may not compile, but you should get the gist.</p>
