How to Organize and Structure Your Code?
These steps can change your perception of writing code!
Let's start with a statistic:
GitHub reports having over 73 million developers and more than 200 million repositories!!!
That means that coding has become an integral part of our lives. We write lots of lines of code every single day. There are a crazy amount of articles and youtube videos that show how to write and learn coding, and use modules, and even some show optimizing the code in terms of time and space complexity.
But when you are writing code for a product that involves multiple scripts and modules, the structure of the code becomes consequential. See, there is a simple concept! For every minute spent organizing, an hour gets earned.
Philosophy aside, lets us try to list down some points why exactly we need to spend time organizing our code.
1. Comprehensible
Organized code will make anyone understand the code easily. People can clearly understand the flow of the code. In this manner, even thousands of lines of code will seem like a story.
2. Easy Modification
Once the story in our mind is crystal clear, we can add, remove, modify, and optimize code very effortlessly. It will not only reduce the time, each time you have a clear picture of where to make changes in code.
3. Bug Fixing in Minutes
It can be a pain. The code can be written in minutes. But identifing and fixing a bug can take a while, and sometimes much more than a while. But, I guarantee that organized code will help you deal with it to a great extent.
So, now we understand the need for organization in code is vital. But the question persists how could we organize? Therefore, here are some great tips that will help you structure your code.
1. THE PLAN
Plan before you write, make your code bright
Every time you plan to write code, make sure you plan first. Thinking and writing code simultaneously will make you think that you are writing code faster. But in long run, that code will take more time to comprehend and modify. To start, you can ask the following questions:
- What inputs do I have?
- What should be the flow of my code?
- How many different functions do I require?
- What is the output?
For example, let us say given the length and breath of a rectangle we need find the harmonic mean of area and perimeter of rectangle. This logic behind the problem is easy. But there exists different versions code.
First comes the plan, which is quite easy
Lets start coding and develop the first code:
def calculate_harmonic_mean(length, breath):
perimeter = 2*(length + breath)
area = length * breath
hm = (area * perimeter) / (area+perimeter)
return hm
2. THE TRIM
Sticks in a bundle can’t be broken but sticks taken singly can be easily broken,
And we need to break code!!!
In this step, we will see how we can functionalize a code. The idea is to trim a big piece of code into a smaller sub-function. These small functions will increase comprehensivity. Also, debugging becomes easy as we know which functions are working and who are creating the issue.
Ideally, there should only be 2–6 lines in each function. So, every time you debug, you will know the exact line that needs to get fixed.
How to functionalize?
When we were planning the code structure, we created some steps. Hence, for each step, we can create one or more functions. That is why we have done planning in the first place.
So, according to our plan, we had two different steps to calculate area and perimeter. Therefore, we will create separate functions for each step.
Hence, now the code becomes:
def get_perimeter(length, breath):
perimeter = 2*(length + breath)
return perimeterdef get_area(length, breath):
area = length * breath
return areadef calculate_harmonic_mean(length, breath):
perimeter = get_perimeter(length, breath)
area = get_area(length, breath)
hm = (area*perimeter) / (area+perimeter)
return hm
It seems that we have increased the length of the code. But, if you see the big picture, this just a simple function. When you would be developing a pipeline or product, functionalizing will surely a greater impact.
3. DO NOT COPY
Never repeat your code!
This should be the bottom line before you write any code. There should be NO repetition within your code. Every time you want to write same line of code, you can easily functionalize it.
The biggest benefit of having this is to make code changing super easy. If the same line of code is present in project in multiple time, you can miss some occurrence when you are modifying the code.
Let us now also functionalize the calculation of the harmonic mean of length and breath. So, instead of writing the harmonic mean formula twice we can functionalize it.
def get_perimeter(length, breath):
return 2*(length + breath)
def get_area(length, breath):
return length * breathdef calculate_harmonic_mean(a, b):
return (a*b) / (a+b)def calculate_harmonic_mean(length, breath):
perimeter = get_perimeter(length, breath)
area = get_area(length, breath)
hm = calculate_harmonic_mean(area, perimeter)
hm2 = calculate_harmonic_mean(length, breath)
return hm, hm2
We have used the same function twice. Hence if in future, we want to calculate average instead of harmonic mean, we could simply change one function rather than changing two lines of code.
4. Small yet effective Tips
The above three methods would greatly affect your quality of code. Addition to them, there are some good practice that can also be follow. This is not related to structure of code but it will affect the comprehensivity.
The below methods are not necessary at all. But I highly recommend that before using the above methods, you should first try these. These are very basic methods which are taught during the initial lectures of laungaue course in universites.
A. Logging / Comments
It is always advised to add comments in you code. Also, when your code is part of pipe line, logging becomes really important.
Comments help you to understand what those code of lines do! You can add the logic or the purpose of code in comments.
Logging in one of the most import module for any pipeline. According to me, logging will help you in these following ways:
- Logging is way to interact with code without even reading the code. If the logging statements are present at correct or required positions, you can effortlessly infer code from its log file.
- Logging will help you know uptil where your code ran, in cases of bugs. You can also print the exact error (Exception) in logs too or the line where you code failed. I think this is a great tool.
B. Global Package
There will be always some variable that we need to call frequently. These can be some contant value, some directory path, or values that are configured in databases.
To elaborate, usually developers use SQL table to make code configurable. Now, these variable are fixed during the code run. Hence, instead of querying database multiple times, we can initialize a global variable.
This will not only reduce the load on SQL database, but will also decrease the run time of you code.
C. Intellegent Variable Name
I will not waste our time in this section. This is very straightforward. The name of variables should be meaningful. They should be named for the purpose they are being used.
Naming variable intelligently will not only help you gain insight, it will be more painless to track them through the code.
D. Varibale = Value
When you call a function, there could be two ways:
perimeter = get_perimeter(length, breath)
perimeter = get_perimeter(length=length, breath=breath)
I prefer to use the second one. As the function we used is very small, but when we are passing 10+ parameters to a function, this methods make code quite handy.
Summary
Writing, reading, and modifying code can be a pain. The only way to reduce this effort is to make your code more organized. And organization and optimization are two different kinds of worlds. And what I have talked about in this article is all about organization.
These were the tips that we discussed:
1. THE PLAN: Create a plan before you start writing code
2. THE TRIM: Try to create small functions
3. DO NOT COPY: Never repeat you code
4. OTHER SMALL TIPS
A. Logging and Comments: Add logs and comments to you code
B. Global Package: Define a global package in you repository
C. Variable Naming: Name your Variable wisely
D. Calling a function: Call your function with proper parameters
I hope these tips will help you write more organized and effective code. I believe bug fixing will not be a pain anymore. And whenever a new team member joins your project, he/she can ramp up quickly.
Also, please let me know what techniques you use to write more organized and structured code. I will be happy to read your comments.