<p>When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:</p>

<pre><code>1. needle.find(haystack)

2. haystack.find(needle)

3. searcher.find(needle, haystack)</code></pre>

<p>Which do you prefer, and why?</p>

<p>I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".</p>

<p>In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?</p>

[{'answer_id': 23756, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 3, 'selected': False, 'text': '<p>This entirely depends on what varies and what stays the same.</p>\n\n<p>For example, I am working on a (non-OOP) <a href="http://www.seqan.de/" rel="noreferrer">framework</a> where the find algorithm is different depending both on the type of the needle and the haystack. Apart from the fact that this would require double-dispatch in an object-oriented environment, it also means that it isn\'t meaningful to write either <code>needle.find(haystack)</code> or to write <code>haystack.find(needle)</code>.</p>\n\n<p>On the other hand, your application could happily delegate finding to either of both classes, or stick with one algorithm altogether in which case the decision is arbitrary. In that case, I would prefer the <code>haystack.find(needle)</code> way because it seems more logical to apply the finding to the haystack.</p>\n'}, {'answer_id': 23758, 'author': 'Dan Herbert', 'author_id': 392, 'author_profile': 'https://Stackoverflow.com/users/392', 'pm_score': 1, 'selected': False, 'text': '<p>Personally, I like the second method. My reasoning is because the major APIs I have worked with use this approach, and I find it makes the most sense.</p>\n\n<p>If you have a list of things (haystack) you would search for (find()) the needle.</p>\n'}, {'answer_id': 23760, 'author': 'Tilendor', 'author_id': 1470, 'author_profile': 'https://Stackoverflow.com/users/1470', 'pm_score': 4, 'selected': False, 'text': "<p>I would say that option 1 is completely out.  The code should read in a way that tells you what it does.  Option 1 makes me think that this needle is going to go find me a haystack.</p>\n\n<p>Option 2 looks good if a haystack is meant to contain needles.  ListCollections are always going to contain ListItems, so doing collection.find(item) is natural and expressive.</p>\n\n<p>I think the introduction of a helper object is approproiate when:</p>\n\n<ol>\n<li>You don't control the implementation of the objects in question<br>\nIE: search.find(ObsecureOSObject, file)</li>\n<li>There isn't a regular or sensible relationship between the objects<br>\nIE: nameMatcher.find(houses,trees.name)</li>\n</ol>\n"}, {'answer_id': 23769, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 7, 'selected': True, 'text': '<p>Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate.</p>\n\n<p>You also have a fourth alternative that I think would be better than alternative 3:</p>\n\n<pre><code>haystack.find(needle, searcher)\n</code></pre>\n\n<p>In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on.</p>\n'}, {'answer_id': 23812, 'author': 'wilhelmtell', 'author_id': 456, 'author_profile': 'https://Stackoverflow.com/users/456', 'pm_score': 4, 'selected': False, 'text': '<p>There is another alternative, which is the approach utilized by the STL of C++:</p>\n\n<pre><code>find(haystack.begin(), haystack.end(), needle)\n</code></pre>\n\n<p>I think it\'s a great example of C++ shouting "in your face!" to OOP.  The idea is that OOP is not a silver bullet of any kind;  sometimes things are best described in terms of actions, sometimes in terms of objects, sometimes neither and sometimes both.</p>\n\n<p>Bjarne Stroustrup said in TC++PL that when you design a system you should strive to reflect reality under the constraints of effective and efficient code.  For me, this means you should never follow anything blindly.  Think about the things at hand (haystack, needle) and the context we\'re in (searching, that\'s what the expression is about).</p>\n\n<p>If the emphasis is about the searching, then using an algorithm (action) that emphasizes searching (i.e. is flexibly to fit haystacks, oceans, deserts, linked lists).  If the emphasis is about the haystack, encapsulate the find method inside the haystack object, and so on.</p>\n\n<p>That said, sometimes you\'re in doubt and have hard times making a choice.  In this case, be object oriented.  If you change your mind later, I think it is easier to extract an action from an object then to split an action to objects and classes.</p>\n\n<p>Follow these guidelines, and your code will be clearer and, well, more beautiful.</p>\n'}, {'answer_id': 23814, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 6, 'selected': False, 'text': '<p>Of the three, I prefer option #3.</p>\n\n<p>The <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">Single Responsibility Principle</a> makes me not want to put searching capabilities on my DTOs or models. Their responsibility is to be data, not to find themselves, nor should needles need to know about haystacks, nor haystacks know about needles.</p>\n\n<p>For what it\'s worth, I think it takes most OO practitioners a LONG time to understand why #3 is the best choice. I did OO for a decade, probably, before I really grokked it.</p>\n\n<p>@wilhelmtell, C++ is one of the very few languages with template specialization that make such a system actually work. For most languages, a general purpose "find" method would be a HORRIBLE idea.</p>\n'}, {'answer_id': 23818, 'author': 'Kevin Pang', 'author_id': 1574, 'author_profile': 'https://Stackoverflow.com/users/1574', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on your requirements.</p>\n\n<p>For instance, if you don\'t care about the searcher\'s properties (e.g. searcher strength, vision, etc.), then I would say haystack.find(needle) would be the cleanest solution.</p>\n\n<p>But, if you do care about the searcher\'s properties (or any other properties for that matter), I would inject an ISearcher interface into either the haystack constructor or the function to facilitate that.  This supports both object oriented design (a haystack has needles) and inversion of control / dependency injection (makes it easier to unit test the "find" function).</p>\n'}, {'answer_id': 23840, 'author': 'Peter Meyer', 'author_id': 1875, 'author_profile': 'https://Stackoverflow.com/users/1875', 'pm_score': 4, 'selected': False, 'text': "<p>I am with Brad on this one.  The more I work on immensely complex systems, the more I see the need to truly decouple objects.  He's right.  It's obvious that a needle shouldn't know anything about haystack, so 1 is definitely out.  But, a haystack should know nothing about a needle.  </p>\n\n<p>If I were modeling a haystack, I might implement it as a collection -- but as a collection of <em>hay</em> or <em>straw</em> -- not a collection of needles!  However, I would take into consideration that stuff does get lost in a haystack, but I know nothing about what exactly that stuff.  I think it's better to not make the haystack look for items in itself (how <em>smart</em> is a haystack anyway).  The right approach to me is to have the haystack present a collection of things that are in it, but are not straw or hay or whatever gives a haystack its essence.</p>\n\n<pre><code>class Haystack : ISearchableThingsOnAFarm {\n   ICollection&lt;Hay&gt; myHay;\n   ICollection&lt;IStuffSmallEnoughToBeLostInAHaystack&gt; stuffLostInMe;\n\n   public ICollection&lt;Hay&gt; Hay {\n      get {\n         return myHay;\n      }\n   }\n\n   public ICollection&lt;IStuffSmallEnoughToBeLostInAHayStack&gt; LostAndFound {\n      get {\n        return stuffLostInMe;\n      }\n   }\n}\n\nclass Needle : IStuffSmallEnoughToBeLostInAHaystack {\n}\n\nclass Farmer {\n  Search(Haystack haystack, \n                 IStuffSmallEnoughToBeLostInAHaystack itemToFind)\n}\n</code></pre>\n\n<p>There's actually more I was going to type and abstract into interfaces and then I realized how crazy I was getting.  Felt like I was in a CS class in college... :P</p>\n\n<p>You get the idea.  I think going as loosely coupled as possible is a good thing, but maybe I was getting a bit carried away!  :)</p>\n"}, {'answer_id': 23953, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 2, 'selected': False, 'text': '<p>To quote the great authors of <a href="https://rads.stackoverflow.com/amzn/click/com/0262011530" rel="nofollow noreferrer" rel="nofollow noreferrer">SICP</a>,</p>\n\n<p><em>Programs must be written for people to read, and only incidentally for machines to execute</em></p>\n\n<p>I prefer to have both methods 1 and 2 at hand. Using ruby as an example, it comes with <code>.include?</code> which is used like this</p>\n\n<pre><code>haystack.include? needle\n=&gt; returns true if the haystack includes the needle\n</code></pre>\n\n<p>Sometimes though, purely for readability reasons, I want to flip it round. Ruby doesn\'t come with an <code>in?</code> method, but it\'s a one-liner, so I often do this:</p>\n\n<pre><code>needle.in? haystack\n=&gt; exactly the same as above\n</code></pre>\n\n<p>If it\'s "more important" to emphasise the haystack, or the operation of searching, I prefer to write <code>include?</code>.\nOften though, neither the haystack or the search is really what you care about, just that the object is present - in this case I find <code>in?</code> better conveys the meaning of the program.</p>\n'}, {'answer_id': 23957, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n<p>@Peter Meyer</p>\n<p>You get the idea. I think going as loosely coupled as possible is a good thing, but maybe I was getting a bit carried away! :)</p>\n</blockquote>\n<p>Errr... yeah... I think the <code>IStuffSmallEnoughToBeLostInAHaystack</code> kind of is a red flag :-)</p>\n'}, {'answer_id': 25296, 'author': 'Anders Sandvig', 'author_id': 1709, 'author_profile': 'https://Stackoverflow.com/users/1709', 'pm_score': 1, 'selected': False, 'text': '<blockquote><p>You also have a fourth alternative that I think would be better than alternative 3:</p>\n<pre><code>haystack.find(needle, searcher)</code></pre>\n</blockquote>\n\n<p>I see your point, but what if <code>searcher</code> implements a searching interface that allows for searching other types of objects than haystacks, and finding other things than needles in them? </p>\n\n<p>The interface could also be implemented with different algorithms, for example:</p>\n\n<pre><code>binary_searcher.find(needle, haystack)\nvision_searcher.find(pitchfork, haystack)\nbrute_force_searcher.find(money, wallet)\n</code></pre>\n\n<p>But, as others have already pointed out, I also think this is only helpful if you actually have multiple search algorithms or multiple searchable or findable classes. If not, I agree <code>haystack.find(needle)</code> is better because of its simplicity, so I am willing to sacrifice some "correctness" for it.</p>\n'}, {'answer_id': 25337, 'author': 'Fredrik Kalseth', 'author_id': 1710, 'author_profile': 'https://Stackoverflow.com/users/1710', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>When implementing a needle search of a\n  haystack in an object-oriented way,\n  you essentially have three\n  alternatives:</p>\n  \n  <ol>\n  <li><p>needle.find(haystack)</p></li>\n  <li><p>haystack.find(needle)</p></li>\n  <li><p>searcher.find(needle, haystack)</p></li>\n  </ol>\n  \n  <p>Which do you prefer, and why?</p>\n</blockquote>\n\n<p>Correct me if I'm wrong, but in all three examples you already <em>have</em> a reference to the needle you're looking for, so isn't this kinda like looking for your glasses when they're sitting on your nose? :p</p>\n\n<p>Pun aside, I think it really depends on what you consider the responsibility of the haystack to be within the given domain. Do we just care about it in the sense of being a thing which contains needles (a collection, essentially)? Then haystack.find(needlePredicate) is fine. Otherwise, farmBoy.find(predicate, haystack) might be more appropriate.</p>\n"}, {'answer_id': 25428, 'author': 'Artur Carvalho', 'author_id': 1013, 'author_profile': 'https://Stackoverflow.com/users/1013', 'pm_score': 1, 'selected': False, 'text': '<pre><code>haystack.magnet().filter(needle);\n</code></pre>\n'}, {'answer_id': 33027, 'author': 'John Douthat', 'author_id': 2774, 'author_profile': 'https://Stackoverflow.com/users/2774', 'pm_score': 2, 'selected': False, 'text': '<p>Easy: Burn the haystack! Afterward, only the needle will remain. Also, you could try magnets.</p>\n\n<p>A harder question: How do you find one particular needle in a pool of needles?</p>\n\n<p>Answer: thread each one and attach the other end of each strand of thread to a sorted index (i.e. pointers)</p>\n'}, {'answer_id': 33056, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 1, 'selected': False, 'text': "<p>The haystack shouldn't know about the needle, and the needle shouldn't know about the haystack. The searcher needs to know about both, but whether or not the haystack should know how to search itself is the real point in contention.</p>\n\n<p>So I'd go with a mix of 2 and 3; the haystack should be able to tell someone else how to search it, and the searcher should be able to use that information to search the haystack.</p>\n"}, {'answer_id': 33156, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 1, 'selected': False, 'text': '<pre><code>class Haystack {//whatever\n };\nclass Needle {//whatever\n }:\nclass Searcher {\n   virtual void find() = 0;\n};\n\nclass HaystackSearcher::public Searcher {\npublic:\n   HaystackSearcher(Haystack, object)\n   virtual void find();\n};\n\nHaystack H;\nNeedle N;\nHaystackSearcher HS(H, N);\nHS.find();\n</code></pre>\n'}, {'answer_id': 33331, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': "<p>A mix of 2 and 3, really.</p>\n\n<p>Some haystacks don't have a specialized search strategy; an example of this is an array.  The only way to find something is to start at the beginning and test each item until you find the one you want.</p>\n\n<p>For this kind of thing, a free function is probably best (like C++).</p>\n\n<p>Some haystacks can have a specialized search strategy imposed on them. An array can be sorted, allowing you to use binary searching, for example.  A free function (or pair of free functions, e.g. sort and binary_search) is probably the best option.</p>\n\n<p>Some haystacks have an integrated search strategy as part of their implementation; associative containers (hashed or ordered sets and maps) all do, for instance. In this case, finding is probably an essential lookup method, so it should probably be a method, i.e. haystack.find(needle).</p>\n"}, {'answer_id': 37511, 'author': 'Binil Thomas', 'author_id': 3973, 'author_profile': 'https://Stackoverflow.com/users/3973', 'pm_score': 2, 'selected': False, 'text': '<p>I can think of situations where either of the first two flavours makes sense:</p>\n\n<ol>\n<li><p>If the needle needs pre-processing, like in the Knuth-Morris-Pratt algorithm, <code>needle.findIn(haystack)</code> (or <code>pattern.findIn(text)</code>)makes sense, because the needle object holds the intermediate tables created for the algorithm to work effectively</p></li>\n<li><p>If the haystack needs pre-processing, like say in a trie, the <code>haystack.find(needle)</code> (or <code>words.hasAWordWithPrefix(prefix)</code>) works better.</p></li>\n</ol>\n\n<p>In both the above cases, one of needle or haystack is aware of the search. Also, they both are aware of each other. If you want the needle and haystack not to be aware of each other or of the search, <code>searcher.find(needle, haystack)</code> would be appropriate.</p>\n'}, {'answer_id': 49082, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 1, 'selected': False, 'text': "<p>Is the code trying to find a specific needle or just any needle?  It sounds like a stupid question, but it changes the problem.</p>\n\n<p>Looking for a specific needle the code in the question makes sense.  Looking for any needle it would be more like</p>\n\n<pre><code>needle = haystack.findNeedle()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>needle = searcher.findNeedle(haystack)\n</code></pre>\n\n<p>Either way, I prefer having a searcher that class.  A haystack doesn't know how to search.  From a CS perspective it is just a data store with LOTS of crap that you don't want.  </p>\n"}, {'answer_id': 49133, 'author': 'jklp', 'author_id': 3847, 'author_profile': 'https://Stackoverflow.com/users/3847', 'pm_score': 3, 'selected': False, 'text': '<p>If both Needle and Haystack are DAOs, then options 1 and 2 are out of the question.</p>\n\n<p>The reason for this is that DAOs should only be responsible for holding properties of the real world objects they are modeling, and only have getter and setter methods (or just direct property access).  This makes serializing the DAOs to a file, or creating methods for a generic compare / generic copy easier to write, as the code wouldn\'t contain a whole bunch of "if" statements to skip these helper methods. </p>\n\n<p>This just leaves option 3, which most would agree to be correct behaviour. </p>\n\n<p>Option 3 has a few advantages, with the biggest advantage being unit testing.  This is because both Needle and Haystack objects can be easily mocked up now, whereas if option 1 or 2 were used, the internal state of either Needle or Haystack would have to be modified before a search could be performed.  </p>\n\n<p>Secondly, with the searcher now in a separate class, all search code can be held in one place, including common search code.  Whereas if the search code was put into the DAO, common search code would either be stored in a complicated class hierarchy, or with a Searcher Helper class anyway.  </p>\n'}, {'answer_id': 52336, 'author': 'Jimmy Chandra', 'author_id': 5321, 'author_profile': 'https://Stackoverflow.com/users/5321', 'pm_score': 1, 'selected': False, 'text': '<p>haystack can contain stuffs\none type of stuff is needle\nfinder is something that is responsible for searching of stuff\nfinder can accept a pile of stuffs as the source of where to find thing\nfinder can also accept a stuff description of thing that it need to find</p>\n\n<p>so, preferably, for a flexible solution you would do something like:\nIStuff interface</p>\n\n<p>Haystack = IList&lt;IStuff&gt;\nNeedle : IStuff</p>\n\n<p>Finder\n  .Find(IStuff stuffToLookFor, IList&lt;IStuff&gt; stuffsToLookIn)</p>\n\n<p>In this case, your solution will not get tied to just needle and haystack but it is usable for any type that implement the interface</p>\n\n<p>so if you want to find a Fish in the Ocean, you can.</p>\n\n<p>var results = Finder.Find(fish, ocean)</p>\n'}, {'answer_id': 60803, 'author': 'user6246', 'author_id': 6246, 'author_profile': 'https://Stackoverflow.com/users/6246', 'pm_score': 2, 'selected': False, 'text': "<p>The answer to this question should actually depend on the domain the solution is implemented for.<br>\nIf you happen to simulate a physical search in a physical haystack, you might have the classes </p>\n\n<ul>\n<li>Space  </li>\n<li>Straw  </li>\n<li>Needle</li>\n<li>Seeker</li>\n</ul>\n\n<p><strong>Space</strong><br>\nknows which objects are located at which coordinates<br>\nimplements the laws of nature (converts energy, detects collisions, etc.)  </p>\n\n<p><strong>Needle</strong>, <strong>Straw</strong><br>\nare located in Space<br>\nreact to forces  </p>\n\n<p><strong>Seeker</strong><br>\ninteracts with space:<br>\n&nbsp;&nbsp;&nbsp;&nbsp;<em>moves hand, applies magnetic field, burns hay, applies x-rays, looks for needle</em>...</p>\n\n<p>Thus&nbsp;&nbsp;<code>seeker.find(needle, space)</code> &nbsp;&nbsp;or&nbsp;&nbsp; <code>seeker.find(needle, space, strategy)</code>  </p>\n\n<p>The haystack just happens to be in the space where you are looking for the needle. When you abstract away space as a kind of virtual machine (think of: the matrix) you could get the above with haystack instead of space <em>(solution 3/3b)</em>:  </p>\n\n<p><code>seeker.find(needle, haystack)</code> &nbsp;&nbsp;&nbsp;&nbsp;or&nbsp;&nbsp;&nbsp;&nbsp; <code>seeker.find(needle, haystack, strategy)</code>  </p>\n\n<p>But the matrix was the Domain, which should only be replaced by haystack, if your needle couldn't be anywhere else.  </p>\n\n<p>And then again, it was just an anology. Interestingly this opens the mind for totally new directions:<br>\n1. Why did you loose the needle in the first place? Can you change the process, so you wouldn't loose it?<br>\n2. Do you have to find the lost needle or can you simply get another one and forget about the first? (Then it would be nice, if the needle dissolved after a while)<br>\n3. If you loose your needles regularly and you need to find them again then you might want to  </p>\n\n<ul>\n<li><p>make needles that are able to find themselves, e.g. they regularly ask themselves: Am I lost? If the answer is yes, they send their GPS-calculated position to somebody or start beeping or whatever:<br>\n<code>needle.find(space)</code> or <code>needle.find(haystack)</code>&nbsp;&nbsp;&nbsp; <em>(solution 1)</em>  </p></li>\n<li><p>install a haystack with a camera on each straw, afterwards you can ask the haystack hive mind if it saw the needle lately:<br>\nhaystack.find(needle) <em>(solution 2)</em>  </p></li>\n<li><p>attach RFID tags to your needles, so you can easily triangulate them</p></li>\n</ul>\n\n<p>That all just to say that in your implementation <em>you</em> made the needle and the haystack and most of the time the matrix on some kind of level.  </p>\n\n<p>So decide according to your domain:  </p>\n\n<ul>\n<li>Is it the purpose of the haystack to contain needles? Then go for solution 2.  </li>\n<li>Is it natural that the needle gets lost just anywhere? Then go for solution 1.  </li>\n<li>Does the needle get lost in the haystack by accident? Then go for solution 3. (or consider another recovering strategy)</li>\n</ul>\n"}, {'answer_id': 69227, 'author': 'Larry OBrien', 'author_id': 10116, 'author_profile': 'https://Stackoverflow.com/users/10116', 'pm_score': 2, 'selected': False, 'text': '<p>haystack.find(needle), but there should be a searcher field.</p>\n\n<p>I know that dependency injection is all the rage, so it doesn\'t surprise me that @Mike Stone\'s haystack.find(needle, searcher) has been accepted. But I disagree: the choice of what searcher is used seems to me a decision for the haystack. </p>\n\n<p>Consider two ISearchers: MagneticSearcher iterates over the volume, moving and stepping the magnet in a manner consistent with the magnet\'s strength. QuickSortSearcher divides the stack in two until the needle is evident in one of the subpiles. The proper choice of searcher may depend upon how large the haystack is (relative to the magnetic field, for instance), how the needle got into the haystack (i.e., is the needle\'s position truly random or it it biased?), etc. </p>\n\n<p>If you have haystack.find(needle, searcher), you\'re saying "the choice of which is the best search strategy is best done outside the context of the haystack." I don\'t think that\'s likely to be correct. I think it\'s more likely that "haystacks know how best to search themselves." Add a setter and you can still manually inject the searcher if you need to override or for testing.</p>\n'}, {'answer_id': 266251, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 1, 'selected': False, 'text': '<p>If you have a reference to needle object why do you search for it? :)\nThe problem domain and use-cases tell you that you do not need exact position of needle in a haystack (like what you could get from list.indexOf(element)), you just need a needle. And you do not have it yet. So my answer is something like this</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchByName("needle");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchWithFilter(new Filter(){\n    public boolean isWhatYouNeed(Object obj)\n    {\n        return obj instanceof Needle;\n    }\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchByPattern(Size.SMALL, \n                                                 Sharpness.SHARP, \n                                                 Material.METAL);\n</code></pre>\n\n<p>I agree that there are more possible solutions which are based on different search strategies, so they introduce searcher. There were anough comments on this, so I do not pay attentiont to it here. My point is solutions above forget about use-cases - what is the point to search for something if you already have reference to it? \nIn the most natural use-case you do not have a needle yet, so you do not use variable needle.</p>\n'}, {'answer_id': 287340, 'author': 'Jeff', 'author_id': 23902, 'author_profile': 'https://Stackoverflow.com/users/23902', 'pm_score': 0, 'selected': False, 'text': "<p>Definitely the third, IMHO.</p>\n\n<p>The question of a needle in a haystack is an example of an attempt to find one object in a large collection of others, which indicates it will need a complex search algorithm (possibly involving magnets or (more likely) child processes) and it doesn't make much sense for a haystack to be expected to do thread management or implement complex searches.</p>\n\n<p>A searching object, however, is dedicated to searching and can be expected to know how to manage child threads for a fast binary search, or use properties of the searched-for element to narrow the area (ie: a magnet to find ferrous items).</p>\n"}, {'answer_id': 287382, 'author': 'Varun Mahajan', 'author_id': 6613, 'author_profile': 'https://Stackoverflow.com/users/6613', 'pm_score': 0, 'selected': False, 'text': '<p>Another possible way can be to create two interfaces for Searchable object e.g. haystack and ToBeSearched object e.g. needle. \nSo, it can be done in this way </p>\n\n<pre><code>public Interface IToBeSearched\n{}\n\npublic Interface ISearchable\n{\n\n    public void Find(IToBeSearched a);\n\n}\n\nClass Needle Implements IToBeSearched\n{}\n\nClass Haystack Implements ISearchable\n{\n\n    public void Find(IToBeSearched needle)\n\n   {\n\n   //Here goes the original coding of find function\n\n   }\n\n}\n</code></pre>\n'}, {'answer_id': 1770119, 'author': 'Jason Orendorff', 'author_id': 94977, 'author_profile': 'https://Stackoverflow.com/users/94977', 'pm_score': 1, 'selected': False, 'text': "<p>Brad Wilson points out that objects should have a single responsibility. In the extreme case, an object has one responsibility and no state. Then it can become... a function.</p>\n\n<pre><code>needle = findNeedleIn(haystack);\n</code></pre>\n\n<p>Or you could write it like this:</p>\n\n<pre><code>SynchronizedHaystackSearcherProxyFactory proxyFactory =\n    SynchronizedHaystackSearcherProxyFactory.getInstance();\nStrategyBasedHaystackSearcher searcher =\n    new BasicStrategyBasedHaystackSearcher(\n        NeedleSeekingStrategies.getMethodicalInstance());\nSynchronizedHaystackSearcherProxy proxy =\n    proxyFactory.createSynchronizedHaystackSearcherProxy(searcher);\nSearchableHaystackAdapter searchableHaystack =\n    new SearchableHaystackAdapter(haystack);\nFindableSearchResultObject foundObject = null;\nwhile (!HaystackSearcherUtil.isNeedleObject(foundObject)) {\n    try {\n        foundObject = proxy.find(searchableHaystack);\n    } catch (GruesomeInjuryException exc) {\n        returnPitchforkToShed();  // sigh, i hate it when this happens\n        HaystackSearcherUtil.cleanUp(hay); // XXX fixme not really thread-safe,\n                                           // but we can't just leave this mess\n        HaystackSearcherUtil.cleanup(exc.getGruesomeMess()); // bug 510000884\n        throw exc; // caller will catch this and get us to a hospital,\n                   // if it's not already too late\n    }\n}\nreturn (Needle) BarnyardObjectProtocolUtil.createSynchronizedFindableSearchResultObjectProxyAdapterUnwrapperForToolInterfaceName(SimpleToolInterfaces.NEEDLE_INTERFACE_NAME).adapt(foundObject.getAdaptable());\n</code></pre>\n"}, {'answer_id': 11927019, 'author': 'Display Name', 'author_id': 1418097, 'author_profile': 'https://Stackoverflow.com/users/1418097', 'pm_score': 0, 'selected': False, 'text': '<pre><code>haystack.iterator.findFirst(/* pass here a predicate returning\n                               true if its argument is a needle that we want */)\n</code></pre>\n\n<p><code>iterator</code> can be interface to whatever immutable collection, with collections having common <code>findFirst(fun: T =&gt; Boolean)</code> method doing the job. As long as the haystack is immutable, no need to hide any useful data from "outside".\nAnd, of course, it\'s not good to tie together implementation of a custom non-trivial collection and some other stuff that does have <code>haystack</code>. Divide and conquer, okay?</p>\n'}, {'answer_id': 48103715, 'author': 'blizzrdof77', 'author_id': 1313496, 'author_profile': 'https://Stackoverflow.com/users/1313496', 'pm_score': 0, 'selected': False, 'text': '<p>In most cases I prefer to be able to perform simple helper operations like this on the core object, but depending on the language, the object in question may not have a sufficient or sensible method available.</p>\n\n<p>Even in languages like <a href="https://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a>) that allow you to augment/extend built-in objects, I find it can be both convenient and problematic (e.g. if a future version of the language introduces a more efficient method that gets overridden by a custom one).</p>\n\n<p><a href="https://www.sitepoint.com/augmenting-javascript-core-objects-revisited/" rel="nofollow noreferrer">This article</a> does a good job of outlining such scenarios.</p>\n'}]
['https://Stackoverflow.com/questions/23755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709/']