Have you seen a number in your code that does not make any sense? We don't talk about 1, 2, or 3. I mean big numbers like 965039008. How would you spell it when support asks you for your account ID?
There are two ways to make big numbers more readable. Instant and easy ways that I found mostly by accident. We use them both in one big project, and it makes our daily number work so much easier I want to share them with you.
Thefirsttrickiscontextspacesforourbraincaneasilyseelogic. Like spaces in a sentence makes it easier to read it word by word.
Let's have a little real-life experience. Today we have less and less time to get through our day. We barely read section titles and text in bold.
To simulate that, read the next number in a blink of an eye (~200 ms):
$housePrice = 10000000;
Now answer: how much does your new house costs?
I can't answer that for sure, and I wrote that number just a few seconds ago.
Now let's see the same number with context spaces:
$housePrice = 10_000_000;
The answer is obvious now - 10 million.
This little trick is called the underscore separator and we can use it since PHP 7.4+.
Do you want to make your future code more readable?
_ in numbers while you're writing them. It will save your from guessing in future months:
$creditCardNumber = 1234_1234_1234_1234; $phoneNumber = 420_776_778_333; $price = 99_99;
Do you want to make your current code more readable?
AddLiteralSeparatorToNumberRector from Rector to upgrade your numbers:
-$int = 500000; +$int = 500_000; -$float = 1000500.001; +$float = 1_000_500.001;
What is the magic behind these numbers?
From the paragraph title, we know it's about time... but how much precisely? No calculators are allowed!
Some packages are very powerful, but only very few developers are aware of them. One of these packages is Nette\Utils. You don't use it for every project yet? Read hidden gem post and look at 1 more reason on Reddit from last week.
It can help to make these numbers more readable:
const TIMEOUT = 86400; const PING = 3600;
What are these? One of them might be an hour in seconds. The second... maybe a day in seconds? "Maybe" is not for coders, it's for gamblers. We play it strictly!
+use Nette\Utils\DateTime; -const TIMEOUT = 86400; +const TIMEOUT = DateTime::DAY; -const PING = 3600; +const PING = DateTime::HOUR;
Suddenly, random numbers will get a sense:
+use Nette\Utils\DateTime; -604800 +DateTime::WEEK -31104000 +DateTime::DAY * 30 * 12
Next time you'll write time in your code, give time to think about the time constants.
Would you like to upgrade your current numbers to constants instantly? Use
ReplaceTimeNumberWithDateTimeConstantRector from Rector to handle it.
Do you learn from my contents or use open-souce packages like Rector every day?
Consider supporting it on GitHub Sponsors. I'd really appreciate it!