Have you ever seen a method with more than 500 lines of code? I have recently faced this challenge (lol). Alright, I won’t tell you guys how bad it is about the way which company manages to control code quality. In this article I’d like to talk about how to refactor the code.
All the time we can’t do the perfect refactor. Only doing good enough at the time we touch it. For example, here we can do first to extract the method to smaller one follow the S – single responsibility principle.
def filling_daily_value_sheet(client, daily_sensor_datas, end_time, sampled_dates, start_time, timezone, total_sensor_names, wb)
end
It’s not good enough because a method which has so many parameters like this which is hard for being used. We might get the order wrong and it will function incorrectly. So we continue to do like this.
def filling_daily_value_sheet(*args)
client, daily_sensor_datas, end_time, sampled_dates, start_time,
timezone, total_sensor_names, wb = args
end
Many thanks to ruby on rails because we can keep it short by using syntax “*args”. However, it’s still not good enough because we are still giving parameters in order. In case of many ones like this we use the “**args” syntax. It allows us to input parameters without considering the order.
def filling_daily_value_sheet(**args)
end
filling_daily_value_sheet(client: client, timezone: 'Singapore', start_time: Time.current)
But in case this method is still too long, we have to extract to three other methods which are involved in this method. We proceed next step to create a class Sheets::FillDailyValue with single responsibility. I repeated this principle many times because we want to limit the reason for changes in our code. We want to separate the one which will regularly change from the one staying the same. Because changes cause of issue, take costs and risks. If we have to change the code block, we limit it to one reason for change. If there are many reasons – responsibilities, we violate the Open/Close principle. No change, no issue. No code no issue.
module Sheets
class FillDailyValue
def call
end
end
end
The code need to be readable. So please be careful when we name any variables. Any words we put in the IDE as code, it must expose its meaning, giving understandable meaning for developers to maintain later. It must be direct, simple and tell “what” it does, not “how”. How to read code fast? By reading the methods and variables. We don’t dive deep on the implementation. We look at the class and its behaviours. We get to know what it does simply by the naming.