Multiple Dispatch in Modern Languages
Aliaksei Kirkouski
Posted on March 16, 2023
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; }
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; }
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?
Posted on March 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.