How to Write Clean Code? A Brief Guide on Rules and Principles • Slash

articles

How to Write Clean Code? A Brief Guide on Rules and Principles

February 20, 2022

When Robert C. Martin wrote the book “Clean Code” back in 2008, it began to change the world of coding. In early 2000, coding was meant to be harsh – if not by intention but due to the market practice. However, the concept of clean coding changed the view of many programmers when they started implementing the rules and principles of clean coding. So let’s find out what clean code is, its rules and principles, and how we use it at Slash?

What’s Clean Code?

Codes are said to be clean if they are understandable by the entire team without scratching their heads multiple times. In other words, a clean code is easy-to-read, maintain, extend, and change by any developer. That means if you’re an author of a project and pass it on to your colleague developer, but the person cannot understand the code, you haven’t written clean code.

Rules to Write Clean Codes to Avoid Mess

You can save your entire team from having a few extra cups of black coffee every day by writing clean codes. All you need to do is to follow these rules:

Be All Downhill

The first rule is to do things in the simplest way possible. Try to write codes without complexities. If you got a file with a lot of complicated codes, try to fix those before going forward. Doing so will ease coding in the upcoming stages. Also, try your best to view and overcome problems from their roots.

Design Rules

Always keep configurable data on the highest level but avoid over-configurability. Also, it is best to use a single interface to different types of entities (polymorphism) to switch/case or if/else statements.

Moreover, it is wise to break up multi-threading codes and apply the dependency technique. Additionally, always follow the “Law of Demeter” (LoD).

Understandability

Just be consistent in your way of doing things.

For instance, if you have a particular method to code a specific action, make sure that all similar actions are done in the same manner.

Likewise, put all boundary conditions processing in one single place and include explanatory variables when writing codes.

Next, avoid using negative conditionals and logical dependencies by writing codes that aren’t dependent on any other element in the same class.

Give Easy Names

First things first, give names that are easy to understand. You can do this by:

  •       Using searchable names
  •       Choosing clear and descriptive names
  •       Replacing constants with magic numbers
  •       Keeping names that are easy to pronounce

Say No to Large Functions

Functions help achieve specific tasks through codes. It would be best to use small functions to describe a single task to write clean codes.

Yes! You can use descriptive names but never go for a series of arguments. Or, in other words, avoid using flag arguments. Instead, divide a single large method into numerous independent methods. So whenever the client calls any of them, it comes without the flag.

Comments

Remember, self-explanatory codes don’t require comments. However, it doesn’t mean comments are good or bad, but programming without putting comments is the best way to write clean codes.

Therefore, try your best to:

  •       Explain your work through codes
  •       Avoid unnecessary comments
  •       Remove any comment out codes
  •       Ignore the noise and closing brace comments in coding to make it reader-friendly

And if you are using comments in your codes, then they should be used as:

  •       Explanation of intent
  •       Warning of any consequences
  •       Clarification of your codes

Structuring

We have divided structuring into two sections:

  1. Source Code Structuring
  2. Objects and Data Structuring

When structuring source codes, you should:

  •       Separate your concepts vertically
  •       Make related codes look vertically dense
  •       Declare variables as per their usability
  •       Close all similar and dependent functions
  •       Downward the direction of functions
  •       Keep the lines short
  •       Avoid using horizontal alignments
  •       Use unbreakable indentation
  •       Use white spaces for differentiating similar and distinct codes

And when it’s time for objects and data structuring, this is what you should do:

  •       Keep the internal structure hidden
  •       Work on data structures
  •       Don’t use “half object and half data” (hybrid)  structures
  •       Structures should be small and one at a time
  •       There should be minimum instance variables
  •       Base class should be disconnected with any of its derivative codes
  •       Have many functions
  •       Apply non-static methods rather than static methods

Testing

When you are about to test your program, ensure testing one assertion at a time. Furthermore, the test should be readable, fast, independent, and repeatable.

Image1
Credit: monkeyuser

A Few Deeper Problems to Overcome for Clean Coding

When you are trying to write clean codes, you should know the common code smells, such as:

Rigidity

Keep in mind that once the software is written, it is difficult to make amendments later. It is because even a tiny little change could cause a series of alterations, making everything go to waste.

Fragility

The software has a fragile nature. Any changes to it in the later stage could disrupt the overall functionality.

Immobility

Since you are writing clean codes, so expectedly, they will be short and to the point. Therefore, it could be pretty impossible to use them on any other project with a different nature.

