8 Ways to Make Your Code Look Cleaner and Better👀!

8 Ways to Make Your Code Look Cleaner and Better👀!

Written by Arindol Sarkar on Feb 11th, 2022 Views Report Post

1. Indentation and Formatting :

Use of Proper indentation makes your code look a lot cleaner and organized. It helps in identifying blocks. Sometimes maintaining proper indentation isn't possible, so it's better to format your code via third party apps.

\\unformatted code
func main() {
a:=10
b:=5
if(a<b){
fmt.Printf("%v is greater than %v",b,a)
}else{
fmt.Printf("%v is greater than %v",a,b)
}
}
\\formatted code
func main() {
    a := 10
    b := 5
    if a < b {
        fmt.Printf("%v is greater than %v", b, a)
    } else {
        fmt.Printf("%v is greater than %v", a, b)
    }
}

The above code looks cleaner and better than the first one.

2. Use of commands and proper doc strings :

It is better to use command lines while declaring loops or using of conditional statements. This helps you to understand what you are doing, or even someone else who is reviewing your code. Use of doc strings and multiple line commends under methods, structs, or function helps in proper managing of your code.

package main

import "fmt"

type Event struct {
    Name string 
    date string 
    daysCelebratedinYear int
}
/*
Event struct declares the name of the Event, the date as string, and the duration of the event
*/
type IndianFestival struct{
    Event
    celebratedIn string
    isWorldWide bool
}
/*
IndianFestival is a struct that accepts which country is the festival celebrated
and asks if the festival is world wide. It calls event struct to receive it's values
*/

func main() {
    durgaPuja := IndianFestival{Event{"Durga Puja","None",4},"Bengal",true} //declaring a struct
    fmt.Printf("One of the most popular Indian Festival is %v",durgaPuja) //printing using a format

}

3. Proper Use of Data Structures :

Data structures are used to implement the physical forms of abstract data types. Data structures are a crucial part of designing efficient software. They also play a critical role in algorithm design and how those algorithms are used within computer programs. We must understand when to use arrays, pointers, slices, reference data types, etc.

4. Make proper flow chart of Your Project :

There are times when making new projects seems tough and stressful. You maybe frustrated about the syntactical error, or logical error. While you are building a new project, your focus must be more on problem solving than worrying about syntax. Hence you can use a flow chart, to plan out what logic are you going to apply. Use of proper flow charts really reduce time of coding. Example of a simple flow chart :

5.Implementation of proper functions :

Sometimes when you are migrating from older languages to a newer one, you maybe unfamiliar with some of the functions. Like in your old language, you may had to do some stuffs manually, but in your new language, you have certain functions to do so. Like suppose you want to sort a group of elements, you may use your conventional methods to sort it out, but in languages like go, package like sort., automatically arranges the element based on the function used. Here's an example :

package main

import "fmt"

func main() {
	a := [10]int{45, 23, 74, 3, -32, 43, 839, 32, 9, 0} 
/*
Sorting without using proper methods
*/
	for i := 0; i < len(a)-1; i++ {
		for j := i + 1; j < len(a); j++ {
			if a[i] > a[j] {
				t := a[i]
				a[i] = a[j]
				a[j] = t
			}
		}

	}
	fmt.Println(a)
}


Output :

[-32 0 3 9 23 32 43 45 74 839]
package main

import (
	"fmt"
	"sort"
)

func main() {
	a := []int{45, 23, 74, 3, -32, 43, 839, 32, 9, 0}
	sort.Ints(a) // sorting in 1 line using proper function
	fmt.Print(a)
}


Output

[-32 0 3 9 23 32 43 45 74 839]

That brings us to our next point.

6. Don't reinvent the Wheel :

This might sound fancy, but actually might be a life saver. When you are doing a project, you may start from the scratch. However, starting from scratch is time consuming and raging. Instead there are many open source library available to get started. Libraries create functions, which you can use to reduce your code, and thoughts while working on the project. It takes away many things to worry about. Python, Javascript, Java, Go has many such popular libraries.

7. Modularization of code :

Modular code is a code that is highly organized. To organize code based on task means that the programmer can organize each piece of code based on what it does. Then, it can easily find or reference that code based on the organization scheme. Furthermore, other programmers working on the code can follow it's organization scheme to read the code as well. This optimizes code for use among multiple developers with less trouble.

8. Use proper language feature:

Using proper language feature in languages is very important. When we are new to a language or migrated to one, we tend to find similarities with their previous language, and implement the same logic. This will work most of the time but sometimes it's better to follow language feature than the algorithm. This makes the program smaller and simple. Here's an simple example :

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
# generate fibonacci sequence
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

Output :

How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

Now here's a better method :

fibList = [0,1]
n = int(input("Enter no. of iterations"))
for i in range(1, n-1):
    fibList.append(fibList[i] + fibList[i-1])
print(fibList)

Output

Enter no. of iterations7
0
1
1
2
3
5
8

Thanks for Reading,

If you like my content do follow me in Twitter.

Until Next Time !

Arindol Sarkar.

Comments (0)