Tips
1️⃣ Use Intention-Revealing Names
- Choose descriptive and unambiguous names.
- Use pronounceable names.
- Use searchable names.
- Replace magic numbers with named constants.
2️⃣ Do One Thing and Do It Well
A function should perform a single task, and you should be able to describe it easily in its name.
3️⃣ Shorter Functions Are Better
Functions should ideally be under 25 lines; anything over 35 lines is suspicious, especially in Python, which is very succinct. It should not take more than 1 minute for someone else to understand what the function does.
4️⃣ Use Fewer Function Arguments
Fewer arguments are better:
0 arguments > 1 argument > 2 arguments.
This also helps you follow rules 2 and 3.
5️⃣ Pure Functions Are Better
Functions that change state or whose output depends on external state are undesirable.
6️⃣ Boolean Arguments Are Usually Bad
Boolean arguments often indicate that a function does more than one thing, violating rules 2️⃣, 3️⃣, and 4️⃣.
7️⃣ Maintain a Single Level of Abstraction Within a Function
This principle takes time to master. Even experienced programmers often struggle with it.
On Technical Interviews
A great way to demonstrate that you can write production-quality Python code during an interview is to apply these principles to data structures and algorithms problems. However:
1️⃣ Solve the Actual Problem First (With Optimal Complexity)
Do not obsess over clean code at the expense of solving the problem. If you’ve encountered the problem before, focus on writing the best (and cleanest) code you can to impress.
2️⃣ When You Solve the Problem
Communicate with your interviewer:
“I think this code is optimal because it has O(xy) space/time complexity because…”
Then add:
“I implemented this as quickly as possible. Normally, I would make it more readable by applying principles like (insert rules from above). Should I do this now?”