Refactoring code has become one of my favorite things to do as a developer. It can have a major impact on code cleanliness, readability, and maintainability.
In this post I’ll outline 6 refactoring patterns that I've found to be very useful and provide examples of each. Many are inspired by Martin Fowler's “Refactoring” book, which I highly recommend if you're looking to better understand common refactoring patterns.
(Side note: having good test coverage is also a CRUCIAL part of refactoring, but is outside the scope of this post.)
While the examples are in JavaScript, each pattern should be applicable to any programming language.
6. Introduce Object Parameter
When functions have multiple parameters, you start running into a few issues:
- For the function to work correctly, the order of parameters needs to be maintained.
- The names of the arguments (the actual values) passed to a function might not necessarily be the same as the parameter names, which makes searching for certain types of data/logic hard to do.
- Adding/removing parameters is a chore; each use of the function needs to be examined.
To make function parameters more manageable, this pattern involves converting a list of parameters into a single object. This forces consistent parameter naming across all functions, and makes the parameter order insignificant.
// Before
function sayHello(toName, punctuation, fromName) {
return `Hello, ${toName}${punctuation} From, ${fromName}.`
}
sayHello(customerName, end, myName);
// After
function sayHello({ toName, punctuation, fromName }) {
return `Hello, ${toName}${punctuation} From, ${fromName}.`
}
sayHello({ toName, punctuation, fromName });
5. Replace Anonymous Function with Expression
In JavaScript it’s a common practice to pass an anonymous function into an array method, such as .map, .reduce, or .filter. One issue I frequently see with these anonymous functions is they become complicated and difficult to parse; and since there is no name for the function it can be difficult to quickly understand the intent of the code.
Instead, I’ve found it helpful to extract these anonymous functions into a function expression, which makes it much easier to understand the intent (this also resembles "point-free style" a.k.a. "tacit programming".).
// Before
const activeUsers = users.filter((user) => {
if(user.lastPayment >= moment().startOf('week').toDate()) {
return true;
}
return false;
});
// After
const activeUsers = users.filter(hasUserPaidThisWeek);
function hasUserPaidThisWeek(user) {
if(user.lastPayment > moment().startOf('week').toDate() ) {
return true;
}
return false;
}
4. Replace Primitive with Object
Using a primitive value such as a string, number, or boolean is a common practice in many programming languages. But problems can arise when requirements and/or rules around these primitive values become more complex.
Instead of using an uncontrolled primitive value, a helpful practice is to wrap these primitives in an object, which will give you more control over how the value is consumed and modified.
// Before
let isLoading = true;
// some code...
loading = false;
const phone = '1 617 484-4049';
const price = 11;
// After
class LoadingStatus {
constructor(initialStatus) {
if(!this.statusSet.has(initialStatus)) {
throw new Error('Invalid status');
}
this._status = initialStatus;
}
statusSet = new Set(['loading', 'success', 'error', 'idle'])
get status() {
return this._status;
}
set status(status) {
if(!this.statusSet.has(status)) {
throw new Error('Invalid status');
}
this._status = status;
}
}
class Phone {
constructor(phone) {
this._phone = this.parsePhone(phone);
}
parsePhone(phone) {
const trimmedPhone = phone.trim();
if(phone.length !== 10) {
throw new Error('Invalid phone format');
}
const areaCode = trimmedPhone.slice(0,3);
const prefix = trimmedPhone.slice(3,7);
const lineNumber = trimmedPhone.slice(7, 10);
return { areaCode, prefix, lineNumber };
}
get areaCode() {
return this._phone.areaCode;
}
get formatted() {
const { areaCode, prefix, lineNumber } = this._phone;
return `${areaCode} ${prefix}-${lineNumber}`
}
...
}
class Price {
constructor(price) {
if(typeof price !== 'string') {
throw new Error('Invalid price');
}
if(!(price).match(/^[0-9]*$/)) {
throw new Error('Invalid price');
}
this._price = price;
}
get price() {
this._price;
}
}
3. Decompose Conditional
if/else statements can be a powerful tool when adding logic to your program. But they can also become unwieldy and confusing very quickly. One way to counteract this is by making the conditional logic easier to understand by extracting it into expressions that describe your intent.
// Before
if(user.hasEmail() && user.subscriptions.includes('email')) {
sendEmail(user);
}
// After
const isSubscribed = user.hasEmail() && user.subscriptions.includes('email');
if(isSubscribed) {
sendEmail(user);
}
2. Encapsulate Record (Bridge Pattern)
Most of the time building software involves consuming an existing API and/or providing your own. If your component is coupled with another API and that API changes, you may need to change your component as well; and this can sometimes be very time consuming.
Instead of coupling various APIs, I find it helpful to give each component an API that makes the most sense given its functionality, and adding a layer in between your component and any other API it is interacting with.
The Encapsulate Record refactoring pattern provides a great way to do this. This idea is also aligned with the Bridge pattern, which you can learn more about in "Design Patterns: Elements of Reusable Object-Oriented Software”.
// Before
const user = {
name: 'A Name',
favorites: {
color: 'blue',
food: 'pizza'
}
}
const UserComponent = (user) => (
<div>Name: {user.name} - Food: {user.favorites.food}</div>
);
UserComponent(user);
// After
const user = {
name: 'A Name',
favorites: {
color: 'blue',
food: 'pizza'
}
}
class User {
constructor(user) {
this._user = user;
}
get name() {
return this._user.name;
}
get food() {
return this._user.favorites.food;
}
}
const UserComponent = ({ name, food }) => (
<div>Name: {name} - Food: {food}</div>
);
UserComponent(new User(user));
1. Replace Conditional with Polymorphism
This is probably my favorite refactoring pattern. Several times it has helped me make confusing conditional logic much more readable and maintainable. And once logic is encapsulated in an object, you then have the flexibility to utilize other OOP design patterns to help achieve your goals.
The idea here is that instead of using a bunch of nested if statements in your code, you create objects that represent different "types", and give each type method(s) that are in charge of performing certain actions. Then, the application can simply call the same method on each type, and it’s up to the type to perform the action in the correct way.
// Before
if(user.favorites.food === 'pizza') {
sendPizzaEmail(user);
}
if(user.favorites.food === 'ice cream') {
sendIceCreamEmail(user);
}
// After
class PizzaUser {
constructor(user) {
this._user = user;
}
sendEmail() {
sendPizzaEmail(this._user);
}
}
class IceCreamUser {
constructor(user) {
this._user = user;
}
sendEmail() {
sendIceCreamEmail(this._user);
}
}
// this would create the appropriate user using the above classes
const user = getUser(userData);
user.sendEmail()
That's it! Happy refactoring!
Oldest comments (35)
So cool that more than one of your favorite refactoring strategies specifically clarify intent of the code! This is so fundamental to good code. Having code communicate intent is so much more important than having code that is a few lines shorter.
Exactly. Code is meant to be read by developers. Computers don't need to understand the code to execute it, they only have to follow instructions.
In example number five you use
hasUserPaidThisWeekbefore you assign it. Does it still work because of hoisting or something like that? Isn’t it a bit counterintuitive for people who read the code later?Hey Olivier, good catch! Yes that would be an issue - it would need to be a function declaration which would make it work via hoisting - I'll update the example (I'll admit I didn't actually run any of this code - it was more to illustrate the concepts - so there may be other runtime errors 😬).
But, I do think that declaring a function right after it's used is a good pattern. It follows the "Stepdown Rule" described in the book Clean Code. The idea is code should read like a top-to-bottom narrative, which I do kind of like. More examples here: dzone.com/articles/the-stepdown-rule
Generally I think the most important thing is that related functions live close together in the code...whether they are before or after is less of a concern.
I agree with you: the top-to-bottom narrative works better. Declaring such functions before they are used makes you wonder what’s happening, before you see the usage, when you read the code.
And I think the way the code is set now is good. My brain is not bothered by the function being declared after it’s used, even if it’s inside the current scope, because it’s a function declaration.
P.S. no worries about not having run the examples. You’re right, they’re illustrations. I was just curious about that particular case as I found it surprising (then again, programming languages are full of surprises) and I’m not a JS expert.
I love #6 (single object param) hands down one of my favorite coding practices! Works great with TS too :D
About #1, how do you implement "getUser(userData)"?
I'd probably use a switch statement to instantiate the appropriate user type - so something like:
Switch statement itself sometime bound you, we can use factory pattern to return the desire class object ;)
Thanks, Abdul. Could you provide an example of what the code might look like? Most factory functions I've seen still involve a switch statement or a series of if/else statements.
You might have included this snippet in the article
This is like the #1 #1 part of the article... You might want to add it.
Great article but for number 6, did you actually introduce an object parameter or am I reading that wrong, looks the same?
Thanks. I did, it's using object destructuring. They do look very similar but in the "after" version there are brackets around the params.
Ahhhh, thanks for the reply, learned 2 things from this article so! Many thanks again, great article
I would prefer to modify it to below. In this way the signature of method is clear. It also tells what kind of objects are acceptable. It also tells what kind of properties should be bound together as an object. The grouping of properties is domain specific. It is not anonymous.
I am taking clues from
Replace Anonymous Function with Expression.Note: I am not satisfied with
personPairas variable name. Feel free to suggest better variable name.A useful extension to (1) is the null pattern: providing an implementation which has the right methods but does nothing, instead of a conditional at the point of doing the required thing (eg a NoEmail user facade in the example above)
Thank you for the article!
I also like to store gigantic conditionals in a meaningful variable 😛
As for the example number 4, I suppose it's an implementation of the Value Object pattern, for elements that do not have a specific identity?
martinfowler.com/bliki/ValueObject...
Yes that looks very similar!
Nice article!
Great post, very interesting🙂 I can't say I'm very good at refactoring yet (I'm a beginner still) but I'd love to improve because clean and readible code literally makes me happy!