Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Comparators newable or injectable objects?

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?

like image 312
user1405469 Avatar asked Oct 08 '22 19:10

user1405469


1 Answers

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.

like image 179
Tom Anderson Avatar answered Oct 10 '22 07:10

Tom Anderson