If you write 20 lines of code, then go to drink a cup of coffee and come back after 10 minutes, now you're maintaining the code you had written earlier. You might not remember what each part of the code does, you might need to read it again and recreate the whole picture in your mind. It doesn't matter how fast you write (being a programmer) because the time you spend on actual writing is, I would argue, far less than 10%, maybe even closer to 1% than the 10%.
I've noticed some uncomfortable habits people have when writing code, especially
if statements. Nested if statements.
Let's say you have the following piece of code:
- const condition_1 = ...;
- const condition_2 = ...;
- if(condition_1) {
-
- if(condition_2) {
-
- // do some stuff
- }
- }
Now let's have a closer look at this code. You have some 2 conditions (3 dots `...` represent some
boolean value extracted from another method, ternary operator etc).
What if I had more nested if's? What you can see here is the beginnig of so called 'Pyramid of Doom' where code marches to the right substantially fast (instead of downwards). My solution is this:
- const condition_1 = ...;
- const condition_2 = ...;
- if(!condition_1) {
-
- return; // end of story, nothing more to do here
- }
- if(!condition_2) {
-
- return; // end of story, nothing more to do here
- }
- // do some stuff
If you are able to grasp the most basic if-then event chains then you surely have noticed that
condition_2 cannot be executed if condition_1 isn't true, so everything after condition_1 doesn't matter if the condition equals false.
Obviously you might say 'Wait a second, but why are you returning? Shouldn't it all be wrapped in a function?'. It should indeed. My goal, when writing code, is to extract such nested
if statements into a separate function and then inside the function I can use return to immediately stop any further execution. This way you have more atomic code, easier to understand and also easier to read. Seems more logical to me than terribly looking nested conditions.
That's it for this post, I might add/edit something soon.
Brak komentarzy:
Prześlij komentarz