Let’s Get Clean [Code]

Take a look at your code when you first began to learn programming.

This is mine:

bad commented code
My code in Programming Foundation 1 course. Variable name and comments are written in Bahasa Indonesia.

Do you see something odd?

Yes, it’s a simple program, then why should I wrote all of those obvious comments, dear freshman me😊

Writing a code that works is important, but it’s not enough. You have to write a clean code.

So, what is a clean code?

It’s when a code is easy to understand by every programmer — not just you —, simple, and only need less work if you have to modify some parts.

There are lots of rules on writing clean code. I’ll explain some of it below based on the book by Robert C. Martin — “Clean Code: A Handbook of Agile Software Craftmanship”

A meme from the beginning of the book

General Rules

  • Follow the standard conventions

This means you should write your variables, classes, and methods name based on the standard used in industry. Also, look on the placement of braces and other attributes. Adjust the code writing with your teammates and programming language being used.

The code example below is from my software project course team code implementation. We use Python to write test, so the standard convention of a class name is using camel case, while the methods use snake case.

standard convention implementation in Python
  • Boy Scout Rule

Follow the Boy Scout Rule “Leave the campground cleaner than you found it”. Always try to make your code cleaner than before. You can do it by changing a better variable name, split a big function to several smaller one, remove duplication, and other things.

Design Rules

  • Keep configurable data at high levels

Write constants that used repeatedly by functions or variables in high level of abstraction, so you can change it easily if needed.

The example below is from the book.

public static void main(String[] args) throws Exception {
Arguments arguments = parseCommandLine(args);
public class Arguments {
public static final String DEFAULT_PATH = ".";
public static final String DEFAULT_ROOT = "FitNesseRoot";
public static final int DEFAULT_PORT = 80;
  • Law of Demeter

The law said that a method f() in a class C should only call four methods which is:

  1. Method of C
  2. An object created by f()
  3. An object passed as an argument to f()
  4. An object held in instance variable of C

Or you can remember it as “talk to friends, not to strangers”.

Here are the example — from the book — that violates the law:

final String outputDir = ctx.getOptions().getScratchDir().getAbsolutePath();

it is called train wreck, better separate it to:

Option opts = ctx.getOptions();
File scratchDir = opts.getScratchDir();
final String outputDir = scratchDir.getAbsolutePath();

Understandability Tips

  • Be consistent

Write function, class, and variable names consistently using the same nouns, phrase, and verbs. Beside it makes you easier to think of a new name, it also faster to understand.

The example below use the same phrase for the function name.

consistent naming example
  • Avoid negative conditional

Positive conditional are easier to understand. Here is the difference:

# Positive Conditionalif (files.shouldOpen())# Negative Conditionalif (!files.shouldNotOpen())

Name, Function, and Comment Rules

  • Name

Naming variable, function, and class should be:

  1. Descriptive
  2. Unambiguous
  3. Pronounceable
  4. Searchable
  5. Save a number in a constant variable
  • Function

A function is better to be small and only do one thing. Also, it should only consist of few parameter, keep it less than four.

example function in views.py
  • Comment

This is the rule that I break in my code on the image at the beginning of this article. To write a good comment, you don’t have to write a redundant and obvious thing. Don’t forget to remove your unused commented code. Use comment to explain a hard-to-understand function, to give clarification of a code, and also to write warning of consequence that might be appear on your code.

Error Handling

  • Try-Catch-Finally Statement First

By writing these statement, catchcan handle any errors that caused by unsuccess attempt execute in the trystatement. You can also specify the errors you want to handle in catch , so it can gives a specific warning to the user.

The example below is from my team project code. We implement the try in .post and .then , if they failed to execute, it will be caught by the .catch(error) and run the toast.error() which is a pop-up alert on our application.

Try-catch example in React.js

You can look out for the complete clean code rules by reading the book. Please leave a comment below if you have something to say about this article. Thank you for reading.


computer science student

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to get Trends for a Certain Location in Twitter using Python

How to get document type information and file extension in Python

Creating an HTTP Server using pure OTP

10 free stock photos you would actually use (Sunday 15th 08AM edition)

How to Send Google Forms Responses to Tray.io (or any Webhook endpoint)

RingCentral SMS ‘From’ phone number

Migrate BI Report from One Server to Another Server via OIC

Facing Your Fears Virtually: COMPLETE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yasmin Adelia

Yasmin Adelia

computer science student

More from Medium

Composite Key on Outsystems


Problem with implementation before any pattern

How does HashMap work in Java?

Squash your pull requests