I have a bit of code that I would like your collective opinions on. Currently, my working code has two return statements. I'm not sure how I feel about having multiple points of exit, however, the alternative introduces the inclusion of else, which looks like it will eventually be harder to maintain if more logic is added to the code later on.
My current code (Feel free to comment on other aspects as well):
function generateFileName() {
var k = 0;
var today = new Date();
today = (today.getMonth() + 1).toString() + '-' + today.getDate().toString()
+ '-' + today.getFullYear().toString();
while (true) {
if (!fs.existsSync('./'+ today + '.pdf')) {
return './' + today + '.pdf';
}
if (!fs.existsSync('./' + today + '(' + k + ').pdf')) {
return './' + today + '(' + k + ').pdf';
}
k++;
}
}
As you see, here there are two different return statements. If the file does not exist in the system, a file will be generated with the name 5-19-2017.pdf, i.e., the current date. If there is already a file named that, the file will be named 5-19-2017 (0).pdf, then 5-19-2017(1).pdf, and so on...
This code works just fine, however - I am wondering if maybe a single point of exit might be better, such as :
function generateFileName() {
var k = 0;
var today = new Date();
today = (today.getMonth() + 1).toString() + '-' + today.getDate().toString() + '-' +today.getFullYear().toString();
var result = today;
var stop = false;
while (!stop) {
if (fs.existsSync('./'+ today + '.pdf')) {
if (fs.existsSync('./' + today + '( ' + k + ' ).pdf')){
k++;
} else {
result = today + '( ' + k + ' )';
stop = true;
}
}
else {
stop = true;
}
}
return result;
}
Now, the code has a single point of exit, however the added else statements make the code unbearable to read, in my opinion.
Thoughts?