Clean the Code One More Time?

Janitra Ariena Sekarputri
Inside PPL B7
Published in
6 min readApr 24, 2020

Oh code, code, how was I supposed to know

That something wasn’t right here?

Oh code, code, I shouldn’t have let you go

And now you’re out of sight, yeah

Show me how want it to be

Tell me, code, ’cause I need to know now, oh because

Code dirtiness is killing me (and I)

I must confess I still believe (still believe)

Writing code is one thing. Writing an understandable code is another thing. That’s exactly what clean code is. Computers can read all sorts of code, but there are limitations to what humans can compute when they read code. So, when you write dirty code, people who read your code simply don’t understand your code if they want to ask someone to debug your code when there are bugs. Working on the same codebase with the team requires the code to be easily understandable and maintainable. Some rules are to be implemented on writing the code to enable high readability, other team members allowed quick adaptation, hence better code quality and development velocity.

What is the Clean Code?

“Clean code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.” — Robert C. Martin

In his book, Clean Code: A Handbook of Agile Software Craftsmanship, Martin elaborated about how clean code works. Applying clean code does take a slow start in the development, but gives a smoother workflow during the mid-development stage.

The definition of clean code is actually very wide. The definition includes the use of design patterns, data structures, naming, the suitability of making functions and classes, the suitability of formatting, error handling, unit testing, to the aspects of concurrency. Not all codes can be immediately cleaned when created. Therefore, routine refactoring needs to be done.

Characteristics of Clean Code

  1. Simple
    Follow the Single Responsibility Principle (SRP), every module, class, or function should have responsibility for a single part of the functionality provided by the software. They aim to have a single purpose, hence are focused on its sole function
  2. Elegant
    The clean code must be pleased to read. When the reader skims through the code, they must be happy with a big smile so the programmer should be proud. So, code is written in an elegant manner, yet remains easy to understand
  3. Readable
    Clean code must be easy to read. The naming, conventions, spacing, structure, and flow should be designed with the reader’s mind, so the reader will understand the original programmer’s intent. With the good implementation of clean code, the code is easy to read and understand by the reader
  4. Testable
    Writing code also means writing tested code. Future users can be confident they’re interacting with something that works well. When making changes, they will have a ready test that suits the changes to confirm that nothing broke.
  5. No Duplication
    If some part of the code will get repeated, part of the code needs to be dealt with. Code duplication is to be reduced, with the help of focused functions and specific classes.

Benefits of Clean Code

  1. Easier to Debug
    Clean code makes you easier to identify the cause of bugs. It also will help you to debug faster. Recognize the bugs easily is something we always want to have during development. With our fast-paced environment, we must not have to tinker too long. Due to our lots of tasks, we can’t afford to spend time re-reading our code and thinking about where the bug could be. We must fix it and move on to our next task.
  2. Easier to Test
    Cleaner code is usually easier to test and diagnose when something does break. It is hard to do any sort of automated testing if the underlying code is messy. This is very important, as we implement TDD during the development process. Constant creation of test suites is not that much of a burden if our code is cleaned. It’s easy for us to find the source of failure in the case of failed test cases.
  3. Easier to Maintain
    As a project grows, maintenance will need new features or changes to existing features. Maintenance involving activities other than directly fixing bugs. We might need to alter the existing code to follow new features or improve the codebase.
    In my project, there are always other new features in each sprint. There is a lot of time we need to revisit old codes and add some modifications in order to support the new features. If our code is already cleaned, we are not going to spend a lot of time to re-read the old codes.
  4. Easier to Continue
    The code must be understood by not only one person. Multiple developers can end up working on one project or a new team that will take on the project later.
    In my project development, we only have a short time to implement all features of the app, around 4 months. My project was requested by our client, Justika. If there will be an improvement in them by the future, we want to make it easy for them by writing clean code that’s easy to understand.
  5. Easier to Adapt
    Clean code principles help when there is a new programmer joint. You don’t need extensive documentation to understand the code. Clean code also cuts the time for training the new programmer.
    My team will no experiences this. But, if there is a need for help from outside of the team, they need to first be able to quickly understand what our code is doing.
  6. Easier to Smile
    If your code is clean, neat, and understandable, there will be a change in your face, SMILE :) You will feel confident and happy. You will always be smiling at your team, clients, friends. There is no need to be fear when you want to breakdown the code because you can fix any defects faster. Clean and neat code will evoke a pleasant feeling. The code should always be written with a goal to minimize the amount of pain.

How do I implement clean code for my project?

  • Use meaningful names

Easily pronounceable names for variables and methods makes easier to read and understand. Ensure that we have simple but understandable variable names to makes easier debug code. Classes and objects should have noun or noun phrases, should not be a verb. Meanwhile, the methods name should a verb or verb phrases.

lateinit var mPager: ViewPager

lateinit var mAdapter: OnboardingAdapter

lateinit var tabIndicator: TabLayout

lateinit var btnLanjut: TextView

lateinit var btnMulai: Button

lateinit var btnSkip: TextView
  • Use short method

Ideally, a method is no more than 15 lines long. Even if it’s longer, the code functions should be conceptually clean to understand. Methods or functions should be small, only do one thing, and have less than 3 arguments.

private fun savePrefsData() {
val pref = applicationContext.getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = pref.edit()
editor.putBoolean("isIntroOpened", true)
editor.apply()
}
  • Use necessary comments

Don’t comment on bad code, if there is a bad code just rewrite it. Use comments if only you need to keep notes on your program. Avoid having blocks of a comment of unused code. Sometimes we comment out code that is not working during debugging, That will create messy and unreadable code.

// skip button click listener to the last page
btnSkip.setOnClickListener{
mPager.setCurrentItem(mList.size)
}
  • Use test code

Test code is a part of encoring clean code. We aim to have independent modules to allow good tests. This will reflect on our actual code implementation. Test-Driven Development, as we have discussed in the other post regarding tests, that makes the requirements are turned into very specific test cases then the software improved to pass the new tests. Test code must cover overall code to make 100% code coverage.

@Test
fun testRecyclerJawabanView() {
onView(withId(R.id.recycler_view_jawaban))
.check(matches(isDisplayed()))
onView(withId(R.id.recycler_view_jawaban))
.check(matches(Matchers.notNullValue()))
}
  • Use DRY principles

Don’t Repeat Yourself. It aims to reduce repetition. Just remember if something similar has already been written every time you want to write a new method. Refactoring the existing code by looking for possible repetitions. Never copy and paste the same lines of code in two different methods. Repetitions are harmful to code readability and debugging, makes hard to fix issues.

Conclusion

This clean code implementation has helped everyone to develop smoothly in the mid-development stage, especially my project team. Clean code improve our team’s overall productivity. It is not easy to write clean code, do not get upset when you realize that your code isn’t as clean as you thought to be. You must learn and practice the principles.

Happy cleaning!

References

https://simpleprogrammer.com/clean-code-principles-better-programmer/

--

--