Search code examples
coldfusionmagic-numbersrot13coldfusion-2018

Magic number removal on ROT13 in ColdFusion


I have this function that calculates ROT13.

string function rot13(required string inString) output="false"  {

  var j = 0;
  var k = 0;
  var out = "";
  for (var i = 1; i <= Len(arguments.inString); i++){
    j = asc(Mid(arguments.inString, i, 1));
    if(j >= asc("A") && j <= asc("Z")) {
        j = ((j - 52) % 26) + asc("A");
    }
    else if(j >= asc("a") && j <= asc("z")) {
        j = ((j - 84) % 26) + asc("a");
    }

    out &= Chr(j);
  } // end for

  return out;
}

I don't like that it appears to have 3 magic numbers 52, 26, and 84. I think the 26 can be replace with asc("Z") - asc("A") + 1

But I don't know what the 52 and 84 represent. I don't know what I would name them.


Solution

  • By looking at your magic numbers and an ASCII table, I came up with this.

    26 is the number of letters in the alphabet. That's your first magic number.

    asc('A') is 65. 65 minus 13 is 52, your second magic number.

    asc('a') is 97. 97 minus 13 is 84, your third magic number.

    That's what the numbers represent. You can decide how to name your variables. Alternatively, you can add the explanation as a comment.

    Edit starts here

    13 is the number of characters you are rotating. That's also a magic number. You could enhance your function by making this an argument so you can rotate by other numbers as well.