Join Digital Nomads and Remote Workers to Ask Questions, Share Experiences, Find Remote Jobs and Seek Recommendations.

The Ultimate Guide of Writing Clean Code

Who this course is for

Introduction to code quality is for anyone who knows the code and wants to be a better programmer. It doesn’t matter how years of experience you have as long as you know to code a program. In this introductory course, we don’t specialize it in any specific programming language. So, anyone who are programmers, coders, developers with having basic programming skills are welcome to this course. For those experienced developers are also welcome, we are currently open for discussion and makes codes better!

What Will You Learn

Welcome to Introduction to Code Quality Course! We’re thrilled to have you in this Jorcus School course.

In this quick welcome video, you’ll meet your instructor (Jorcus) and learn more about what you’ll be able to accomplish by the end of the course.

Hi, my name is Jorcus. Welcome to the intro to code quality course. In this course, you will learn about everything you need to know to improve code quality. First, we will introduce you how it’s going to impact you and your organization. Then, we will give you some tips to improve your code quality in this course.

If you would like to enroll the course with more technical one, we have a course coming soon for JavaScript.


Introduction

Programming is the art of telling another human being what one wants the computer to do.

– Donald Knuth

One of my favorite quote from Donald Knuth that emphasize the programming is an art and communication not only human and machine, and it’s also communication between human-to-human.

When you write the code, you instruct the computer what to do. At the same time, you are responsible for letting the programmer knows what you intent to let the computer execute.

Having this mindset will help you build your code to better in future. It’s a win-win-win situation. The machine wins, coders, and you win because you won’t suffer if anyone writing poor code for you.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

Martin Fowler, 2008.

Anyone who learns the programming syntax can write the code to tell the computer what to do. Writing code without consideration for the future maintenance is not a good idea. A good developer should always consider the readability and prepared for future maintenance of the software they write unless It’s a temporary code which may be thrown away soon.

Writing poor code may save your times for short-term, but it and it may cause unwanted bugs when debugging it in future. You’ll end up wasting more time on debugging and figuring out the issues. The best practices for a programmer always make sure you refactored the code each time you wrote the code in case of end up you had to re-write the whole code.

What is the code quality of software development?

Programming Is The Art
Donald Knuth

One of my favorite quote from Donald Knuth that emphasize the programming is an art and communication not only human and machine, and it’s also communication between human-to-human.

When you write the code, you instruct the computer what to do. At the same time, you are responsible for letting the programmer knows what you intend to let the computer execute.

Having this mindset will help you build your code to better in future. It’s a win-win-win situation. The machine wins, coders, and you win because you won’t suffer if anyone writing poor code for you.

Any Fool Can Write Code
Martin Fowler

Anyone who learns the programming syntax can write the code to tell the computer what to do. Writing code without consideration for the future maintenance is not a good idea. A good developer should always consider the readability and prepared for future maintenance of the software they write unless It’s a temporary code which may be thrown away soon.

Writing poor code may save your times for short-term, but it and it may cause unwanted bugs when debugging it in future. You’ll end up wasting more time on debugging and figuring out the issues. The best practices for a programmer always make sure you refactored the code each time you wrote the code in case of end up you had to re-write the whole code.

Reading code is just like reading an article written by somebody else. An excellent article is commonly having a clear title, proper use of punctuation, correct use of grammar and without any spelling error. It’s usually well structured without much sloppy punctuation.

As a developer, we are responsible for writing quality software that serves everyone better. We should not always look for the short-term goal, considered of the future maintenance that the code you are composed. Reading your code repeatedly and refactored it where it needs. You can ask your senior co-worker to review your code as well. In others word, we called it to peer code review. It’s one of the conventional methods we used to improve our code quality today.

A lousy code may affect you and your team when they are trying to understand what’s you are intent to let the computer execute it. If the code is terrible unreadable, your organization may lose interested in continuing work with the code.

Code Quality
Source from Quora

So, what’s code quality?

