Stop passing too many parameters
Stop passing too many parameters
What I saw in LinkedIn today and made me realize is passing too many parameters to methods means bad code. It's really easy to pass in multiple parameters to a method but with increasing number of parameters it becomes harder to read and maintain.
To solve this issue, there is Parameter Object. I found a great example to understand this as well. Imagine having to carry bunch of stuffs, like books, pens, umbrella, wallet, cards, etc. You can't carry all of them in your hands.Some may say you can and if you do, you will be same as methods carrying multiple parameters. Once stuffs increases, you can't find the items you need without dropping things. This is similar to it being harder to read code once parameter numbers increase. But if you carry a bag(Object), you can fit everything inside. It's easier to take out the stuff you need without making a mess. The Object acts like a bag for data.
So, how to make a Parameter Object?
Suppose you have a method that updates user's preferences. It has multiple parameters like username, email, phone, age, language, theme, notifications and many more. The simple way to do it would be as below:
function updatePreferences(
username,
email,
phone,
age = 18,
language = "en",
theme = "light",
notifications = true
) {
// Update user preferences with multiple parameters
}The good way to do this would be to create a Parameter Object and pass it to the method as below:
class UserPreferences {
constructor(
username,
email,
age = 18,
language = "en",
theme = "light",
notifications = true
) {
this.username = username;
this.email = email;
this.age = age;
this.language = language;
this.theme = theme;
this.notifications = notifications;
}
}
function updatePreferences(userPrefs) {
// Update user preferences based on the provided Parameter Object
}And it can be even broken down into many objects.
class UserDetails {
constructor(username, email, age = 18) {
this.username = username;
this.email = email;
this.age = age;
}
}
class AppPreferences {
constructor(language = "en", theme = "light", notifications = true) {
this.language = language;
this.theme = theme;
this.notifications = notifications;
}
}
function updatePreferences(userDetails, appPreferences) {
// Update user preferences based on the provided Parameter Objects
}
const userDetails = new UserDetails("john_doe", "john@example.com", 21);
const appPreferences = new AppPreferences("fr", "dark", false);
updatePreferences(userDetails, appPreferences);Each class now has single responsibility of maintaining one aspect of data(SRP). This makes it easier to read and maintain.