MoonBun
MoonBun

Reputation: 4402

What design pattern is better?

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

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

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:

  • if there is a fixed, natural "order" of fruit, put it inside Fruit class
  • if there are multiple different ways you can compare fruit by (size, weight, color, taste), have several comparators and use whichever you need at a time.

You 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

M.A. Hanin
M.A. Hanin

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

Related Questions