No, it's "multimethods" or "dynamic method dispatch". This is not a Java thing, that's why it sounds unfamiliar))
Finally at the computer. Well, you can find many resources about that, just google the keywords I've provided. I'll give you a good practical example of what it is. I don't like the popular spaceship example, it's not too obvious in necessity of multimethods there. I have a better one. Or even two. I've also worked last days with browser js, so an example has just sprung in my mind. Here's how you would express interacting animals hierarchy in java: interface Animal { void interactWith(Animal other); } class Dog { @Override void interactWith(Animal other) { happyToMeet(other); } } When you add a cat to it, things become not so pretty: class Cat { @Override void interactWith(Animal other) { if (other instanceof Cat) { // joy, coupling or war for territory with // casted ((Cat) other) } else if (other instanceof Dog) { runAndHideFrom((Dog) other); } } class Dog { @Override void interactWith(Animal other) { if (other instanceof Dog) { // joy, couple, make a pack with // casted ((Dog) other) } else if (other instanceof Cat) { chaseAfter((Cat) cat); } else { ... default behavior ....} } When new animals implementations would be added there will be tone of that type-checking conditional dispatching code. Moreover the type hierarchy structure is probably going to become more complex (more levels), like CommonDog, FigterDog, DecorativeDog. In that case your checks would become with more than one level depth like: if (other instanceof Dog) { if (other instanceof DecorativeDog) { ...... // known types dispatch } else { // dispatch to handler for // all other unknown types } } else if (other instanceof Cat) { ..... } There's an option to use "visitor" design pattern to solve this problem. It works because of "double dispatch". Just google it if you're interested. I don't like this approach and would hate collegues who would use visitor to solve this problem ))) joking
What is important to note here is that all that if-else code is actually just a dispatching code. It just casts argument and dispatches call to a correct handling method. It does zero real work
Just decided to not spam with another example with DOM nodes. Example with animals is obvious. Another good and so familiar to all java developers is Object.equals(Object) method. Did you notice that all that code looks pretty similar to your equals implementations? @Override boolean equals(Object other) { // null checks, etc. if (other instanceof ThisObjectType) { // compare using most information } else if (other instanceof MoreGenericType) { // compare using less info } else { // compare references } } With multimethods the implementation could be boolean equals(ThisObjectType other) { // compare using most information } boolean equals(MoreGenericType other) { // compare using less info } boolean equals(Object other) { // check for null // compare references }
Обсуждают сегодня