See question in the title! Would you 'inject' or rather 'new' a Comparator? Would you new it if the order of elements is set in the specification and is likely not to change?
The question "should I inject this dependency?" is really "should the referring object know about the nature of this dependency?". Er, only negated.
If your class is a FastestPonyFinder
, and it needs to sort a List<Pony>
by speed, then i would say it should know about the comparator. The comparator needs to compare by speed, sorting the fastest to the head of the list; no other comparator is suitable for the job. The object should create the comparator, just like it created the List
.
If your class is a BestPonyFinder
, then it probably should have the comparator injected, because the definition of what constitutes 'best' is separable from the definition of how to find the pony which meets it. This is going to make your code easier to test and easier to change in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With