DEV Community

Somenath Mukhopadhyay
Somenath Mukhopadhyay

Posted on • Originally published at som-itsolutions.blogspot.com on

Paradigm shift - from behaviours inside objects in OOAD to Julia's multiple dispatch...

From OOAD To Julia

OOAD Thought Processing

Concept → Owner

  • Behavior → Object
  • Polymorphism → Virtual methods
  • Extension → Subclassing
  • Encapsulation → Methods inside class

Julia Thought Processing

Concept → Owner

  • Behavior → Generic function
  • Polymorphism → Multiple dispatch
  • Extension → Add new methods
  • Encapsulation → Types + modules

OO Design Thinking

  • Identify entities (classes)
  • Attach behavior to them
  • Use inheritance for variation

Julia Design Thinking

  • Identify operations (functions)
  • Define data types
  • Implement methods for combinations of types

Worldview Comparison

OOP worldview

The world is made of interacting objects.

Julia worldview

The world is made of operations applied to data.

The State Pattern in Pure Julia Style

Enjoy the State pattern written in Julia.

Note that this works without the context class of the original State Pattern, which is typically implemented using object-oriented languages like C++, Java, or Python.

# 1. Define the State Hierarchy
abstract type ChickenState end

struct Uncleaned  <: ChickenState end
struct Washed     <: ChickenState end
struct Marinated  <: ChickenState end
struct Cooked     <: ChickenState end

# 2. Define State Transitions (Multiple Dispatch)

# --- Washing ---
function wash(::Uncleaned)
    println("Chicken is getting cleaned → Washed")
    sleep(2)
    return Washed()
end

wash(s::ChickenState) = s  # Default: no change if already washed/cooked

# --- Marinating ---
function marinate(::Washed)
    println("Chicken is being marinated → Marinated")
    sleep(2)
    return Marinated()
end

marinate(s::ChickenState) = s

# --- Cooking ---
function cook(::Marinated)
    println("Chicken is being cooked → Cooked")
    sleep(4)
    return Cooked()
end

cook(s::ChickenState) = s

# --- Serving ---
function serve(::Cooked)
    println("Chicken is being served. Final state.")
    return Cooked()
end

serve(s::ChickenState) = (println("Can't serve yet, chicken is $(typeof(s))"); s)

# 3. Execution Flow
state = Uncleaned()

state = wash(state)
state = marinate(state)
state = cook(state)
state = serve(state)
Enter fullscreen mode Exit fullscreen mode

And here's the State Pattern in Python...

Feel the difference - Pythonian way and Julian way

https://dev.to/sommukhopadhyay/the-state-pattern-in-python-205

Top comments (0)