Tip: if code getting complicated, try rethinking the approach

Posted 2022-01-17

Lots of work bugs to fix, so I'll write a little about a lesson.

Core D Development Statistics

In the community

Community announcements

See more at the announce forum.

Tip of the Week

I had to fix some bugs in dom.d's toPrettyString for a commercial customer who found some weird edge cases. The fix ended up being to delete some special cases in the code.

Not long ago, I did a little talk thing with a group of new programmers who asked for some general advice. I told them one important lesson to learn is when you find yourself piling code on top of code to handle problems that keep popping up, you should try deleting it all (well, ok, save it somewhere else just in case, but don't keep adding to it) and starting over. It might prove that a new approach solves all the complication. It is like taking medications to treat the side effects of other medications long after the original disease has actually been cured - you might be able to just stop it all instead of adding one more.

Well, that actually happened to me this week! The dom toPrettyString method was failing in one weird edge case, so I added a check for that. Then turns out it failed in another edge case as a result of this fix. I spent a kinda long time trying to patch it all together before I finally listened to myself and just tried a new approach. Turns out something like four hacks ago was the root cause of all these problems and deleting that, putting in a more thought-out fix, made all the other problems go away. I was a bit surprised myself when deleting it all actually caused all the tests to pass... but goes to show even when you know better, you don't necessarily act better.

If you add special case after special case after special case, there's a good possibility you missed an actual general case. Not always true, of course, sometimes there just legitimately are special case complications. But always worth giving it a try.