Skip to main content
3 of 3
added 322 characters in body
gnasher729
  • 47.5k
  • 4
  • 68
  • 133

The code you linked to is not editable. If you don’t have to touch it, leave it. If you have to touch it, having unit tests would be nice. So write unit tests, and make sure that if you change any single condition, some unit test breaks.

Now the linked code is not difficult to change but difficult to change without making any mistakes. One way that helps is two people making the changes individually and then you check that you have the exact same code twice. It improves your chances.

Now a systematic way to fix it in this case of massively nested ifs and else’s: Add a variable “bool done = false”. Then you change from “if(cond1) { things1; if (cond2) { things2; if (cond3) { things3 } } } to

If (! Cond1) done = true;  
If (! Done) thing1;  
If (! Done && ! Cond2) done = true;
If (!done) thing2;
If (! Done && ! Cond3) done = true;
If (! Done) thing3;

And you can do that for miles.

What you don’t do: Change this total mess of code without refactoring. Or write code that you think is correct: During refactoring you write code that has exactly the same behaviour, whether it’s right or wrong. If anything in the end result looks strange, then either you have found a hidden bug, or you have found that the correct behaviour isn’t what you thought is correct. Either way you want to know.

That’s the rule with refactoring: Don’t even try to figure out what the code does, but change it purely mechanical so the semantics stays identical while the code becomes readable. At that point it should be editable in case you need to change it, and what it does should become obvious, whether it is correct or not.

gnasher729
  • 47.5k
  • 4
  • 68
  • 133