When to extract constants
Key takeaway: Extract a constant only when its name tells the reader something the raw value cannot.
Extract a constant only when its name tells the reader something the raw value can’t. I often see programmers get a little “Extract Constant” happy.
class Greeter
HELLO = "Hello"
def self.greet(name)
"#{HELLO}, #{name}"
end
end
HELLO adds nothing. The usual argument is reuse: if the greeting changes to “Guten tag”, there’s one place to change it. But then a constant named HELLO holding “Guten tag” makes no sense, so you rename it to GUTEN_TAG everywhere, and the reuse argument falls apart.
Compare that to this:
class Today
WEDNESDAY = 3
def self.wednesday?
Date.today.wday == WEDNESDAY
end
end
Checking == 3 all over the code tells you nothing about what you’re testing. WEDNESDAY gives the magic 3 a meaning.
Values that are fixed facts of the domain also make good constants, like DISTANCE_TO_THE_MOON = 238_900.
So I extract a constant when it names an otherwise magic value, when the value is a fact of the world that never changes, or when real reuse makes maintenance simpler. A constant named after its own string doesn’t do any of those.