DEV Community

Aliaksei Kirkouski
Aliaksei Kirkouski

Posted on

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?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay