So I used to write codes like this:
And it is not only 3 layers, but many!
What are the issues of doing like this?
- Hard to follow: Huge blocks of code is very difficult to read.
- Difficult to maintain: After a time when coming back to the project again, I would not remember what I did because logic and functions overlapping each other everywhere. When I want to modify something or add new features it seems to be impossible.
- Looks really bad and stressful: Every time looking at this code I just want to ignore everything and go to sleep.
So after a time learning and practicing, I realized there are some ways to fix this:
Table of contents
1. Write tasks into functions
Each tasks can be written into a function. This prevents code duplication and easy to follow what tasks are called in which conditions.
So the key point here is not to overcomplicate your functions. Each function should only do one task, whether to validate or to get information. An ideal function is more or less 15 lines of code.
2. No need to include “else” all the time
Just get rid of them to have peace of mind if you don’t know what to do in the else case.
3. Returns early
Returns when the conditions do not match. It is better than setting up the whole conditions block and includes an else for the case that does not match.
So, instead of:
It can be like, just for example:
The benefits:
- Get rid of the annoying multi-layered nested functions.
- Tasks are written into functions so it is easier to debug or add features.
- Returns early so the program never has to execute codes before it realizes the case does not match.
- The code is cleaner and easier for team collaboration.
So that’s what I have learned. How about you? Please share your thoughts.
Leave a Reply