Cleaner Code = Better Quality

Carlo Tupa Indriauan
7 min readApr 5, 2021
https://blog.knoldus.com/wp-content/uploads/2020/09/CleanCode.jpg

So a long story short, I was taking one of the courses at my university, especially majoring in computer science, namely software projects (Proyek Perangkat Lunak). As the name implies, in this course I was given the task of creating a team of five people and making software with predetermined topics. My team got the topic of creating mobile applications that are involved in academia, especially in the field of law. The name of the application is Pantau Peradilanmu. Well, in this article I will briefly explain why cleaner code generates code with better quality on my team’s project.

It doesn’t require an awful lot of skill to write a program that a computer understands. The skill is writing programs that humans understand.
Robert C. Martin

Writing clean, understandable, and maintainable code is a skill that is crucial for every developer to master. Here are the main points of writing clean code:

General rules

  1. Follow standard conventions.
  2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
  3. Boy scout rule. Leave the campground cleaner than you found it.
  4. Always find the root cause. Always look for the root cause of a problem.

Design rules

  1. Keep configurable data at high levels.
  2. Prefer polymorphism to if/else or switch/case.
  3. Separate multi-threading code.
  4. Prevent over-configurability.
  5. Use dependency injection.
  6. Follow the Law of Demeter. A class should know only its direct dependencies.

Understandability tips

  1. Be consistent. If you do something a certain way, do all similar things in the same way.
  2. Use explanatory variables.
  3. Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put the processing for them in one place.
  4. Prefer dedicated value objects to a primitive type.
  5. Avoid logical dependency. Don’t write methods that work correctly depending on something else in the same class.
  6. Avoid negative conditionals.

Names rules

  1. Choose descriptive and unambiguous names.
  2. Make a meaningful distinction.
  3. Use pronounceable names.
  4. Use searchable names.
  5. Replace magic numbers with named constants.
  6. Avoid encodings. Don’t append prefixes or type information.

Functions rules

  1. Small.
  2. Do one thing.
  3. Use descriptive names.
  4. Prefer fewer arguments.
  5. Have no side effects.
  6. Don’t use flag arguments. Split method into several independent methods that can be called from the client without the flag.

Comments rules

  1. Always try to explain yourself in code.
  2. Don’t be redundant.
  3. Don’t add obvious noise.
  4. Don’t use closing brace comments.
  5. Don’t comment on the code. Just remove.
  6. Use as an explanation of intent.
  7. Use as clarification of code.
  8. Use as a warning of consequences.

Source code structure

  1. Separate concepts vertically.
  2. Related code should appear vertically dense.
  3. Declare variables close to their usage.
  4. Dependent functions should be closed.
  5. Similar functions should be closed.
  6. Place functions in the downward direction.
  7. Keep lines short.
  8. Don’t use horizontal alignment.
  9. Use white space to associate related things and disassociate weakly related.
  10. Don’t break indentation.

Objects and data structures

  1. Hide internal structure.
  2. Prefer data structures.
  3. Avoid hybrids structures (half object and half data).
  4. Should be small.
  5. Do one thing.
  6. A small number of instance variables.
  7. The base class should know nothing about their derivatives.
  8. Better to have many functions than to pass some code into a function to select a behavior.
  9. Prefer non-static methods to static methods.

Tests

  1. One assert per test.
  2. Readable.
  3. Fast.
  4. Independent.
  5. Repeatable.

Code smells

  1. Rigidity. The software is difficult to change. A small change causes a cascade of subsequent changes.
  2. Fragility. The software breaks in many places due to a single change.
  3. Immobility. You cannot reuse parts of the code in other projects because of the involved risks and high effort.
  4. Needless Complexity.
  5. Needless Repetition.
  6. Opacity. The code is hard to understand.

Benefits of Cleaner Code

Easier to Test

Messy, complex code is difficult to test. It isn’t just difficult to unit test, but it is hard to do any sort of automated testing if the underlying code is messy. Sure, it can theoretically be done, but cleaner code is usually easier to test and–more to the point–easier to diagnose when something does break.

When a test fails–be it automated or manual–it is almost always going to be easier to find the source of the failure if the call path doesn’t pass into a mass of spaghetti at some point.

Lower Maintenance Burden

The vast majority of the cost of software is not in the initial construction: it is in the maintenance, with most of that maintenance involving activities other than directly fixing bugs.

