Have you ever gone back to your code of like some months and you're like "What does this function do?" because of the way functions and variables are named?. Well, you are not alone. Everybody has at one point or another in time experienced that.
Now how about working in a team and when it's time to review your colleague's code and you are like
Wow...looks frustrating...right?
Ever pondered on why it looks gibberish? Well, one of the reasons is that they are not readable.
Looking at the three(3) Pillars of Programming, your code should meet these criteria for it to be considered a good code:
- Readable
- Speed: It should be fast
- Memory: It should consume less memory during runtime
What does "Readable" mean?
Readability is the ease with which a reader can understand a written text.
In simple terms: It means making your written message legible or able to be deciphered
Now how do I make my code readable for myself and others?
Hmmm...how do I achieve this?
Here are some tips
1. Avoid NINJA CODE:
Hahahaha!!. That sounds confusing...right?. Yeah, I know the words, "Ninja Code" kinda sounds cool
Many try to follow ninja paths. Few succeed.
Examples of Ninja Code
- Writing shortcode
Bad code ❌
let amountInNaira = 100.00
let message = amountInNaira ? amountInNaira < 200.00 ? 'low balance' : 'processing payment...' : 'amount cannot be empty'
The above code can be better written this way:-
Good code ✅
let amountInNaira = 100.0;
let message;
// amountInNaira could be empty so we want to check if it was passed at all
if(amountInNaira) {
message = amountInNaira < 200.0 ? 'low balance' : 'processing payment...';
} else {
message = 'amount cannot be empty';
}
- Using abbreviations
writing a variable like this
Bad code ❌
let pOptions = ["card", "qr", "ussd"];
instead of:
Good code ✅
let paymentOptions = ["card", "qr", "ussd"];
will only make people end up racking their brains on what you mean as your program gets longer
2. Name function with action words
e.g
function joinTwoStrings(string1, string2){
//your code here
};
3. Add comments to code
// Function to add two strings
function joinTwoStrings(string1, string2){
//your code here
};
4. Your functions should only handle one job at a time
5. Break your code into chunks:
Nobody really wants to start reading a long code with up to a thousand(1000) lines. It gets frustrating and you might end up losing focus or interest or both.
Did you find my blog interesting and would love to drop your opinion? feel free to add yours in the comment section.
Thank you for reading my blog!!
I would love to connect with you on LinkedIn and Twitter. Also, feel free to subscribe to my newsletter for more content.