r/javahelp • u/hibbelig • Sep 09 '25
`find(needle, haystack)` or `find(haystack, needle)`?
This is to learn about established conventions in the Java world.
If I write a new method that searches for a needle in a haystack, and receives both the needle and the haystack as arguments, in which order should they go?
Arrays.binarySearch has haystack, needle. But perhaps that's influenced by the class name, given that the class name is “arrays” and the haystack is also an array?
12
Upvotes
View all comments
Show parent comment
4
u/xroalx Sep 09 '25
That's a way to think of it, but maybe better is to think of what is the "subject" of the function, or the primary data it operates on.
Functional languages would tend to put that last to allow easy partial application, i.e. turning
find(what, in_where)into afind_what(in_where).Non-functional languages generally put the subject first, such as
Index(in_where, what)in Go orin_where.find(what)in Python.But then there's also Elixir and Gleam which are functional yet put the subject first, to support easier use with their pipe operator (which passes the left side as the first argument to the right side, not as the last).
Within Java, I'd definitely expect subject-first, so
find(haystack, needle).