Have you ever looked at code you wrote a year or two ago, and found you could not understand it? Clean code is something we should all aspire to, and yet the exact definition can be vague. In this discussion, you will share your favorite examples of both good and bad practices.
Prompt: What is one thing from the articles that you would like to start doing (more often), and why? What is one thing you want to avoid doing and why?
Clean code is an ongoing struggle and opportunity for me. I’m dyslexic, so it takes me longer to program. Getting to a point having a clean, concise code is a major goal for CS majors.
When searching for “clean code examples”, there were a lot of them. I read an article from freeCodeCamp, There’s a lot of great tips in the article. I have made many mistakes mentioned in the article.
I want to use more searchable names in my code. In previous classes, I have used magic numbers in my code whereas it is good practice to use searchable, named constants. Another great tip is to not use single-letter names for constants because they can exist in many places and be hard to search for.
An example of a bad searchable name is below:
if (student.classes.length < 6) {
// Do something
}
An example of a good searchable name is below:
if (student.classes.length < MAX_CLASSES_PER_STUDENT){
// Do something
}
Another thing I would like to do more of is simplifying method calls – this is a code smell. They can get buried in endless lines of code. There are multiple ways to simplify method calls, according to Tech Target:
- adding or removing certain parameters;
- renaming methods with ambiguous names;
- separating queries from the modifying component;
- parameterizing methods and introducing parameter objects;
- removing the methods that assign objects certain values; and
- replacing the parameter with explicit methods or calls. [2]
One thing I’m working on is to “avoid noise words”. For example, if a class is named UserInfo, Info can be removed so it can just be User. Another example is using Book instead of BookData as a class name is better because a class stores Data.
If I have a lot of variables in a program, I am concerned that I will forget the purpose of some of them, so I will include “noise words” so I don’t forget the variable’s purpose.
Sources:
https://www.freecodecamp.org/news/clean-coding-for-beginners/