This week, I am going to provide some insights/opinions regarding the practicality of some clean code principles, along with an example of when over-optimization for the sake of readability might actually be counterproductive. The resource I will be referencing this week can be found here. This article documents many of the same clean-code principles we discussed in class, plus or minus a few. For each principle, it provides an explanation as well as a coded example to demonstrate the principle and/or the difference between good and bad code according to the principle. I chose this article because I felt it was comprehensive enough to cover the key points for clean coding, and because I tend to use many of the principles outlined in the article in my own code.
I am currently involved in a project where the Single Responsibility Principle (SRP) might actually be counterproductive to my primary objective. In general, I tend to agree with this principle, and I understand its benefits well. It makes code far easier to read and follow, and, as we discussed in class, modern compilers can optimize functions to where there is almost no difference in execution time by offloading logic into its own function.
My program runs an ultra-fast search on a set of numbers (speaking very loosely), and needs to update numbers around 250 times per second. Thus, my time to find what I am searching for and act on it is ~4ms before all the data is useless (think: cracking Enigma in The Imitation Game). Now, factor in that I need the majority of the ~4ms to actually execute based on my search result, and one arrives at the conclusion that the search needs to take <1ms (or as little time as possible). Now to my point: sometimes, to accomplish this, I found that I had to violate the SRP. This means that I call search(), and search() immediately calls execute() if it finds what it’s looking for, eliminating the time it would have taken to return the value to main() and then pass the value back to execute(). This is obviously a miniscule difference, but in my testing and gathering data, I found that when multiplied out to larger and larger numbers, this little hack shaved off a noticeable amount of time.
This might all be more related to Command-Query Separation or the “No Side Effects Principle” than it is to the SRP, but my points still stand. What I am getting at in the big picture is that these principles, while applicable and preferable a massive portion of the time, are not always the right way to go. Sometimes, you have to sacrifice one or more in pursuit of your primary objective. All this said, my largest takeaway going forward is that I should remember and implement clean code principles whenever/wherever possible, but I will always try to remember that they are not law, and sometimes variance is necessary.
From the blog CS@Worcester – Mr. Lancer 987's Blog by Mr. Lancer 987 and used with permission of the author. All other rights reserved by the author.