Favorite Refactoring Techniques: Extract Class
Naomi Dennis
Posted on January 16, 2020
The next refactoring technique we'll look at is extracting classes. Extracting classes has a similar thought process as extracting functions. In both cases, we are extracting behavior. For classes however, we are extracting sets of behavior or data.
Say we have the following code:
Multiple conditionals that test strings is a perfect code smell that indicates something can be refactored. In this situation, each string in the if statement
denotes a name for an item in a shop. The body of each statement is the same; it performs a transaction with said item, the item's value and the money of the person shopping. After the transaction is complete, #perform_transaction()
returns the amount of money the shopper has left. The only clause that is different is else
, which outputs a message to the shopper that the requested item is not found.
With this information we can split the behavior of the conditionals into two parts: performing a transaction when the item is in the shop and outputting a message when the item is not in the shop. Looking at the transaction portion, we can see that each item not only has its own name, but its own value. We can extract this into a ShopItem
class.
With this class, we can rewrite our if statement to more accurately portray the first portion, checking if the item is in the shop and outputting a message if it isn't. Before extracting the class, if the item wasn't apart of the conditional statement, it was seen as not being included in the shop. Now, we can create a list of items and if the item isn't in the list, we can output the message.
Now our code tells a concrete story. Search for an item. If the item is found, perform the transaction and return money to the shopper, if the item isn't found then tell the shopper the item isn't being sold.
As it stands, our if statement looks pretty good. However, we can make some minor changes to make it a bit better.
All in all, our code now looks this (Please note, # -- snip --
is code that wasn't mentioned.) :
Posted on January 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.