Maintenance is expensive and, worse, it has a tendency to compound. Every minute required to orient yourself to a codebase is a minute that you aren’t designing or implementing your solution. If you can lower the maintenance burden, even by a little bit, that has a compounding effect on your ability to actually ship code.

Lower Communication via Osmosis

Clean code is easier to read, modify, and refactor for people other than the original programmer. Sure, I can read my code, but can a junior engineer? Can an experienced programmer who just started here? Can they both make changes in that code base with some confidence that their changes are correct?

Frequently in messy code, it requires a domain expert to even understand why the code, in isolation, works. In clean code, you may not see the whole picture, but it should be obvious what the problems are in the microcosm, and if you break something you should have at least some confidence that it will be caught before it hits production.

Feature Isolation

If feature X is changed, what is the probability that feature Y will also be manifesting difficulties? Robert C. Martin points out that:

Over the span of a year or two, teams that were moving very fast at the beginning of a project can find themselves moving at a snail’s pace. Every change they make to the code breaks two or three other parts of the code. No change is trivial. Every addition or modification to the system requires that the tangles, twists, and knots be “understood” so that more tangles, twists, and knots can be added.

If the code is clean, then it significantly easier to determine whether a change is “trivial” and whether a change to support X should have an impact in some remote part of the system. Changing the system is much easier because the components interact in well-defined ways.

Bugs Are Obvious

Clean code is almost always simpler code, code in which the presence of bugs is more obvious. This allows the developer to get better feedback during code review since mistakes of reasoning will not be obscured by unnecessary complexity.

Happiness

I have no data on this, but call it a hunch: Developers working in a clean code base are going to enjoy it much more than developers working in a messy codebase.

If “morale is a multiplier for velocity” then it implies that code should be written so as to minimize the amount of pain that the maintainers feel down the road.

Application of Clean Code on My Team’s Project

I did one of the clean code implementations on my team project (using flutter framework) by avoiding the term 1000 lines of code (LoC). The term 1000 LoC indicates that the code we are making is too long so it is difficult to understand and looks messy.

  @override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
key: scaffoldKey,
floatingActionButton: Container(
width: 64,
height: 64,
child: CustomFAB(),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
appBar: PreferredSize(
child: MainAppBar(
scaffoldKey: scaffoldKey, title: titlePage[selectedIndex]),
preferredSize: Size.fromHeight(80)),
drawer: CustomDrawer(),
endDrawerEnableOpenDragGesture: false,
bottomNavigationBar: FABBottomAppBar(
height: 68,
notchedShape: CircularNotchedRectangle(),
onTabSelected: _selectedTab,
color: Theme.of(context).primaryColor,
selectedColor: Theme.of(context).buttonColor,
items: [
FABBottomAppBarItem(iconData: Icons.chat, text: 'Pantau'),
FABBottomAppBarItem(iconData: Icons.library_books, text: 'Lapor'),
FABBottomAppBarItem(iconData: Icons.list_alt, text: 'Lembaga'),
FABBottomAppBarItem(iconData: Icons.person_outline, text: 'Profil'),
],
),
body: PageStorage(
child: pages[selectedIndex],
bucket: bucket,
),
);
}

As can be seen in the code above, I avoided 1000 LoC by creating several new separate widget files that are called into a function, such as:

  • CustomFAB()
  • MainAppBar()
  • CustomDrawer()
  • FABBottomAppBar()

So, the resulting code looks more neat and easy to read. The widget’s function name must also be descriptive so that it can be better understood by readers.

In addition, the clean code implementation that I apply is to do the correct naming of directories, files, and variables.

Based on the effective dart style, you should name your files lowercase and if you need to separate words, you should use underscore. I have applied it like the photo above.

In addition, because I use Visual Studio Code, there is already an auto-formatting code so it looks neater like the picture above.

On flutter, I can also check if my code is clean or not by using flutter’s built-in linter method by running the code below.

flutter analyze

If there are no problems when running flutter analyze, it is hoped that the resulting code will not have bugs, code smells, etc.

Conclusion

Clean coding is not a skill that can be acquired overnight. It is a habit that needs to be developed by keeping these principles in mind and applying them whenever you write code.

That’s all I can share regarding why cleaner code generates code with better quality on my team’s project. Thank you for reading this article. I hope you like it.

--

--