Writing Clean Code: Naming, Comments, Functions, and Testing Best Practices
The article explains how to write clean, expressive code by defining dirty versus clean code, presenting expert guidelines on naming, commenting, function design, and testing, and illustrating each point with concrete good and bad code examples.
Writing Clean Code
Writing clean code is a universal goal for programmers; the book Clean Code defines dirty code as a "swamp" (or colloquially a "shit mountain") and stresses that deliberate practice is required to produce tidy code.
Renowned experts summarize clean code as follows:
Bjarne Stroustrup: elegant, efficient, straightforward, low dependency, single purpose.
Grady Booch: simple and direct.
Dave Thomas: readable, maintainable, unit‑tested.
Ron Jeffries: no duplication, single responsibility, expressive.
The author favors the notion of expressiveness: code should convey its purpose clearly and concisely.
The Art of Naming
Good names should be accurate, revealing what the variable is, why it exists, and how to use it, eliminating the need for explanatory comments.
Key naming principles:
Accurate : the name reflects its purpose.
Avoid Misleading Names : do not use deceptive or overloaded abbreviations.
Meaningful Distinction : differentiate concepts clearly.
Readable Words : names should be pronounceable.
Search‑Friendly : length should match scope.
Avoid Cognitive Mapping : avoid generic terms like temp that require mental translation.
Example of naming improvement:
<code># bad code
def getItem(theList):
ret = []
for x in theList:
if x[0] == 4:
ret.append(x)
return ret
# good code
def getFlaggedCell(gameBoard):
'''Minesweeper: returns flagged cells'''
flaggedCells = []
for cell in gameBoard:
if cell.IsFlagged():
flaggedCells.append(cell)
return flaggedCells</code>Another example shows clearer parameter names:
<code># bad
def copy(a_list, b_list):
pass
# good
def copy(source, destination):
pass</code>Comments
Expressive code should need little or no comments; comments exist to compensate for insufficiently expressive code.
The proper use of comments is to compensate for our failure to express ourselves in code.
Good comments include legal information, intent explanations, warnings, TODOs, and highlighting non‑obvious importance. Overly stale or incorrect comments are harmful.
Example of replacing a comment with clearer code:
<code># bad
// check if the employee is eligible for full benefit
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
...
# good
if (employee.isEligibleForFullBenefits())
...</code>Functions
Each function should have a single responsibility, evident from its name, and should not mix query and command behavior.
Example of a function that mixes concerns:
<code>public class UserValidator {
private Cryptographer cryptographer;
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
}</code>Functions should operate at a single abstraction level; mixing levels leads to confusing code. Example of consistent abstraction:
<code>def pushElephantIntoRefrige():
openRefrige()
pushElephant()
closeRefrige()</code>Parameters should be minimal; many parameters increase test cases and error risk. Boolean flag arguments often violate single‑responsibility and should be split into separate functions.
Testing
Testing, especially unit testing and TDD, is essential for maintaining readable, maintainable, and extensible code. Poorly written tests become "dirty tests" and are as harmful as having no tests.
Key testing principles (FIRST): Fast, Independent, Repeatable, Self‑Validating, Timely.
Overall, clean code relies on expressive naming, minimal and purposeful functions, judicious commenting, and robust testing.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.