When I was researching for the definition of the code quality, I found that everyone is having a different but a similar definition of the code quality. Today, I’ll share one of the best definition of the code quality I found on the internet. (Thus I’m not going to define it my own )

Code quality is a loose approximation of how long-term useful and long-term maintainable the code is.

The code that is thrown away tomorrow is Low quality

Code that is being carried over from product to product developed further, maybe even open sourced after establishing its value: High quality. 

Since looking into the future can be somewhat tricky, we look at the present signs that may help to predict it.

– Quora

How can poor quality source code cost your an arms and legs?

The quality code has made an essential role for a developer. Why did I say that? I believe most developers have experienced working under pressure with the deadline of your clients. In this case, a poorly written code may drive you crazier when you are rushing your work.

The moment when you and your team are working under high pressure to meet the deadline of your client. You open the source code of it, and you find the codes are terrific messy! Unstructured without document where it needs, you find no excuse and keep tracing each of the undocumented parameters, variables, etc. The time keep going second by second, but you have no excuse not to finish it before the deadline where your clients need it. Then, the whole team is going to be crazy about this.


Account

Another issue for lead and finance:

Let’s imagine if you are working on a GitHub open source project that serves at least thousand of developers. On average, to understand the well-written code is about 30 mins. However, if the codes are poorly-written the developers may need about 45 mins or longer to understand it which is 15 mins late.


Now, let’s do a small calculation to differentiate how it impacts developers in between well-written and poorly written code.

  • Imagine 1,000 developers are working with your open source project.
  • Good Code – Takes 30 mins on average to comprehend/developer
  • Bad Code – Takes 45 mins on average to comprehend/developer

So, the bad code causes a waste of 15mins for each developer. (45mins-30mins= 15mins)

  • 1,000 developers x 15mins = 15,000 mins (250Hours!)

Oh ya! You had wasted 15,000 mins of your somebody life/time! This 15,000 mins might be count as the financial loss of if you are paying the 1,000 developers in the big company. Let’s say the average hourly of those 1,000 developers was 30 USD/ hour. That’s 250 HOURS you wasted. Just because of bad code. It cause u 250HOURS + 30UDS/HOUR = 7,500 USD

Now, you have wasted 7,500 USD if you are the tech leads. So, don’t always give an excuse on code quality. Do when earlier stay. It may avoid some financial cost of your company and serves the developers life better.


The sample above was indicating to the big company with many people. Does it mean the small company/team doesn’t have to care about it?

No, it doesn’t mean you can ignore the code quality entirely if you are in a small team. The code quality valued software and represented the company value. Never wait to refactor the code and improve your code quality.

Why code quality is important in software development?

In the previous lesson, we’ve learned about the cost of poor code. Now, we are going to discuss the benefits of writing quality code. In general, the developers were spending more time on reading code instead of writing code just like what we read books more than we write. So, we should train habits that write high-quality code. Writing quality code could give us many benefits likes:

Advantages

Avoid Financial losses

The high-quality code is bug-less, we reduce the risks of getting unwanted bugs that may cost our client run away.

Reduce Time wasted

Imagine you are working the project with over thousands of the developer. If everyone was having difficulties understanding the code, you keep receiving the email repeat that the developers don’t understand your code. Do you think how much time you are going to miss out?

Ease of modification/maintenance

The quality code can be more accessible to modify by anyone. When new members were joining the project, they can won’t get much difficulty when modifying the software.

The confidence of stakeholders

Writing quality code means that your company has excellent technical management profession in this industry. Under great technical quality control/assurance, you to build your confidence of stakeholders.

Value-added (More quality more valued)

No one wants a product which that is unstructured. Pricing of the software can be affected by the code quality. Writing high-quality code brings value to your software. Just ask yourselves, would you pay for the source code that is unstructured? Alternatively, you’d better build it yourself?

Avoid Misunderstand

While improving the code quality, your code becomes more precise and accurate. That helps you reduce the risk of misunderstanding the intent of the code.

More comfortable for debugging

