A month of clean code

Jason McCreary - Nov 10 '17 - - Dev Community

Each week over the past month, I have posted before and after code samples calling out ways to clean up code. The response has been amazing, many receiving hundred of likes. While I will continue to share these weekly clean code samples, I wanted to collect the previous ones into a single post.

Breaking up long methods

In this first tweet a developer submitted a long Laravel controller action they wanted to clean up. At a high level the controller action handled a course enrollment request. At a low level the code had two paths for enrolling the user.

Before and after code cleanup of a long method

The main question to ask when evaluating a long method is who is responsible for this section of code? The answer to this question will help determine if the code can be moved elsewhere. In this case, the creation of the user could be moved to the model. We could also streamline the two paths by creating a private, conditional method. This method performs the branched logic of creating the user when necessary.

The result is a much smaller method. Some may argue we've simply moved the code. Nevertheless, the intent of our original method is more concise and its component parts are easy to follow. Both improve communicates - which is the measurement of clean code.

As pointed out on Twitter, the after code did have some mistakes, such as missing parameters to createUserIfUnauthenticated. However, these are trivial mistakes which do not change the clean up.


Leveraging objects

The second tweet was a Laravel controller action submitted by a developer. At a high level the controller action handled storing image uploads. At a low level the controller did everything itself - validation, image manipulation, storage.

Before and after code cleanup introducing objects

To clean this code, the strategy is to leverage other objects to handle all the things. A Laravel Form Request object could be used for the validation. We could adopt the Repository Pattern to introduce an object to coordinate the storage of an image.

Similar to before, the result is a smaller method. What's different in this case is leveraging existing objects available in the framework. We also applied a pattern that fit our code. Too often developers do this in reverse - fitting the code to a pattern. Letting a pattern emerge from the code is a far cleaner approach.


Cleaning conditional code

The third tweet focused on cleaning up the conditional code that forms most of our codebase. This has been the most popular cleanup so far. Likely because the fundamental code allows it to apply to many languages.

Before and after code cleanup of conditional code

Most of these cleanups fall under the third Writing Clean Code practice - avoid nested code. Anytime you want to clean up conditional code as yourself two questions:

  1. Can I return the condition directly?
  2. Does inverting the conditional logic improve communication?


Spotting primitive obsession

The fourth tweet focuses on spotting Primitive Obsession. Our obsession with using primitive data types often results in duplication of related code. It's not the exact same code which makes it harder to spot. Over time this code leaks through the system and becomes harder and harder to cleanup.

Before and after code cleanup of primitive obsession

The tips do not draw out some additional characteristics of these value objects. Almost as important as the encapsulation there provide is the fact that they are immutable. This limits state, making them relatively lightweight to add and even easier to maintain. For more detail and examples on Range, read RangeObject by Martin Fowler.

And yes, I would absolutely refactor limit() to utilize array filtering. This would be the next clean up:

function limit($items, Range $range)
{
    return array_filter($items, function ($item) use ($range) {
        return $range->includes($item);
    });
}
Enter fullscreen mode Exit fullscreen mode


Want more cleanup tips? Follow me on Twitter to get weekly tips or sign up for my upcoming field guide.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player