Question

I have some measurement object instances from a series of test runs stored in a test collection object. I also have some logic that can compare two test result object instances and tell me if they are "close enough".

Where should this logic be placed?

  1. On the object as a method? Like: instance.approximately_equal(other)
  2. On the object's class as a class/static method? class.approximately_equal(a,b)
  3. On the collection object as a method? collection.approximately_equal(a,b)

What is the correct OO design for this?

(I ask, since although #1 would seem the correct solution, I'd never be asking if some one instance is approximately_equal to a different instance. Only if "some group of objects" are equal to each other. It got me thinking...)

Thanks

Was it helpful?

Solution

The object oriented design books I have read suggest putting cross class functionality into service provider objects. This will decouple the two objects and reduce complexity, but may be overkill if your project is small.

OTHER TIPS

I would use option 1 (instance method) since that enables you to refine the comparison logic in derived classes (if needed).

I've found #3 is the least obtrusive and leads to less bloated code, because it tends to force you to make those methods as flexible/reusable as possible. For example, in C++, you'd potentially just use operator overloading to handle it; if you have a utility class (or, if you plan on extending a native data type), the net effect is the same, just with a different presentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top