Repetition and Complexity

Unnecessary repetition of codes adds a new level of difficulty for the team, as they cannot fix things or continue the project without the author’s supervision.

Opacity

Complicated coding is always hard to understand.

Principles of Clean Code

Just like there are rules for clean coding, there are principles made by fellow developers, which are valuable when followed.

These principles help organizations and developers write clean codes.

KISS – Keep it Simple Stupid

The KISS principle tells you that simple codes are better. It would be best to avoid including complicated codes in your program. So whenever you’re writing code, ask yourself if there’s another way to write them more straightforwardly?

DRY – Don’t Repeat Yourself

DRY defines that your codes should be unrepeated. They shouldn’t be used multiple times within the codebase and must have an authoritative and clear meaning.

Failure to apply the DRY principle leads to WET, which is considered as “Waste Everyone’s Time,” “We Enjoy Typing,” or “Write Everything Twice.”

YAGNI – You Aren’t Gonna Need It

YAGNI plays an essential role in Extreme Programming methodology to develop software as per customers’ demand.

The acronym simple means that a developer should avoid adding functionality to a program until necessary. You should consider YAGNI during unit testing, refactoring, and integration.

Composition Over Inheritance

Composition over inheritance allows you to design your types according to their functionality rather than nature.

In this scenario, developers prefer “composition” instead of “inheritance,” as inheritance makes your codes inflexible to later modifications.

Favor Readability

The “Favor Readability” principle encourages you to write codes, which are machine, as well as human-readable. So that everyone on the team can understand and work on the project without confusion.

Practice

Lastly, to write clean codes, you must practice with consistency to achieve your goals.

How Do We Clean Code at Slash?

A well-designed program can help businesses create a tremendous positive difference. However, this target is unachievable without high-quality coding and architecture.

At Slash we believe that there are multiple aspects involved in creating a masterpiece, but the most important one is using “Clean Codes” in your program. Therefore, before we start, we make sure to identify:

  •       Design pattern
  •       Framework to use
  •       Agreed standards and conventions
  •       Team members and tools to be used in the process
  •       Flexible architectural runway

Once we are over it, we use the KISS principle to make sure all the codes have the following traits:

Understandability and Readability

We use simple and understandable conventions, such as file naming, correlating functions, proper commenting whenever required, and more to make the project readable for the entire team. 

Maintainability

We prefer short codes for every function to make it easier to add a unit test on that particular file(S). For example, we use clean code rules like “one assert per test” and “independent unit test” with uncomplicated mocking options.

Changeability/Extensibility

Since we use the clean code approach, we ensure that our projects are easy to change and less complicated to test or add new features in the future. It helps our Slash team deal with regression errors in a much better way.

Besides the KISS principle, we also use principles like YAGNI, DRY, Composition over Inheritance, and Favor Readability to write clean codes.

Bottom Line

Clean code is an ideal way to develop highly-functioning programs, which could be tested and amended by every person on the team instead of a single author.

You should follow the rules and principles to get the desired results to write clean codes. And at Slash, we religiously work on principles like KISS, DRY, YAGNI, and more to make sure everyone on our team can transfer their capabilities into the program through their skills and experience without facing complications. This allows us to deliver top-notch quality software to our clients at the end of the day.

Tag Cloud

Agile - Agile Delivery - AI - amazonecommerce - Animal Framework - Attracting talent - Autonomous weapons - B2B - blockchain - businessbuilding - Business building - Clean code - Client consulting - cloud platform - Code Refactoring - coding - Company building - Computer Vision - Corporate startup - cryptocurrencies - de-risking business building - Deepfakes - Deep Learning - DeepMind - derisking business building - Design Research - Developer Path - DevOps - Digital Ownership - ecommerce - entrepreneurs - founder equality - founder equity - front end developer - Fullstack Engineer - Growth strategy - Hook model - Incubator - innovation - Manual Testing - Metaverse - methodology - Mobile Engineer - Natural Language Processing - NFT - NLP - online recruitment - playbooks - Podcast - product versions - project management - Prototyping early-stage ideas - Quantum Computing - Recruitments - Remote Work - Robotics - Sales machine - Self-Driving Cars - Serial entrepreneurs - Slash - Software Development - Software Engineering - teamwork - Tech Talks - tech teams - testing playbook - The Phoenix Project - Unit testing - VB Map podcast - Venture Building - Venture building strategies - Venture Capital - venturecapital - virtual retreat - Web3
This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our privacy policy.