Multiple dispatch and Symmetric methods - Where Does That Code Live?

Hi all.
I am stuck with the above problem, which looks to be a very common and fundamental one. Supposing I have some sort of relation or operation to be performed on various different pairs (or n-tuples) of classes of object. Where does this code belong, given that it is not sole property of any one of the classes, but a kind of property of the collection of classes?
An bad example for me to bring up, but one that neatly illustrates the point, is the equals method. In order to retain the symmetric and transitive properties of the equals method, and object can only make judgement calls about it being equal to another object of it's own type. This prevents the concept of equivalency from crossing between types.
In order to compare a with b (if a and b are of different types), b must supply some sort of representation of itself as an a, then the comparison statement a.equals(b.asA()); must be called.
This of course means b must supply an 'asXXX()' method for each class XXX it wishes to equate itself to. Furthermore, by an extension of the equals contract for symmetricality, the method AsB() in class A (if it exists) must be such that, if a.AsB() .equals (b), then b.AsA.equals( a ).
This sort of design is unfeasible for obvious reasons, the main reason being that it is impossible to anticipate evey case where an instance of class A could reasonably be compared to an instance of some other class X.
The other annoyance is all that hard work of providing methods to equate A with something else, would go unused for 99% of the time.
With this in mind, I was thinking. Suppose in some program environment, we have only 3 classes, A, B, and C, such that:
{A,B} can be meaningfully compared
{B, C} and {A, C} cannot.
It would be OK to supply code (somewhere) for comparing A's with B's. We also know that under no circumstances will an A or a B, and a C, ever need to be compared for equality.
Supposing an extension of this environment were created, introducing class D.
{D, A} and {D, B} can be meaningfully compared.
Now, neither A nor C knows what a D is, or how to compare themselves to it. But D was developed with A, B and C in mind, and contains logic for the various comparisons (with A and with B). An obvious idea for this is to let D bring it's new code into play, by registering these new comparison functions in the environment somehow.
Supposing instead that equality comparison was delegated to some third party, instead. This third party contains a table of pairs of classes, which act as keys to look up a comparison object.
So, when class A is loaded, something of the sort happens:
public class A {
    static {
        Equals.comparer.addEntry(A.class, B.class, new EqualsMethod() {
           // details of the EqualsMethod interface implementation go here
public class B {
    static {
        // since equals is symmetric, this method clashes with the above in A
        // This could happen...
        Equals.comparer.addEntry(B.class, A.class, new EqualsMethod() {
           // ... different approach to the above
public class D {
    static {
        Equals.comparer.addEntry(D.class, A.class, new EqualsMethod() {
        Equals.comparer.addEntry(D.class, B.class, new EqualsMethod() {
    } // Ds can now be compared with Bs and As. They can now be compared with Ds
}There is a problem with the above. As can clearly be seen, there are 3 unique situations that might occur between two classes (call them X and Y).
o One of X or Y contains code to compare them both.
o Neither X nor Y contain code to compare the two. X equals Y is always false
o Both X and Y contain code to compare the two.
The third causes the problem. What if X and Y disagree on how to compare themselves? Which method gets chosen? The only solution would be to let whosever static initialiser gets called first be the one to supply the code.
I said before that equals was a bad example to bring up. this is because the usage of equals and the concept of equality in java is already well defined, and works just fine. However, in my own pet project at the moment, I have run into the same problems as outlined above.
I am currently assembling a generic pattern API for use in various other applications I am writing (I was finding that I was writing code for matching objects to patterns, in different guises, quite frequently, so I made the decision to refactor it into its own package). An important part of the API is the section that handles the logic for combining patterns, ie with AND, OR and NOT operations.
The Pattern interface is this:
interface Pattern<E> {
     public boolean match(E toMatch);
     public Pattern<E> not();
     public Pattern<E> or(Pattern<E> other);
     public Pattern<E> and(Pattern<E> other);
}There are a few basic Patterns:
TruePattern<E> - a pattern that always returns true no matter what E is passed for it toMatch
FalsePattern<E> - self-explanatory.
ExactValuePattern<E> - true if and only if the E that it is passed toMatch is .equal to the E that this pattern was constructed with.
NotPattern<E> - a pattern that contains another pattern, and returns true for any E that returns does not match it's contained pattern. Used for when the contained pattern cannot be logically reduced to one pattern under the NOT method in the Pattern interface
AndPattern<E> - a pattern that contains 2 other patterns, and returns true for some E iff both contained patterns return true for that E. Used for when the 2 patterns cannot be logically reduced into one pattern via the AND method in the Pattern interface
OrPattern<E> - self explanatory
RangePattern<E extends Comparable <E>> - a pattern for comparing if some Comparable lies between two other comparables.
Every pattern has the opportunity to provide a reduction, when combined with another pattern through And or Or. For example, any pattern AND a FalsePattern can be reduced just the FalsePattern. any pattern OR a TruePattern can be reduced to just the TruePattern.
The methods AND and OR from the Pattern interface present the same problems as the .equals() example I was using before.
o AND and OR are symmetric operations
o There exist situations where two patterns of unrelated class could be meaningfully combined (and reduced) under these two operations.
Example: The pattern on Integers '0 < X < 3' and 'X is 5' can be reduce to the FalsePattern
Example: The pattern on Doubles '0 < X <= 10' or 'X is 5.5' or 'X is 7.2' can be reduced to '0 < X <= 10'.
Example: The pattern on Integers ('0 <= X <= 5' and 'X is not 0') or ('X is 6') or ('x is 7') can be reduced to '1<=X<=7'.
So the question is, where does the code belong? a.and(b) should return the same as b.and(a), but both b and a may well disagree as to what happens when they are combined under and. At present, both a and b need to supply their own separate implementations. Clearly though, the code for combining patterns A and B belongs to neither A alone, not B alone, but to A and B as a whole.
Thanks in advance, and sorry for this overlong post.

So the equivalent thing in my scenario would be an
AndAnator, and an OrAnator? :)
The thing is, it would be nice for comparison between
A and B to take place automatically, without the poor
coder having to maintain a reference to a Comparator
and invoke the comparison method each time. Likewise
in my situation, it'd be nice to say A.or(B) instead
of andAnator.and(A,B), yet have all the goodness of a
third party doing the comparison (or in this case,
the anding).
I am going to go and test this all out, but do you
have any suggestions on a good structure? I think it
would involve pulling the and/or/not methods from the
interface (this appeals, as many implementors may not
wish to supply logic for running these methods
anyhow), and then putting them... somewhere else.I didn't consider your speicifc problem very deeply because after such a long detailed explanation I figured you'd be up for kicking around the idea for a while.
In your case, I see that you would want to be able to call the and and or methods on the Objects themselves. Luckily, in this case, I think you can have your cake and eat it too.
You can make your and and or methods fa�ades to the third party 'referee'. This way you can enfore symmetry. It's difficult (if not impossible) to enoforce transitivity with this design but I think you don't even need that in this case. That is if a == b and b == c then a == c should be true but if a and b and b and c then a and c is not necessarily true. In your case, it may not even make sense.

Similar Messages

  • I signed up for 20 bucks a month to use photoshop and only got one day of use.  Where does that get

    I signed up for 20 bucks a month and only got one day of use of Photoshop.  Where does that get off?

    What error are you receiving?  Do you have a subscription to Photoshop CS6?

  • I installed iOS 7 and it deleted some of my contacts, as expected, so I just resaved them all. There's one particular number that will save but in my messages, it shows up as the number instead of the name saved. How do I fix it? And why is it doing that?

    I installed iOS 7 and it deleted some of my contacts, as expected, so I just resaved them all. There's one particular number that will save but in my messages, it shows up as the number instead of the name saved. How do I fix it? And why is it doing that?

    I had this problem too, I fixed it by going to my settings and under general at the bottom there is a reset option, go there. One of the options should be reset network settings, select that one. I’m not sure why it happens but that worked for me; hope you have the same luck!

  • Text messaging some are green and some are blue does that reference that they have orhave not been received

    Some of my text messages are green and some are blue,does that reference some delivered some not.  Why is there a difference in color.  Some of my texts seem to not go through

    Blue = iMessage...
    Green = Text message... SMS
    Using Messages  >  http://support.apple.com/kb/HT3529

  • HT4236 I successfully synched photos from my mac book iphoto to my new iphone 5 (icloud did not do the job).  Now these photos appear on my phone in three places--iphoto, last import and photo library.  Does that mean that they take up three times the mem

    I successfully synched photos from my mac book iphoto to my new iphone 5 (icloud did not do the job).  Now these photos appear on my phone in three places--iphoto app, last import, and photo library.  Does that mean that they take up three times the memory?  Will that affect iCloud?  Sorry for the end-user questions!!

    HHi, thank you for the reply. I have checked my iPad and iPhone and neither has iCloud Photo Library (Beta) enabled. Turned off in both. Photostream is turned on.
    i tried to sort it out  by dragging all the photos to Events on the Mac and then deleting them from iCloud - (left hand side of iPhoto under the section 'Shared'). the photos now show up in Events. I did force quit but the issue remains. The message reads ' photos are bing imported to the library. Please wait for import to complete.'
    i can't empty iPhoto trash either. The message read "Delete error. Please wait for import to complete.'
    WHen I was moving the photos to the Events I always had a message about duplicates - to the effect that the photos already existed, did I want to import them? I clicked on Yes, import all duplicates. But when it showed the images - duplicates side by side - one showed the photo and the other was blank.
    I really don't know what to do! And I don't know how to handle my iOS devices. Is it to do with the large number of photos? Any help, advice appreciated.

  • I'm trying to move my photos from my iphone to my PC, every time I go to my Computer it comes up with PhotoStream and iPhone , unfortunately this does that have all my photos from iPhone in it. Can anyone help me?

    I'm trying to move my photos from my iphone to my PC, every time I go to my Computer it comes up with PhotoStream and iPhone , unfortunately this does that have all my photos from iPhone in it. Can anyone help me?
    I'm using the most up to date software.
    Thanks

    Thanks for that, on the sync via iTunes, when my iphone is connected to iTunes via USB my photos tab says my iphone but I can never see any pics there. If I press Sync it still doesn't show anything.
    Correction from my original post, it only comes up with PhotoStream on my computer when I'm connected via USB.

  • I installed a game, where can i find the files and maps? where does iMac store this data?

    I installed a game,Now I need to add some files however, I cannot find where iMac stores it.. where can i find the files and maps? where does iMac store this data?
    thx alot
    erik

    Depends on game, i would look first on the game file itself, right click (or ctrl click) the game file you installed (Applications?) and select show package contents, its usually a application bundle, as in basicly a folder where the application and the required files and subfolders are.

  • It won't let me into I message. I type in my ID then I pick what people can text me by then I press next and it goes back to the sign in page so I tried it again and it just kept doing that so it won't let me into iMessage? Please help!

    It won't let me into I message. I type in my ID then I pick what people can text me by then I press next and it goes back to the sign in page so I tried it again and it just kept doing that so it won't let me into iMessage? Please help!

    Try:
    iOS: Troubleshooting FaceTime and iMessage activation

  • My I-pod screen is cracked and my account says 'Repairs and Service Coverage: Active' does that mean I can get it fixed for free or replaced?

    My I-pod screen is cracked and my account says 'Repairs and Service Coverage: Active' does that mean I can get it fixed for free or replaced? the ipod is very usefull to me as it keeps my three younger brothers entertained for a few minutes or hours and yes I understand that the Ipod is not indestructible but when in my pocket with two euro coins, it should not break when I sit down.

    That kind of damage is accidental and is not covered by warranty.  You can get the unit replaced for a flat fee:
    Replace broken screen on i-device - https://discussions.apple.com/thread/3869709 - lllaass post.  Similar one at https://discussions.apple.com/thread/3925666
    Apple - Support - iPod - Repair pricing - http://www.apple.com/support/ipod/service/prices/

  • Hi. I just wanted to update my 3 apps PS, Brigde and Indesign. After doing that I wasn't ablle to open Brigde??? PS and Indesign works fine. Further more the Application Manager does not seem to register the updates I have made. Everytime I open the compu

    Hi. I just wanted to update my 3 apps PS, Brigde and Indesign. After doing that I wasn't abble to open Brigde??? PS and Indesign works fine. Further more the Application Manager does not seem to register the updates I have made on Indesign and PS. Everytime I open the computer MacIBook 4.1, OS 10.6.7) it looks like I haven't updated software? Please help! Kurt

    Moving this discussion to the Bridge General Discussion forum.
    Kurt Rodahl Hoppe I would recommend reviewing Updates repeatedly applied | CC which discusses how to apply the updates successfully.

  • HT201210 if i restore and update my ipod does that mean my pictures in the ipod would be deleted?

    if i restore and update my ipod does that mean my pictures in the ipod would be deleted?

    Welcome to the Apple Support Communities
    It will delete all your data. However, before upgrading, iTunes will make a backup, so you can restore it after upgrading and your data will be restored, including your photos taken with your iPod

  • Where does the artwork live ?

    Where in the systm does the artwork 'live' thats associated with tracks ?
    I fully understand how to add it to tracks etc but where does it actually live as I don't see it in the itunes music folder ?

    iTunes stores the artwork inside the music files, if the files support tagging (MP3, AAC).
    Observing the file sizes of AIFF (does not officially support tagging) makes it assumable it is also stored in/attached to these files.
    You can read more about ID3v2 tagging at www.id3.org.
    Hope this helps.
    M

  • APEX_COLLECTION - where does the code go?

    I am trying to create my first APEX collection.
    Where does the code go?
    Do I create a region as a PL/SQL anonymous block?
    Please advise -
    Regards,
    Stan

    Hi,
    I think best is create page process where you create/populate collection
    Br,Jari

  • Notes field in Capture dialogue - Where does that information go?

    I have been capturing a lot of complete tapes lately (using Capture Now), and I have used the Notes field to some extent to describe the content.
    However, I cannot seem to find that information when I look at the clip in the browser, even in list mode. I thought that the Master Comment 1 field was the one in question, but apparently not.
    Can someone enlighten me as to where this information is gathered?

    I was about to write Thanks to you, but then I saw that I already had Log Note displayed, and that the field is completely empty... I tried another import yesterday, but I am not getting anything filled out in the Log Note field. Or any other field actually, beyond Reel, although they are alled filled with information. Is this right? I am using "Capture Now" btw.

  • What about MS Access VBA where does that go?

    Hello Folks newbie here,
    This is the closest form that matched my needs. New to Oracle. Have around 4+ yrs with Access. Access has reached some limitations hence I downloaded Oracle Xpress Edition ("Access on steriods" as the white paper calls it). Well if thats the case then I hope somebody can point me in the right direction.
    I'm looking to re-design my current desktop app. into Web App. My current Access / Excel / VBA is a legacy system. The Web interface part required is having Excel Spreadsheets viewed, edited online and any changes would go back to the Oracle Express edtion DB.
    I think moving the access tables to Oracle is pretty straight forward. What about all the VBA modules where do those go?
    Well hope to hear back.
    Steve ---
    TORONTO, CANADA.

    -I think moving the access tables to Oracle is pretty straight forward. What about all the VBA modules where do those go?
    Hello ,
    you can transform your data with kettle or develope Java , C# etc applications.

Maybe you are looking for

  • Apple Mail won't download .doc attachments

    Lacking a specific "Mail" catagory I've posted this here. Less than Ideal I know but here goes. This just started last week. Many of us in the office and contractors we work with send .doc files by email. In the last four of five days (mid March 2014

  • How to save Checkbox inputs as a Variants in WD ABAP

    Hi, I am going through this nice blog [http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=(J2EE3414700)ID0832150950DB20043138143752756391End?blog=/pub/wlg/10731] which helped me creating varaint options for SELECT -optins fields. Everything works fine

  • How I fixed Imessage and Factime

    As I'm sure all of you know, Imessage and Facetime seem not to work with new IOS 5 updates. I can't seem to understand why, but it seems as if pre-paid users of the Iphone are the people whom are suffering the most. If your anything like me, your abl

  • Video Pro application missing from my 808 even aft...

    Hi, Well the title says it all. I saw everywhere on the net that the 808 PureView was to get the Video Pro app after the FP2 update, but even after the update to FP2 my 808 still doesn't have that application. And it doesn't show up in the update app

  • One Site from the Menu does not work

    Hello everyone, I recently built a simple webpage for my personal online-portfolio with the trial version of Adobe Muse. It involves five sites with some pictures and html-embedded YouTube-videos and a menu, that's it. When I publish the page to busi