Since you have exception handling that tells the issue, you won’t stress out much when unwanted bugs appear. You might take a shorter time for debugging because the bugs had tracked.

Acceleration development

The excellent quality code can speed up from short to long-term software development since it’s reusable. Thus, the developer can be valued their time for creating more creative and valuable stuff instead of wasting time on fixing the bugs and errors.

Maximize profitability

Since you had saved a bunch of time, your cost minimized that create the opportunity to maximize your profitability and ROI.


Why developers write bad code?

  • Impossible project deadline
  • Quick & Emergency fix (Shortcuts)
  • Poor development processes
  • Lack of Experience
  • Lazy/poor developers
  • Too many developers
  • Lack of management
  • Low expectation
  • No guiding principle
  • Unaware of the importance of code quality
  • Lack of code quality management
  • No peer code review
  • Pay Cut?

Good code VS Bad code

In the previous lesson, you have learned about what is code quality and how it’s essential it is. Now, we are going to differentiate between good code and bad code. Before we are dive into differentiating between code, how do you differentiate the quality of food?

  • Good smell?
  • Well structured?
  • Price?
  • Good appearance?
  • Good taste?
  • Deliver in the best temperature of food?

What’s well organized can bring you? Well organized is good because you can achieve the same result with lesser effort/cost with a competitive price.

The most developer writing many codes may forget what the code write in the past few weeks. In future, you refer to your code again and again. It’s not just you, anyone who may read your code in future might need. You write code that you barely understand what you write, but you might be unable to comprehend it at all later. Unable to read your code after few months or years later, it’s embarrassing when someone is asking you what’s the code you wrote in the past.

The quality code is clear, concise and straightforward. It has a few characteristics/attributes mentioned below.

Characteristics of Good code

Clarity/Readability/Legible/Simplicity/Elegance

The high-quality code is accessible to read and understandable by anyone even the non-programmer can understand it.

Maintainable/Extensible/Scalable

The high-quality code can be easily extended without much-complicated process. Any developer working on the code can quickly make any change. When new developers coming to the team, you may reduce the extra works in long run. It’s always good to keep the technical debt in low.

Documentation

A good code should always include documentation where it needs. Make sure comments the code where it needs instead of adding unnecessary comment to the code. Writing non-useful comments may cause reversely. The best code is self-documented, you can understand it easily without writing any comments.

Well-Structured

The architecture of the overall should be in healthy. Avoid lack of planning or over-structured. Always good to make sure the code formatting is consistent and follow the team guidelines. The code needs to be refactored and make sure in consistent format.

Efficiency

Good code are refactored, reduce unnecessary code and keep it simple using reusable components whenever you can

Usability

It’s reusable, you can reuse the code when needs.

Well-tested

You wrote a small piece of software to test the code, make sure it passes all the expected result to ensure the code is bug-free, stable, no crashes, no hangs with all the possibilities.

Failure handle

When anything goes wrong, it throws the issue precisely instead of keeping it silence or do nothing.

Security

There are many security issues are coming due to the bugs and errors in the code. A better code quality are reduce the vulnerable of the software.

Technical debt

In our life, we have credit card debt, housing loan debt, student loan debt, medical debt, sleep debts and many more no matter personal, company or a country and the debts it always exists no matter what. People like to excessive use currently owned to get what they want now and pay it for the future.

In technical, we have technical debts too! Technical debts generally happened when the deadline is too close, and only ways to meet the deadline are using the quick/emergency fix. Sometimes, technical debts can be good that you can fix it immediately without harming any users with downtime.

As a software developer, you’re responsible for reducing the debts whenever it possible. There are many different cases, and it doesn’t mean without any debts are good. The debts can be useful and evil it depends how you manage it. It’s just like taking loan debts that depending on how you use it. Taking the debts gives you the power to decide how your future owned used. Every decision you made affect you and organization in the future.

Technical Debt

Why are people taking technical debt?

