DEV Community

William Kennedy
William Kennedy

Posted on • Originally published at williamkennedy.ninja on

Good Citizen Refactoring

alt textPhoto by Cookie the Pom on Unsplash

No matter how much you try, refactoring is a hard sell. Why change code that works, so a developers job is more straightforward?

Refactoring is specific to software development as code is malleable. Users can’t see it, and it doesn’t affect them.

However, bad code can make life difficult for the next developer(or you in six months).

Yet, explaining the upsides of refactoring to anyone outside of your bubble is hard. So here is a compromise that can help. The next time you have to venture into a particular part of the codebase that’s unpleasant, see if you can apply a small change to make life better for you and your fellow developers.

Adopt a Good Citizen Culture at Work

Refactoring can be as simple as reducing copy and paste code. It can be as complex as creating new classes and modules for easier readability.

The next time you’ve wandered in the thick swathes of messy code, try to leave it in a better place for the next person.

Nothing needs to be said to anyone outside of the development team. It’s fast, clean and your fellow team will be happier.

Keep refactoring small

If you try to refactor too much, it may take focus away from the task.

Here is an example of refactoring I did once as part of a more significant task. As part of the task, I had to change the controller. Here is what it looked like

class PostsContoller < ApplicationController
  def edit
    @post = current_user.posts.find(params[:id])
    ...
  end

  def show
    @post = current_user.posts.find(params[:id])
    ...
  end

  def destroy
    @post = current_user.posts.find(params[:id])
    ...
  end

  def publish
    @post = current_user.posts.find(params[:id])
    ...
  end
end

Enter fullscreen mode Exit fullscreen mode

The above is an example; the real controller was 900 lines long and filled with conditional blocks. However, reducing the file was easy via extraction.

class PostsContoller < ApplicationController
  before_acton :set_post

  def edit
    ...
  end

  def show
    ...
  end

  def destroy
    ...
  end

  def publish
    ...
  end

  private 

  def set_post
    @post = current_user.posts.find(params[:id])
  end
end

Enter fullscreen mode Exit fullscreen mode

Now we have removed four lines of code by adding a before_action to the Rails controller. An experienced Rails developer would be familiar with the above pattern, but I’ve come across this more than once in a few different companies in real-world codebases.

This example was a simple refactor I did as part of another task. It required minimal testing but made life easier for the next person even if I left the company.

And that is what being a good citizen is all about.

Top comments (0)