While doing pair programming with developers, I have experienced that some of them are hesitant to introduce the explaining variable. They worry more about other devs thinking about that extra variable.
Will it be redundant to have an extra variable? Well, let’s see:
In the above code snippet (…even though it’s a simple one), checking file size against an arbitrary number does not convey any business rule clearly. You can’t predict easily about the meaning of ‘10000000’ or size whether it is in Bits, Byte, KB, MB or something else. One who visits this snippet needs to spend some time to figure out the intent.
Well, let’s introduce explaining variable and see if it helps.
I know, I have increased the line of code here. However, don’t you think the introduction of explaining variable made it expressive and understandable?
Now it reads like:
When file size exceeds maximum allowed size (10000000 Bytes!), then just exit!
It’s really difficult for me when I read it the first time.
Now at least, you know that there is a regular expression for valid phone number pattern. It is used to determine if the phone number is valid or not and take appropriate action.
Introduce the explaining variable to convey your intent. This is one of the ways to express yourself via code.