Here is a good example of clean coding and refactoring. Even for such a small piece of code, refactoring is always good (if done properly of course).
Refactoring and clean coding are not separate tasks that you should do when you have extra time or when your boss gives you permission to do it. They are a part of the software development (or coding) process. When you write code, you should always pay attention to clean coding and as you write the code, if something doesn’t feel OK, you should immediately refactor and get rid of the problem.
I’ve worked on methods with 400+ lines of code, crazy if statements that no one understands, code with indentation so deep that it doesn’t make sense anymore and many unsolved mystery bugs. I witnessed some cases where the code does not do what it was supposed to do with extras like no logging, no errors on sentry, no nothing. This one time the team lead called me to fix the situation. The code was the one I just described and what was expected of me? Solve the problem just by looking at 400 lines of code. We didn’t even have the slightest clue of what was happening. Of course I knew that was not possible at that very moment, I told him we needed logging to figure it out but the response was something like: “You are a senior developer, you should be able to solve it.”.
I have no idea why the culture around coding is so limited and narrow for most of the coders. I think it is probably about the quality of software being so abstract and hard to measure. Anyone can code something that works but most of the coders, educated or not, cannot code high quality code. It is something like learning to read and write your mother language. We all learn to read and write in elementary school but most people, even in adulthood, have a hard time to write a good sentence. For example, let’s assume that I want to express to you that tonight I want to eat a hamburger. I can do this in many many ways but the most straightforward way is like this:
“Tonight I want to eat a hamburger.”
This is really easy to understand, very simple. Now imagine I am really really bad at expressing myself, like a really bad programmer. I will say something like this:
“After sun goes away today I want put in my stomach meat between bread.”
Here I am trying to express the same thing but it’s longer and takes more time to understand. I can go on like this as much as I want to. Here’s one more example:
“After 6 hours after hour 16:00 minus 1 hour I want to make my stomach full with cooked meat between two pieces of bread.”
So now imagine a program with 50000 lines of these. That’s what bad code looks like and that code needs refactoring.