Search code examples
oopclass-designprogram-structure

How do you find a needle in a haystack?


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

1. needle.find(haystack)

2. haystack.find(needle)

3. searcher.find(needle, haystack)

Which do you prefer, and why?

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".

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?


Solution

  • 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.

    You also have a fourth alternative that I think would be better than alternative 3:

    haystack.find(needle, searcher)
    

    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.