OOP Design: Where to put object specific “compare” method?
-
28-09-2019 - |
문제
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?
- On the object as a method? Like:
instance.approximately_equal(other)
- On the object's class as a class/static method?
class.approximately_equal(a,b)
- 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
해결책
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.
다른 팁
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.