5 min read


Generating 6-digit code for SMS authorization using sprintf() method



The simplest and most obvious bugs are the trickiest ones. That was the case on my recent project where the task was simple as it might seem - to generate a random 6-digit code for SMS authorization. 

The simple and easy solution here would be to use a range method with diapason from 000000 to 999999. That’s the one I went with. Taking into account the practicality and simplicity of the approach chosen, we didn’t prepare the additional tests to run the feature through. And that, actually (surprise, surprise), played the joke with us.

So, already at the production stage – when a lot of people tried to complete the registration – we bumped into the undesired bug. We’ve noticed that in some cases the length of the code generated was shorter than expected. Not a very neat situation for production. 

So, why did it happen?

It’s, actually, simple as it is – we didn’t consider that 000000 == 0, so the generation was done incorrectly. To fix it, there were two ways: either to change diapason from  000000 to 100000 or to use sprintf'%06d' method. We’ve preferred the latter.

What is sprintf('%06d', rand(1..999999)) method? '%06d' is a format that ensures that string must be 6-character long, so it adds up nulls, if the number that goes as the second argument is of a shorter length. The main difference between (100_000..999_999) range and sprintf('%06d', rand(1..999999)) is that sprintf returns the line that does not pass the requirements.

To sum up, this case shows us how important it is to write tests for all critical parts of the product, even if we’re talking about the simplest and most obvious features. It’s much better to detect and fix them before going to production. And most importantly, don’t forget to acknowledge your failures, embrace and learn from them.