Похожие чаты

Not sure what you mean. Polymorphsim?

4 ответов

15 просмотров

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 }

Похожие вопросы

Обсуждают сегодня

Ready for some fun AND a chance to win TKO Tokens? Join us for exciting minigames in our Telegram group! 🕒 Don’t miss out—games start on today 25 October 2024, at 8 PM! Ge...
Milkyway | Tokocrypto
255
Добрый вечер. Есть вопрос, а может и предложение. Был у меня диалог в другой группе о делфи и я задался вопросом: "А нельзя ли в делфи цвет //коментария и {комментария} сде...
Kraszx
24
Всем привет! Подскажи, пожалуйста, как передать в TComboBox сразу значение и id записи. На Delphi я делал так: ComboBox1.Items.AddObject('Какое-то значение', Pointer(id запис...
Евгений
13
Мдя, прикол, боевая сборка запускается (именно под отладчиком) после F9 примерно полторы минуты (97 секунд если быть точным). Начал копать - проблема детектится сразу - зависа...
Александр (Rouse_) Багель
38
How are we going bro about the Raids ??
🅿️abby_FX
13
я так понимаю, я так подозреваю, что создание такого плагина для человека, кто умеет писать плагины для делфи потребует минут 5-10 времени. но это мое подозрение. хотелось бы ...
Kraszx
7
Товарищи, кто работа с iphelper? Или может я в самой логике ошибки фигачу, не пойму.... var ifTable : PMIB_IFTABLE; size, corSize: DWORD; Buffer ...
Warfarellen
4
Здравствуйте, вопрос по структурам данных. Были у вас случаи, когда пришлось писать деревья или двунаправленные списки?
/ /
50
Keep saying it, it’s Trump or WW3. Iran will be emboldened if Harris wins by cheating. Israel will have to take the initiative against Iran. How has BTC faired everytime the...
Adz | Ferrum Network Product & Service Consultant @ Ferrum Network
1
Коллеги, добрый вечер. Создаю коллекцию от TFPGMap, ключ - перечисление, значение - целое. Нужно отсортировать коллекцию по значению. Как это можно сделать?
Kirill Filippenok
11
Карта сайта