When developers/company want to get a thing done fast. Taking debts gave you the power of leverage. It can boost 2x, 3x, 5x or even most faster than that. The bad things are the risks are also increasing at the same time as 2x, 3x, 5x times or even more.

The difference between those debts is just a difference between using cash or credit cards. Good use of the credit card(technical debts) may make your life better or get your life even worst. There are short-term technical debts or long-term technical debts. The debt be clean when new features or lines of code replaced. Always remember, refactor your code whenever you can.

After writing so much about the technical debts, what do you think? In which scenario would you use technical debts and when you shouldn’t? Also, why?

Please share your thought below and make a small discussion of it too!

Code smells

Whenever you cook a portion of food or writing an article, there’s a smell existed. To determine the smell is good or bad it depends on the characteristic of the food/article. For example, an excellent article optimized with fewer errors in punctuation, grammar and well-structured.

The same, the code smells are also referring to the characteristic of the source code from the software. To determine the code are in good smell or not, you may look into the different characteristics of the code smell below.

Bad smell

  • Duplicated code
  • Long Parameter List
  • Long method
  • Complex conditional statement
  • Primitive obsession
  • Lazy classes
  • Large classes
  • Oddball solutions
  • Moreover, you can refer to the link below

How to improve the quality of the code?

As a developer, the hardest thing probably keep it in simple. Keeping things simple are always the best way to optimize anything. A high quality code are also means that it should be less effort and less complexity when working on it. At here, I’m going to share with you a couple ways to improve your code.

  • To be active on discussion group about best practices and code quality/health
  • Code Review – Atlassian
  • Static code analysis – JSHINT
  • Unit Test – Jasmine
  • Automated & Manual Testing – Grunt(Run static ode analysis and unit tests)/BrowserStack/SeleniumHq
  • Code measurement for quality(sonarQube)
  • Remove unnecessary/redundant/unreachable/duplicated code
  • Use meaningful names for variables, functions and methods
  • Make sure the code are readable
  • Writing comments when needed.
  • Using appropriate naming of variable
  • Review your code regularly
  • Stay consistent
  • Always writing the code with clear and simple way.
  • Training/On-boarding
  • Excessively Short or Long Identifiers
  • Overly Large Methods or Procedures
  • Excessive Parameters
  • Detailed Requirements
  • Too Many Class Implementation Dependencies

Code Review

Code review a  process of improving code quality that involves more than one developer to inspect the bugs and quality of the source code. This technique has used in any organization for many years. When a developer finished writing a piece of code, it’s always good to have someone more experienced to inspect and provide the feedback to your source code before it released.

Why organization should do code review?

Learn by doing

Code review is kind like learn by doing when you finished your work, and you think that everything is perfect right now, anyone who is more experienced could be able to figure out things to improve.   Having a code review in any organization will make your developer going to another level.

Mentoring new developers

When a new developer on board, the code reviewer will help to mentor new developer to ensure it meets the code quality requirement and avoids an unwanted mistake.

Make discussion but not the argument

When you or someone reviewing the code, it’s good to ask a question and make discussion and analyzing the best practices for the code. Be sure you take notes and avoid turning the discussion into an argument. Take advantage from the code review since it will benefit both of you and organization.

Code review tools

At here, I’m going to introduce you some code review tools that help you conduct and manage code reviews.

Source: https://en.wikipedia.org/wiki/List_of_tools_for_code_review

Whenever a developer wrote a new piece of code, it should submit a pull request in GitHub. When the project leads saw it, it may take some time to review the code and changes before it gets approved. It’s one of the most popular methods that been used in almost all organization. Here are the collaboration tools that we use for code tracking and review. You will be able to find the difference on changed easily that the tools highlighted all the new, edited, or deleted source code.

Here is the sample of GITHUB:

NOTED: The code reviewer is not only for the senior team member, it can be anyone who is more specialized and professional on some specific knowledge and experience to review it.

Code Review Best Practices

  1. Encrypt all sensitive information like password, credit card, SSN, or any sensitive personal data.
  2. Never log sensitive information in log files.
  3. Disable Weak Ciphers on your applications/web servers.

