
What separates two people most profoundly is a different sense and degree of cleanliness. – Friedrich Nietzsche
What is clean code?
You did it. You just wrote some code for an app that you built with your colleagues. You thought to yourself: “I understood what this code does, got the code to function right and tested it so that you can be sure it works perfectly”. Then, a few days later, your friend wants to integrate his code to yours. Your friend opens the file that contains your code and does not understand anything that you wrote, and because of that he called you on a Sunday morning to talk about the code that you wrote over the past working week.
Seeing that it’s from a colleague, you HAD to take the call, even though you just woke up. “But it works!”, you assured your friend. Your friend does not care. He wants to integrate the code quickly so that he can enjoy the rest of his Sunday after not sleeping for two days trying to code the feature that he wants to implement. So on a Sunday, you have to meet your friend and explain each and every line of code that you wrote. If the code that you wrote is tiny, maybe it won’t take long for your friend to understand it. But what if the code is huge in size?
This is usually the point where you regret not being a clean freak when it comes to coding. You only care about implementing a feature that works, and not more than that. You pay no care to your team, even though without them you won’t be able to finish the app and because of that, you need to do extra work that you don’t really have to do if you had wrote cleanly.
Now I’m going to tell you a different story, this time from my own experience. When I finished coding on a certain date late in the week and I expect my friend Aloy to have to read it to implement additional features, I never get contacted (unlike the previous example). Since this worries me, I asked my friend Aloy the next week why he did not contact me and whether or not he understood my code. He said to me that he understood the code perfectly and was quite shocked to see that it is really easy to understand (even though his additional implementation dirties the code somewhat) therefore not needing to contact me to ask about what the code does.
You want your teammates to completely understand the code that you just made, without you having to do extra work. That is (at least, in my case) why you need to write code that is clean.
Clean code meets all of these criteria:
- Focused
- Functions must only do a certain thing and not more than that and there must only be only one abstraction per function (either low such as getDownloadLink(); , mid such as var x = y.function(z) or low abstraction such as .append(x) ). Functions must never have a side effect to it in the sense that it does something else in addition to it’s intended function.
- Functions must have the fewest parameters that it can possibly have. If able, format the parameters into objects. Keep in mind that the more parameter a function has, the harder it is to understand it. “The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). ” (From the book Clean Code: A Handbook of Agile Software Craftsmanship)
- Classes must be tiny and only has one reason to change, as per the Single Responsibility Principle. It must have high cohesion and low coupling.
- Whenever switch statements are absolutely needed to be used, make sure to bury it in an object such as an abstract factory and do not repeat it.
- Tested
- It has to have a test that, if passed, makes developers confident that the code works as intended.
- Contains no duplication
- Remember the principle “Don’t Repeat Yourself”? You wouldn’t want to be writing code that you have written before just because it’s poorly designed, would you? That’s just tedious, even for me. I prefer splitting the code up to a separate function and have my other code execute that function. You may not be used to it at first, but after a while it becomes second nature (trust me, I experienced it myself).
- Carefully written
- It follows standards and is formatted beautifully. The standards vary depending on the language and/or that you choose, but typically your language or framework has a standard in its documentation that if you follow, will yield you code that is able to be more easily understood.
- Names should be Searchable, Pronounceable, Descriptive and Intention Revealing.
- Meaningful Comments
- The code itself should be written as if it explains to the reader what it does. Comments do not make up for bad code.
- Good comments however, such as legal comments, TODO comments, warning of consequences, clarification to things that are unalterable, explanations of intent, are needed.
Example Code
I have an example of a code from the app that I am working on, SusunJadwal that meets all of the criteria above. Take a look below at the code for one of the front-end components that it has.

Look at how simple it is! From this code alone you can know that it is a component that has another component, SplashWrapperComponent inside of it, wrapped around a nice div with an id of bg. You may infer that it is named WelcomeComponent since it appears first on the welcome portion of the app, and you will be correct. That component is then exported so that it may be imported somewhere else.
A front-end developer may notice that it imports a CSS file, and may look at it. What he found was code that was truly pleasing to see.

Another tiny code! From this, the developer now knows that the div actually is a container for a background image, has a certain width and height and has a hidden overflow.
Now after seeing that code, you may want to know whether or not it works. You now look for a snippet of a test code that tests this component. You open the test code, opened the find tool and search using the name of the component as the only keyword for the search. After that, you notice this code being highlighted as one of the results.

