Reputation: 4402
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?
Upvotes: 3
Views: 104
Reputation: 341003
In Java you have Comparable.compareTo(o1)
that is executed on behalf of one object and takes second object as an argument:
apple.compareTo(orange);
There is also Comparator.compare(o1,o2)
abstraction:
comparator.compare(apple, orange);
None of them are deprecated and none of them are considered better. They are both used in different scenarios:
Fruit
classYou 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.
Upvotes: 3
Reputation: 8084
IMHO, coming from the .NET background: If any of the objects might be null, use a static method.
If the first (left object) is bound to be non-null, and you'd like to make it possible for inheriting classes to provide their own implementations of the equality method, use an instance method.
Upvotes: 0