Participate In Discussion Forums

Asking questions is one of the best way to improve yourself. One of the discussion forum I would recommend is StackOverflow. There are lots of master programmers in the forum, asking for help when need. Be sure you have research the questions before asking it. Most questions are already answered, you can just search for it and get the answer directly without waiting it. if you are interested on more programming forums and how it can help you, CLICK THE LINK HERE.


Clean code principles

There are many ways and ideas to make sure your code are clean. Here are a always remember the principles that will guide you through the right direction to write a good code.

KISS Principle

Keep it simple, stupid. We might also call it as “keep it short and simple” or “keep it simple and straight forward”.

Writing simple code, will make your life simple. Writing complicated code makes your life complicated. That’s what ECHO of karma is. Bear in mind, always make difficult task simple and “Make simple tasks more simpler!” – by Bjarne Stroustrup’s

DTSTTCPW – Do the simplest thing that could possibly work

Albert Einstein: “Everything should be made as simple as possible, but not simpler.” This means that one should simplify the design of a product and success is achieved when a design is at its maximum simplicity.

Occam’s (or Ockham’s) Razor: A 14th century theory that states that in a series of hypotheses, the simplest one is most likely to be correct unless the burden of proof rests on a more complicated theory.

DRY Principle

Don’t repeat yourself.

One of the good way to avoid duplicated code is to split the reusable code into small unit. So, you don’t have to define it again and again. You can reuse the code where it needs.

WET Principle

“write everything twice”, “we enjoy typing” or “waste everyone’s time”. 

YAGNI Principle

You Aren’t Gonna Need It.

“Always implement things when you actually need them, never when you just foresee that you may need them.” – Ron Jeffries

SOLID Principle

TED Principle

Terse, Expressive, Do one thing

Over-engineer


Use Good Code Editor

Static code analysis

Use linter to automatically test code style

When writing an article in English, we use the grammar checker tool. The linter is like a grammar tool, to helps you to check the code your wrote. Using linter can help you save a lot of time when debugging or figuring out anything doesn’t meet the standard of writing code. When the code doesn’t meet the standard, it will automatically show the warning and the feedback immediately.

There are many popular linter out there in the market, here I share you a few.

  • Javascript – ESLINT

Follow a Style Guide


Code Refactoring

Code Refactoring is a technique of restructuring the source code without adding or removing any functionality. That means the code previously has been work without any issues and you rewrite it for better code readability and structure.


Test Your Code


Questions you should ask yourself when writing code. (Self-Evaluation)

In previous lessons, we have learned a lot methods to improve your code quality on your programming. One more thing you should never forget is ask yourself a few questions every time you finish a project or a section. Make some self-evaluation are always considered a good habit as a programmer. Here are a few questions for your code you can ask yourself before closing your computer.

  1. Are the code readable, maintainable, scalable and understandable?
  2. How’s the performances?
  3. Can other developers able to understand the code easily?
  4. Does the code following the coding standards/guidelines?
  5. Is there any code duplicate more than twice?
  6. Can I debug it easily to find the root cause?
  7. Is there any function or class trying to do many things?
  8. Should I refactoring the code?
  9. Is it good enough?
  10. How is the code structured? Are they in good structured?

Congratulation! You’ve did it!

Congratulations, you’ve done it. After finished all the reading, I believe you are now have some ideas of how to be a great programmer that better code.

There are long way journeys to go, things are keep improving. The current best one doesn’t mean it will still the best in the future. The best is always improved yourself to be better also be sure to make sure the code are up to date.

If you found this is helpful don’t forget to share it to your friends and social media. I’ll very appreciate for that!

What’s Next?!

Now, I encourage you to learn how to write a better code in my next course in JavaScript. We are moving forward to the more technical course for the future.

We Work From Anywhere

Find Remote Jobs, Ask Questions, Connect With Digital Nomads, and Live Your Best Location-Independent Life.