Multiple Dispatch in Modern Languages

crushby

Aliaksei Kirkouski

Posted on March 16, 2023

Multiple Dispatch in Modern Languages

Rock, paper, scissors is a hand game that two or more people can play. Each player chooses one of three shapes: rock, paper, or scissors. The rules are: rock beats scissors, scissors beats paper, and paper beats rock.

We need to implement this logic using object-oriented programming without using if statements.

In a fictional language this could look like this :

abstract class Shape;
abstract boolean beats (Shape a, Shape b);

class Rock : Shape;
class Scissors : Shape;
class Paper : Shape;

// "+{ }" means implementation of the abstract function
beats(Shape a, Shape b) +{ return false; }

beats (Rock a, Scissors b) +{ return true; }
beats (Scissors a, Paper b) +{ return true; }
beats (Paper a, Rock b) +{ return true; }
Enter fullscreen mode Exit fullscreen mode

A call to the "beats" function for any two Shapes will return the result of the game.

The advantage of this approach is that you can easily extend the logic with new elements. For example :

class Lizard : Shape;
class Spock : Shape;

beats (Lizard a, Paper b) +{ return true; }
beats (Lizard a, Spock b) +{ return true; }
beats (Spock a, Rock b) +{ return true; }
beats (Spock a, Scissors b) +{ return true; }

Enter fullscreen mode Exit fullscreen mode

We implemented similar logic in our DSL, but our approach does not fit into general-purpose languages.

What is the most elegant way to implement the described problem in modern programming languages?

💖 💪 🙅 🚩
crushby
Aliaksei Kirkouski

Posted on March 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Multiple Dispatch in Modern Languages
programming Multiple Dispatch in Modern Languages

March 16, 2023