Elijah's Blog

Refactoring is not just moving code around

Modern text editors and IDEs allow for easy ways to “refactor” the code we (or someone else) wrote. Is it really refactoring if you just move the code to a different place?

When we first learn to program, we’re taught to write procedural code. The first line executes, then the next line and so on. From there you’re introduced to functions which allow for reducing duplicative logic. After that we’re greeted with the wonderful world of OOP (object-oriented programming). We can get into an OOP vs functional programming debate later but since most popular languages are OO based I will base this post off of that.

The problem is that we fall into the trap of writing very procedural code that doesn’t take advantage of all that object-orientation gives us. However when we then “Right click > Refactor”, the code loses context and makes it even harder to read.

Here’s a nice example of some code that’s doing too much in the “get_context_data” function of a Django view.

From first glance, it looks like it’s a pretty straightforward refactor. Here’s a naive refactor:

Wow, look at that! “get_context_data” looks so much cleaner now! Or does it? At first glance the function does look a little nicer to deal with but it’s essentially still doing the same thing but now we have a bunch of useless private methods on the view that are only used within the “get_context_data” function.

Of course this is a simple example but the point is still there, we technically “refactored” this view and now the methods are contained elsewhere. However, let’s go back to our roots when we were taught when to create functions… when logic is duplicated. It makes no sense to move this to private methods if we’re only using this within this single function. It makes it harder to read because you have to jump between the main function and other private functions to know what’s fully going on.

What’s the better way to do this? Most modern web application frameworks come with ways to validate data being sent in. Django, for example, has forms which would be great for this.

In the future now, when we want to create a Comment with validation it’s all in one place so we can reuse it! And our “get_context_data” is even more simple now. What’s more, is that Django provides a “FormView” class that would make this even more simple.

Newer
Older