lundi 30 mai 2016

Cleaning up pathologically-nested "if { } else { if { } else { if { ... } } }"

I currently have the misfortune of working on Somebody Else's C# code which has truly blown my mind. I have no idea how the person before me ever maintained this code, as its various pathologies have crashed the IDE, the compiler, the runtime environment...

The problem I'm facing today involves a 15 megabyte source file that features a truly mindblowing degree of pathological nesting. Code like:

if(var == 0) {
  // do stuff
}
else {
  if(var == 1) {
    // do stuff
  }
  else {
    if(var == 2) {
      // do stuff, identical word for word to the `var == 1` case
    }
    else {
      // etc.
    }
  }
}

This is a questionable stylistic choice at the best of times. However, this combines with another pathology of the code: some of these blocks are nearly a thousand levels deep. (The deepest I bothered to measure was well over 700.) I sincerely hope the person before me, as one of their final acts before being forcibly separated from this code, ran a styling tool that resulted in the abomination before me. I cannot conceive that they could possibly have written this code as it is now, especially since every third or fourth edit to the code crashes the IDE. (And sometimes deletes my copy of the source file, as a bonus.)

I wrote a simple regex-based tool to try to condense the simpler cases, but it seems to half-process and then corrupt this particular code. (I'm not sure whether it fails because this code also uses preprocessor conditionals from time to time, or because the longest of the matches would be almost 10MB long and Lua's regular expression matcher just can't cope.) I'm hoping there's a widely-used tool or technique that can reverse this problem. I already had to use astyle to clean up some other stylistic "issues" the code had. The --remove-brackets option for astyle almost does what I want, but requires that the bracketed statement be a single statement on a single line, which is very much not the case here... (And just to cross my "t"s, I checked; astyle did not create this particular problem.)

Aucun commentaire:

Enregistrer un commentaire