When writing a function with 2 objects as an arguments, like a compare function or vectors sum, what design pattern is better?
1) Writing the function inside the objects class, and get only the second object.
2) Writing an outside class with a static function, that will get both objects.
Why and when?
In Java you have
Comparable.compareTo(o1)that is executed on behalf of one object and takes second object as an argument:There is also
Comparator.compare(o1,o2)abstraction:None of them are deprecated and none of them are considered better. They are both used in different scenarios:
FruitclassYou can even combine them: you default ordering (encoded inside
Fruit) as long as the default order suits you. If one day you need a different order, choose specific comparator.I believe this scales to other similar situations and languages.