All the needed test cases for the WelcomeComponent, described and written in few lines each, and since it is a component that does nothing else other than it being displayed nicely on screen, it only needs to be defined and rendered correctly. You notice the names of the test cases, and you smile knowing that both of those criteria are fulfilled if the test results yield green, and it does.
That’s it! The code review process for that component is done. How many minutes did that take to review? It probably did not take more than five minutes. If the code that is written is clean, you can just take a quick look at it, and easily understand what it does and be sure that it works correctly.
Here is a slightly more complicated code. This is a component with some functions. You can see that I have divided the functions into separate methods which are clearly named, and not just combined it into one single method.

Here is an even more complicated one…..you get the idea.
import React from 'react'; import RentangTanggalUjianComponent from '../date_range_input/rentangTanggalUjianComponent'; import JumlahSesiPerHariComponent from './JumlahSesiPerHariComponent.jsx'; import PilihTanggalUjianComponent from './PilihTanggalUjianComponent.jsx'; import SendButtonComponent from './SendButtonComponent' import JumlahTanggalComponent from './JumlahTanggalComponent'; class SettingComponent extends React.Component { constructor(props) { super(props); this.state = { dateRange: [new Date(2020, 6, 2), new Date(2020, 6, 10)], isPilihTanggalUjianComponentVisible: false, dateCount: 0 }; this.dateComponent = React.createRef(); } setDateRange(startDate, endDate) { this.setState({ dateRange: [new Date(startDate.valueOf()), new Date(endDate.valueOf())] }); } componentDidMount() { this.setDateRange(new Date(2020, 6, 2), new Date(2020, 6, 10)) } setIsPilihTanggalUjianComponentVisible(isVisible) { this.setState({ dateCount: 0, isPilihTanggalUjianComponentVisible: isVisible }); } submit() { const dates = this.dateComponent.current.state.dates_enabled; this.props.setState(dates); } setCount(delta) { this.setState({ dateCount: this.state.dateCount + delta }) } render() { return <div className="container bg-white min-h-75"> <RentangTanggalUjianComponent setVisibility={this.setIsPilihTanggalUjianComponentVisible.bind(this)} setDateRange={this.setDateRange.bind(this)} /> <br/> <JumlahSesiPerHariComponent /> <br/> <PilihTanggalUjianComponent dateRange={this.state.dateRange} visible={this.state.isPilihTanggalUjianComponentVisible} setGeneratedDates={this.setGeneratedDates} ref={this.dateComponent} setCount={this.setCount.bind(this)} /> <JumlahTanggalComponent count={this.state.dateCount} /> <SendButtonComponent visible={this.state.isPilihTanggalUjianComponentVisible} submit={this.submit.bind(this)} /> </div> } } export default SettingComponent;
For all of these cases, I wrote the code myself. Unless I am chasing deadlines, every code that I wrote will be written in this standard of cleanliness.
What I Have Discovered.
Above, I have showed you how I apply the concepts of clean code into my project. However, there are a lot of things other than what I showed you, that I learned when I was either cleaning code, or conversing with my professor. Some of them are specific to Javascript, or even React which you can implement yourself. With that said, here is what I have discovered.
1. For some cases, use React Hooks
React Hooks is a new feature that is added with the release of React 16.8. A feature that could easily be utilized without changing the old code that we have written if we choose not to do that (Facebook even promotes a gradual adoption strategy for React Hooks), this allows us to write react features without the use of a class.
With React Hooks, we can create a different type of Stateful component, one that is created from a functional component, but then added with some Stateful component features. This leads to a cleaner code after transpiling, making it easy to test and debug. React Hooks also allows us to create a global state, which could further shorten the lines of code that I need to write.
Currently, we pass states to components whenever we want elements in other components to modify a component’s state. Let’s say there is an input form on component A, which modifies the state of component B which displays whatever is written on the input form. Let’s also say that these two components are a child component of C. We have to pass what is inputted into the props of component A which passes it to the state of component C, and then component B will have to access component C’s state and pass whatever is in it to its props. Before Hooks, this would be the ideal way to do it. However, with global states, we need only to access the global state, and not have to pass states through multiple component props.
My professor told me about this on the last evaluation day of the project, which led me into discovering how beneficial it is to use hooks instead of pure react.
2. Convert Duplicate Code into Components
Whenever there is a code that is duplicated, we can actually convert them into components. This reduces the line of code that is needed to create a component. This can also lead to fewer code duplication, as we can import the needed components and not have to write them again. We have done this for multiple components, and have added the possibility of creating a component that is imported multiple times in other components into something that we will factor in the planning process of creating the Front End UI.
3. Keep Components Simple
We should have not made components that are unnecessarily complex. We should have remembered that each component must have a single well defined function. We should have kept the logic and presentational counterpart separate. If we had done that, we would not have to rewrite multiple lines of code to change a single component’s function.
4. Use Prettier
Whenever we are planning to create a component, we sometimes argue about how to write it cleanly. If we had used Prettier, a code formatter tool which is compatible with Javascript, JSX and CSS (You can use this with other languages too, if Prettier supports it) and is compatible with various code editors (It supports Atom, Emacs, Espresso, Sublime Text, Vim, Visual Studio, Webstorm and the code editor that we choose to use, VSCode), we would have not worried about formatting as Prettier will clean it automatically according to the Formatting Rules for us. Even though Prettier does not help with Code-Quality Rules (Prettier cannot solve this due to code that fails the Code Quality check may have the correct syntax and formatting, and sometimes removing parts of the code that fails this check may result in broken code), this would have saved us lots of time versus cleaning the code manually.
You can click on this link to find out more information about Prettier. https://prettier.io/
5. Use Small Functions
This may be a general tip, but it is something that I want to mention here. We used to create large functions that does a lot of things before returning a value. However, in the process of refactoring the code, we have learnt that we could separate them into multiple functions and execute them whenever we want to. This allows us to not only make the code easier to understand, we could easily re-use the functions in functions that need them, without us needing to write code that we have written before.
6. Whenever Possible, Destructure.
There are two types of destructuring that we have applied to our project. One of them, is array destructuring. Array destructuring allows us to set multiple variables by way of putting the values in the array, and in the same order as the values that we want our variables to be assigned to, we create an array of variables. Here is a code snippet which demonstrates array destructuring.
const [day, dates] = arrayOfDayDates;
Here, we have set arrayOfDayDates[0] and arrayOfDayDates[1] into day and dates variables respectively. This replaces the conventional way of setting variables like this which unnecessarily elongates the code:
const day = arrayOfDayDates[0]; const dates = arrayOfDayDates[1];
The other type of destructuring that we have implemented is object destructuring. One example that we have used this on is the setting of dates in a component’s state.
Instead of using this….
setDates(dateArray){
this.setState({ dates: dateArray });
}
we use this
setDates(dates){
this.setState({ dates });
}
Destructuring is a new feature that came out with the release of ES6, and I am glad that unlike last semester, we can use it extensively in our current project to not only shorten the line of code, but also make it more intelligently written.
7. Use Rest/Spread
Rest parameter syntax allows us to represent an infinite number of arguments as an array. This is useful so that we don’t need to create new functions as the number of parameters that we want to pass increases. Here is a code snippet demonstrating the usage of the syntax:
function sumOfAllNumbers(...numberArray) {
return numberArray.reduce((prev, curr) => {
return prev + curr;
});
}
Spread is a syntax that we can use in multiple cases. However the case that we use it is as a more powerful array literal.
Whenever we want to insert the values of an array to another array, we previously did this:
function addDateFromDateArray(dateArray){
var resultingArray = getArrayFromState("resultingArray");
for (let i = 0; i < dateArray.length; i++){
resultingArray.push(dateArray[i]);
}
return resultingArray;
}
With the inclusion of Spread in ECMAScript 6, we could now do this instead
function addDateFromDateArray(dateArray){
var resultingArray = getArrayFromState("dateArray");
return [...resultingArray, ...dateArray];
}
While this may not reduce complexity, even though by using this we are forfeiting the use of the for loop, this makes the code more concise, which will be more easily readable. This will help in future developments, where code needs to be added on top of existing code.
Conclusion
Whenever you are reviewing code, you want the code that you review to be clean. Therefore, on the basis of respect, you need to also be somebody that churns out clean code every time. You need to be a clean freak when it comes to coding. Set a standard for your team to follow, have your team follow them, and you can be sure that any process of code reviewing will be a lot easier in the future.
Sources
Martin, R. C. (2009). Clean code: A handbook of agile software craftsmanship. Upper Saddle River, NJ: Prentice Hall.































