Software developer Brandon Gregory’s two-part post in the blog “A List Apart”, describes key concepts every software designer should follow in order to make the functions in our programs not only functional, but also efficient and professionally designed.
The first piece of advice Gregory shares with us is to maintain what he calls the “single responsibility principle”. In other words, each function should only focus on one process. By following this rule, we not only limit the margin of error in our code, but also increase the flexibility of them. Having simple functions makes the program easier to read, modify, and detect errors.
The next concept the author illustrates Gregory described as “command-query separation”. This means that a function should either carry out some work, or answer a question and return some data. The key advice is to not combine the two types. A function should either perform an action or answer a question, never both. If a program needed to both change data and return information, it would be better to write two separate functions to handle the tasks.
Finally, Gregory delves into the details of “loose coupling” and “high cohesion” in code. What he means by “loose coupling” is that each subsection of a program should be as independent as possible, not relying on the other parts of the code to inform a function. Similarly, the author advises us to stick to “high cohesion”, meaning that each object in a program should only contain data and functions that are relevant to that object.
Personally, I very much agree with and appreciate Gregory’s perspective and advice on writing clean code. In his advice, he very effectively clarified a lot of the concepts that I’ve trouble with implementing in my previous programs. One of my favorite lines in this post was “Large functions are where classes go to hide.” I found this quote very useful because it helps solidify the process of abstraction. From this point on, if I’m writing a function that becomes too unruly or long or complicated, I will ask myself “would this large function be better off as an independent class?” I definitely learned a lot about good practices in simplifying functions, and I will reflect on from now on when developing programs.
From the blog CS@Worcester – Bit by Bit by rdentremont58 and used with permission of the author. All other rights reserved by the author.