Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Combinatorial explosion is a phenomenon where the number of possible options rapidly increases with the addition of elements. Everything seems innocent until you start counting.
For example:
- We have 3 types of pizza and want to choose 2 β that's just 3 options.
- But what if we have 20 toppings and want to choose any combination? That's already over a million options!
In mathematics, this is related to combinatorics - a branch that studies the ways of selecting and arranging objects.
In programming, artificial intelligence, or game theory, combinatorial explosion is a real enemy. For example, in chess, the number of possible positions after 5 moves is over 69 billion. Going through all the options is simply unrealistic β optimizations, heuristics, and workaround strategies are needed.
Combinatorial explosion is a situation where "counting everything" becomes impossible because there are too many options.Β
The term sounds a bit dramatic - and for good reason. It illustrates well how quickly a simple task can grow into a real mathematical storm.
Combinatorial Explosion When Creating a New Class in Ruby
In Ruby (as in other OOP languages) combinatorial explosion can occur when you try to anticipate all possible combinations of object behavior or dependencies between class parameters.
Example of poorly designed Notification class:
class Notification
def initialize(user:, type:, channel:, urgency:)
@user = user
@type = type # :comment, :like, :mention, :follow
@channel = channel # :email, :sms, :push
@urgency = urgency # :low, :medium, :high
end
def deliver
# logic based on all combinations
end
end
Now we have:
- 4 types of events (:comment, :like, :mention, :follow)
- 3 delivery channels (:email, :sms, :push)
- 3 levels of urgency (:low, :medium, :high)
This already results in 4 Γ 3 Γ 3 = 36 combinations, each of which potentially requires separate delivery logic. Add 2 more parameters β and now there are hundreds of options that are difficult to test and maintain.
How to Avoid Combinatorial Explosion?
1. Strategy Objects:
class EmailNotificationStrategy; def deliver; ...; end; end class PushNotificationStrategy; def deliver; ...; end; end
2. Separate Responsibilities (SOLID):
- Notification should not know everything about all channels.
- Each channel implements its own behavior.
3. Metaprogramming (should be done wisely):
rubyCopyEditdefine_method("deliver_#{channel}_#{type}_#{urgency}") do
# ...
end
But if there are 100+ methods, this will only worsen the situation. Combinatorial explosion in a class occurs when you try to "sew" too many logic options related to the combination of parameters into the class. Over time, this leads to unreadable code, bugs, and pain.
This post doesn't have any additions from the author yet.