We already know the way but probably out of laziness we don’t follow it. It’s the most underestimated way of writing clean code and there is a misconception around it as well which is totally not true, I will come to that in a while. So, Its breaking down code into functions!
I agree, we do break down code into functions but not as often as needed. Let’s take this snippet below as our example which was literally a state of code in my previous company. Let’s go through each of the points below.
- It looks like it is restoring some kind of group. Even though its just 2 lines, it make sense to extract a method out of it.
- Initially this must have started with one flag. Developer might have thought why bother having a separate method for just 1 line of code! Then later another flag was added and then yet another.
- Seems like we are creating a drawer for a view. Why the heck high level code should care how it is getting initialised?
- Only after going through 4 lines of code, I am able to understand that we are notifying device information. I know 4 lines aren’t lot but such things can span 10s or even 100s of lines. Better extract out a method.
- Logging in a reading flow is very unproductive. Get a room!
- All listeners should be set separately in a method.
After doing some refactoring.
See how beautiful the high level code looks now. Its easy to scroll through without getting bogged down in unnecessary detail. A well defined method name doesn’t require any comment as well!!
- Don't pollute the reading flow with irky initialisation or complex conditions.
- Define short methods. They are easier to reason, flow is more obvious, scope is shorter, side effects are better visible.
- Make most read parts of your code declarative.
Its always easy to add two lines in an existing method. But do pay attention if the code above and below the added changes require its own space, if yes, then extract a method out of it. Every set of logic must be bundled properly in a method, that way future contributors will obligingly add changes in there respective methods.
Does an increase in the number of methods hurt performance, as many people claim? It’s a misconception and in almost all cases the impact is so negligible that it's not even worth worrying about. If you work on JVM based languages then let me tell you JVM is a wonderful piece of software (it will probably outlast Java!) that has many truly amazing runtime optimizations built-in. So, break it down...
Code is like humor. When you have to explain it, it’s bad. — Cory House