“What in the World am I Reading !?”. A guide to clean code

Faza Aryoga
Electronic Logbook
Published in
6 min readMay 24, 2021
Photo by Chris Ried on Unsplash

Picture this: You have just been hired in a tech company as a programmer, you have been put in a team of programmers and to fill the role of the guy they just fired the other day. You are briefed on the project; what the project is, user requirements, software architecture, etc. You started to continue off of someone’s work, you browse the files, go through the code and at the end of the day you understand none of it. Variables named with only alphabets, hundred line functions named like function_a and whatnot with nary an explanation or comments as to what they actually do. Turns out the guy they fired seemed to have a bad case of not writing clean code.

What is Clean Code?

There is no fixed definition as to what clean code is — it is a matter of software craftsmanship. Clean code as the name might suggest, is code that is clean, in that it is easy to read, make sense of, and communicates what it does clearly.

Code is clean if it can be understood easily — by everyone on the team. Clean code can be read and enhanced by a developer other than its original author. With understandability comes readability, changeability, extensibility and maintainability.

There is no one standard to clean code but in book “Clean Code”, Robert C. Martin defined several guidelines to cleaner codes. Let us go through them summarily.

Naming Rules

  1. Follow standard conventions

If you’re, for example, coding in java you should follow standard naming conventions specific java such as using camelCase for variables and functions and PascalCase for classes and interfaces. Different programming languages have different naming conventions so be sure to learn them.

2. Use descriptive and unambiguous names

Instead of naming your functions and variables like,

void funcA(){ //function to get date
int a; //

Have them be descriptive and unambiguous, avoid using having to use comments to explain a function or variable’s purpose.

void getDate(){
int todaysDate;

Naming them this way clearly communicates their purpose, you should understand what they are and what they do just by reading their names.

3. Use pronounceable names

This point pertains to the previous point, you should be able pronounce functions and variable’s names.

Instead of,

int scrOftst1;

Name them

int scoreOfTest1;

Using pronounceable names also makes the functions and variables easy to be searched.

Function Rules

  1. Functions should be small

Functions with 100+ lines can likely be split to several smaller simpler functions. Always try write simpler and smaller functions.

2. Functions should do only one thing

If you read through a long function and see that it is doing multiple jobs in the same function such as creating a list from database, sorting the variables, and then transforming to a readable format — such function can be split to smaller functions: one for creating the list, one for sorting, and one for presenting the data especially if one part of the function is used multiple times like the sorting part. This rule relates to the previous point of making smaller and simpler functions that only does one thing.

3. Prefer fewer arguments

If a function has three or more arguments, it is likely that the function can be simplified to smaller ones with different inputs or if not, you should encapsulate the arguments to its own class and then accessing its properties in the function.

4. Don’t Repeat Yourself

The DRY (don’t repeat yourself) is a principle of software development aimed at reducing repetitions of software. It simply means if you’re seeing a piece of code pop up multiple times in different places, you should turn that piece of code into its own function. It prevents human errors such as typos when copying the code, makes your code more reusable and easy to update.

Comment Rules

  1. Always try to explain yourself in code

If you have to explain what your code does with comments then your code probably doesn’t communicate what it does clearly. Use comments as clarification of code not explanation of it.

2. Don’t add obvious noise and redundancy

Comments like

//get date
string getDate(){
.
.
}
int result; //final result

Are redundant to already self explanatory code and will just be useless noise in the code.

3. Don’t comment out code

If you have commented out code remove them.

Testing Rules

Clean code also calls for clean tests. Tests should ideally only contain one assertion and follows the F.I.R.S.T principle. F stands for fast, I for independent, R for repeatable, S for self-validating, and T timely.

Error Handling

Any errors in our code should be handled gracefully. Avoid returning error messages and raise exceptions. Raising exceptions allows us to pinpoint the exact part of our code

Examples in action

The following live code examples are from a project for my software engineering course.

1. Creating understandable variable names

All the variables in class are succinct, descriptive, and non ambiguous. imagine if the were named only a, b, c, and so on, we won’t be able to determine what each variable is for.

2. Creating good function structure

The following is a function to assign terms to a student:

We can see here by relegating jobs such as fetching currently enrolled terms to function getTermIds() we keep the focus of function assignTerms() to just assigning terms. Also by making fetching enrolled terms its own function allows us to reuse and update it multiple time in other sections of the code without rewriting the whole implementation.

3. Writing comment for clarification

These 3 functions unfortunately have 3 similar naming and therefore it is difficult to tell the distinction between them, the comments above them clarifies their difference.

4. Creating a good test

The following code is for fetching the total amount of admin:

Here we are using jest for testing library to test the functionality of adminService.getTotal. Here we mocking the return result for userService.getTotal making our test independent of any other function so that we can focus on the functionality of adminService.getTotal itself. This test is also self-validating as we use the expect() clause to verify the return result of adminService.getTotal.

5. Error handling

The following function is for getting a user:

As we can see here we are raising an exception if we are getting a null value after getting the data from the database. We raising an exception with an error message instead of just returning an error message.

Conclusion

Code is meant to be read by computers and humans. Writing easily readable and modifiable code — clean code is a hallmark of a good programming.

With all that said, while clean code is certainly important, spending too much time cleaning your code is not ideal. Simply keep these principles in mind and not need to obsess over it, when you are coding write decently clean code if not cleaner ones, too much effort is wasted effort after all.

--

--